diff --git a/.gitattributes b/.gitattributes index 4db3926d36ff5c4dccac5f7015fc25e439a80811..50de509022a74c22b3282bcc4df30db9c2bcd413 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1308,3 +1308,231 @@ platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-pack platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/__pycache__/qdrant_remote.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/conversions/__pycache__/conversion.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/http/models/__pycache__/models.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/local_collection.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/libjemalloc.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/jars/ray_dist.jar filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/worker.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/__pycache__/typing_extensions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/frozenlist/_frozenlist.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/_multidict.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/thirdparty/pynvml/__pycache__/pynvml.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/gcs/gcs_server filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/raylet/raylet filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/__pycache__/compiled_dag_node.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/thirdparty_files/psutil/_psutil_linux.abi3.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/__pycache__/cluster.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/asyncio/__pycache__/cluster.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/commands/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/test_regex.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/_emoji_codes.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/console.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dfitpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_lu_cython.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_expm.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_schur_sqrtm.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_hausdorff.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ellip_harm_2.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_gufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_specfun.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_special_ufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_test_internal.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs_cxx.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/cython_special.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_biasedurn.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_sobol.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmc_cy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmvnt_cy.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats_pythran.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_bsplines.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_interpolate.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/__pycache__/_optimize.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_filter_design.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_ltisys.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_short_time_fft.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_signaltools.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_filter_design.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_signaltools.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_spectral.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_dpropack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_spropack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_zpropack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpack.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/__pycache__/distance.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rigid_transform.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rotation.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/tests/__pycache__/test_distance.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_basic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_stats_py.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_continuous_distns.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distn_infrastructure.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_resampling.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distribution_infrastructure.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_morestats.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_mstats_basic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_multivariate.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_qmc.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_rcont/rcont.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_continuous.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_hypotests.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_morestats.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_mstats_basic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_resampling.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentence_transformers/__pycache__/SentenceTransformer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/_loss/_loss.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hierarchical_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_common.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_elkan.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_lloyd.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_minibatch.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/_svmlight_format_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_cdnmf_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_online_lda_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_gradient_boosting.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_cd_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sag_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sgd_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/manifold/_barnes_hut_tsne.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_dist_metrics.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_pairwise_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_ball_tree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_kd_tree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_quad_tree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_liblinear.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm_sparse.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_criterion.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_partitioner.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_splitter.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_tree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_utils.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_cython_blas.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_fast_dict.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_isfinite.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_typedefs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/arrayfuncs.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_random.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_seq_dataset.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_vector_sentinel.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/murmurhash.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/sparsefuncs_fast.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_linkage.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_reachability.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_tree.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/compose/tests/__pycache__/test_column_transformer.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/__pycache__/_forest.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_gradient_boosting.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_predictor.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/histogram.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-312-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_coordinate_descent.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_ridge.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text +platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/tests/__pycache__/test_logistic.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/local_collection.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/local_collection.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1fb71e86d6690a1cb7fedb38af41cc3ad23c404 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/local_collection.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0699ba907a98774436919cc12434144f29276d982303d837bec80896ed1ac1f6 +size 117154 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/multi_distances.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/multi_distances.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b15a41f24a166234420876c8469e402426c43f32 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/multi_distances.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/order_by.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/order_by.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88cbb5c75290c7a30403e650916f7370a0b9dff3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/order_by.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_filters.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_filters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b66b6157d624e441f285a71a99028a5971a3f7d0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_filters.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_value_extractor.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_value_extractor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1443e5e0ca4e72461530d9b19eeb217ca9c339d8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_value_extractor.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_value_setter.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_value_setter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c60ce45dd75f8fb4aa881384b0ae419e70e1f6fd Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/payload_value_setter.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/persistence.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/persistence.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..baedcb5a4d6904f43df0fb3146e453e3e0cdc5ae Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/persistence.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/qdrant_local.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/qdrant_local.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7a026276480896e77b167d3a7bca7e4c958c4e43 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/qdrant_local.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/sparse.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/sparse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b9839f665606338d9f3fddffc640233b008a61d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/sparse.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/sparse_distances.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/sparse_distances.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..406398838b0eca909bb34a9fe40c7792694809a7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/__pycache__/sparse_distances.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03455438b780c61ef6c3c9ffa69770d08ece5e17 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_datetimes.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_datetimes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea302746379a39506db79c032f18278fc1f1f9f3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_datetimes.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_distances.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_distances.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b5630cd2206cf390102b34f3cd5319114d95368 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_distances.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_payload_filters.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_payload_filters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aeaa72a249dfac77551fa9f4e2389db69e8bd72b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_payload_filters.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_payload_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_payload_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ecb3351555a31b0396b00a8cf88068d4f8a91ce Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_payload_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_referenced_vectors.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_referenced_vectors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed3f47f288640be3df1b24ee4684ab12a2a1fcf2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_referenced_vectors.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_vectors.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_vectors.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f39bc9d93c5d317a914a1567831cc504e001aa6c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/__pycache__/test_vectors.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_datetimes.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_datetimes.py new file mode 100644 index 0000000000000000000000000000000000000000..9e25f17bbd678474bef17d7fe61c0cffc7b9f6ec --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_datetimes.py @@ -0,0 +1,57 @@ +from datetime import datetime, timedelta, timezone + +import pytest + +from qdrant_client.local.datetime_utils import parse + + +@pytest.mark.parametrize( # type: ignore + "date_str, expected", + [ + ("2021-01-01T00:00:00", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ("2021-01-01T00:00:00Z", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ("2021-01-01T00:00:00+00:00", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ("2021-01-01T00:00:00.000000", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ("2021-01-01T00:00:00.000000Z", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ( + "2021-01-01T00:00:00.000000+01:00", + datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(hours=1))), + ), + ( + "2021-01-01T00:00:00.000000-10:00", + datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(hours=-10))), + ), + ("2021-01-01", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ("2021-01-01 00:00:00", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ("2021-01-01 00:00:00Z", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ( + "2021-01-01 00:00:00+0200", + datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(hours=2))), + ), + ("2021-01-01 00:00:00.000000", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ("2021-01-01 00:00:00.000000Z", datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone.utc)), + ( + "2021-01-01 00:00:00.000000+00:30", + datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(minutes=30))), + ), + ( + "2021-01-01 00:00:00.000009+00:30", + datetime(2021, 1, 1, 0, 0, 0, 9, tzinfo=timezone(timedelta(minutes=30))), + ), + # this is accepted in core but not here, there is no specifier for only-hour offset + ( + "2021-01-01 00:00:00.000+01", + datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(hours=1))), + ), + ( + "2021-01-01 00:00:00.000-10", + datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(hours=-10))), + ), + ( + "2021-01-01 00:00:00-03:00", + datetime(2021, 1, 1, 0, 0, 0, tzinfo=timezone(timedelta(hours=-3))), + ), + ], +) +def test_parse_dates(date_str: str, expected: datetime): + assert parse(date_str) == expected diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_distances.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_distances.py new file mode 100644 index 0000000000000000000000000000000000000000..ba4dc7ed62ee5cc83e74824b4f689883807e656b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_distances.py @@ -0,0 +1,57 @@ +import numpy as np + +from qdrant_client.http import models +from qdrant_client.local.distances import calculate_distance +from qdrant_client.local.multi_distances import calculate_multi_distance +from qdrant_client.local.sparse_distances import calculate_distance_sparse + + +def test_distances() -> None: + query = np.array([1.0, 2.0, 3.0]) + vectors = np.array([[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]) + assert np.allclose(calculate_distance(query, vectors, models.Distance.DOT), [14.0, 14.0]) + assert np.allclose(calculate_distance(query, vectors, models.Distance.EUCLID), [0.0, 0.0]) + assert np.allclose(calculate_distance(query, vectors, models.Distance.MANHATTAN), [0.0, 0.0]) + # cosine modifies vectors inplace + assert np.allclose(calculate_distance(query, vectors, models.Distance.COSINE), [1.0, 1.0]) + + query = np.array([1.0, 0.0, 1.0]) + vectors = np.array([[1.0, 2.0, 3.0], [0.0, 1.0, 0.0]]) + + assert np.allclose( + calculate_distance(query, vectors, models.Distance.DOT), [4.0, 0.0], atol=0.0001 + ) + assert np.allclose( + calculate_distance(query, vectors, models.Distance.EUCLID), + [2.82842712, 1.7320508], + atol=0.0001, + ) + + assert np.allclose( + calculate_distance(query, vectors, models.Distance.MANHATTAN), + [4.0, 3.0], + atol=0.0001, + ) + # cosine modifies vectors inplace + assert np.allclose( + calculate_distance(query, vectors, models.Distance.COSINE), + [0.75592895, 0.0], + atol=0.0001, + ) + + sparse_query = models.SparseVector(indices=[1, 2], values=[1, 2]) + sparse_vectors = [models.SparseVector(indices=[10, 20], values=[1, 2])] + + assert calculate_distance_sparse(sparse_query, sparse_vectors) == [np.float32("-inf")] + + sparse_vectors = [ + models.SparseVector(indices=[1, 2], values=[3, 4]), + models.SparseVector(indices=[1, 2, 3], values=[1, 2, 3]), + ] + assert np.allclose( + calculate_distance_sparse(sparse_query, sparse_vectors), [11.0, 5], atol=0.0001 + ) + + multivector_query = np.array([[1, 2, 3], [3, 4, 5]]) + docs = [np.array([[1, 2, 3], [0, 1, 2]])] + assert calculate_multi_distance(multivector_query, docs, models.Distance.DOT)[0] == 40.0 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_payload_filters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_payload_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..baf0c7a0b2bdb37f8c9f90861c61701cfe4a22ae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_payload_filters.py @@ -0,0 +1,189 @@ +from qdrant_client.http.models import models +from qdrant_client.local.payload_filters import check_filter + + +def test_nested_payload_filters(): + payload = { + "country": { + "name": "Germany", + "capital": "Berlin", + "cities": [ + { + "name": "Berlin", + "population": 3.7, + "location": { + "lon": 13.76116, + "lat": 52.33826, + }, + "sightseeing": ["Brandenburg Gate", "Reichstag"], + }, + { + "name": "Munich", + "population": 1.5, + "location": { + "lon": 11.57549, + "lat": 48.13743, + }, + "sightseeing": ["Marienplatz", "Olympiapark"], + }, + { + "name": "Hamburg", + "population": 1.8, + "location": { + "lon": 9.99368, + "lat": 53.55108, + }, + "sightseeing": ["Reeperbahn", "Elbphilharmonie"], + }, + ], + } + } + + query = models.Filter( + **{ + "must": [ + { + "nested": { + "key": "country.cities", + "filter": { + "must": [ + { + "key": "population", + "range": { + "gte": 1.0, + }, + } + ], + "must_not": [{"key": "sightseeing", "values_count": {"gt": 1}}], + }, + } + } + ] + } + ) + + res = check_filter(query, payload, 0, has_vector={}) + assert res is False + + query = models.Filter( + **{ + "must": [ + { + "nested": { + "key": "country.cities", + "filter": { + "must": [ + { + "key": "population", + "range": { + "gte": 1.0, + }, + } + ] + }, + } + } + ] + } + ) + + res = check_filter(query, payload, 0, has_vector={}) + assert res is True + + query = models.Filter( + **{ + "must": [ + { + "nested": { + "key": "country.cities", + "filter": { + "must": [ + { + "key": "population", + "range": { + "gte": 1.0, + }, + }, + {"key": "sightseeing", "values_count": {"gt": 2}}, + ] + }, + } + } + ] + } + ) + + res = check_filter(query, payload, 0, has_vector={}) + assert res is False + + query = models.Filter( + **{ + "must": [ + { + "nested": { + "key": "country.cities", + "filter": { + "must": [ + { + "key": "population", + "range": { + "gte": 9.0, + }, + } + ] + }, + } + } + ] + } + ) + + res = check_filter(query, payload, 0, has_vector={}) + assert res is False + + +def test_geo_polygon_filter_query(): + payload = { + "location": [ + { + "lon": 70.0, + "lat": 70.0, + }, + ] + } + + query = models.Filter( + **{ + "must": [ + { + "key": "location", + "geo_polygon": { + "exterior": { + "points": [ + {"lon": 55.455868, "lat": 55.495862}, + {"lon": 86.455868, "lat": 55.495862}, + {"lon": 86.455868, "lat": 86.495862}, + {"lon": 55.455868, "lat": 86.495862}, + {"lon": 55.455868, "lat": 55.495862}, + ] + }, + }, + } + ] + } + ) + + res = check_filter(query, payload, 0, has_vector={}) + assert res is True + + payload = { + "location": [ + { + "lon": 30.693738, + "lat": 30.502165, + }, + ] + } + + res = check_filter(query, payload, 0, has_vector={}) + assert res is False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_payload_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_payload_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..bb76621f9f72d6dd0f78ffd118a536acae651262 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_payload_utils.py @@ -0,0 +1,549 @@ +from typing import Any + +import pytest + +from qdrant_client.local.json_path_parser import ( + JsonPathItem, + JsonPathItemType, + parse_json_path, +) +from qdrant_client.local.payload_value_extractor import value_by_key +from qdrant_client.local.payload_value_setter import set_value_by_key + + +def test_parse_json_path() -> None: + jp_key = "a" + keys = parse_json_path(jp_key) + assert keys == [JsonPathItem(item_type=JsonPathItemType.KEY, key="a")] + + jp_key = "a.b" + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="b"), + ] + + jp_key = 'a."a[b]".c' + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="a[b]"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="c"), + ] + + jp_key = "a[0]" + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=0), + ] + + jp_key = "a[0].b" + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=0), + JsonPathItem(item_type=JsonPathItemType.KEY, key="b"), + ] + + jp_key = "a[0].b[1]" + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=0), + JsonPathItem(item_type=JsonPathItemType.KEY, key="b"), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=1), + ] + + jp_key = "a[][]" + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.WILDCARD_INDEX, index=None), + JsonPathItem(item_type=JsonPathItemType.WILDCARD_INDEX, index=None), + ] + + jp_key = "a[0][1]" + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=0), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=1), + ] + + jp_key = "a[0][1].b" + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=0), + JsonPathItem(item_type=JsonPathItemType.INDEX, index=1), + JsonPathItem(item_type=JsonPathItemType.KEY, key="b"), + ] + + jp_key = 'a."k.c"' + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="k.c"), + ] + + jp_key = 'a."c[][]".b' + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="c[][]"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="b"), + ] + + jp_key = 'a."c..q".b' + keys = parse_json_path(jp_key) + assert keys == [ + JsonPathItem(item_type=JsonPathItemType.KEY, key="a"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="c..q"), + JsonPathItem(item_type=JsonPathItemType.KEY, key="b"), + ] + + with pytest.raises(ValueError): + jp_key = 'a."k.c' + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = 'a."k.c".' + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = 'a."k.c".[]' + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a.'k.c'" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a[" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a]" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a[]]" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a[][]." + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a[][]b" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = ".a" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a[x]" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = 'a[]""' + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = '""b' + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "[]" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a[.]" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = 'a["1"]' + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a..c" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a.c[]b[]" + parse_json_path(jp_key) + + with pytest.raises(ValueError): + jp_key = "a.c[].[]" + parse_json_path(jp_key) + + +def test_value_by_key() -> None: + payload = { + "name": "John", + "age": 25, + "counts": [1, 2, 3], + "address": { + "city": "New York", + }, + "location": [ + {"name": "home", "counts": [1, 2, 3]}, + {"name": "work", "counts": [4, 5, 6]}, + ], + "nested": [{"empty": []}, {"empty": []}, {"empty": None}], + "the_null": None, + "the": {"nested.key": "cuckoo"}, + "double-nest-array": [[1, 2], [3, 4], [5, 6]], + } + # region flat=True + assert value_by_key(payload, "name") == ["John"] + assert value_by_key(payload, "address.city") == ["New York"] + assert value_by_key(payload, "location[].name") == ["home", "work"] + assert value_by_key(payload, "location[0].name") == ["home"] + assert value_by_key(payload, "location[1].name") == ["work"] + assert value_by_key(payload, "location[2].name") is None + assert value_by_key(payload, "location[].name[0]") is None + assert value_by_key(payload, "location[0]") == [{"name": "home", "counts": [1, 2, 3]}] + assert value_by_key(payload, "not_exits") is None + assert value_by_key(payload, "address") == [{"city": "New York"}] + assert value_by_key(payload, "address.city[0]") is None + assert value_by_key(payload, "counts") == [1, 2, 3] + assert value_by_key(payload, "location[].counts") == [1, 2, 3, 4, 5, 6] + assert value_by_key(payload, "nested[].empty") == [None] + assert value_by_key(payload, "the_null") == [None] + assert value_by_key(payload, 'the."nested.key"') == ["cuckoo"] + assert value_by_key(payload, "double-nest-array[][]") == [1, 2, 3, 4, 5, 6] + assert value_by_key(payload, "double-nest-array[0][]") == [1, 2] + assert value_by_key(payload, "double-nest-array[0][0]") == [1] + assert value_by_key(payload, "double-nest-array[0][0]") == [1] + assert value_by_key(payload, "double-nest-array[][1]") == [2, 4, 6] + # endregion + + # region flat=False + assert value_by_key(payload, "name", flat=False) == ["John"] + assert value_by_key(payload, "address.city", flat=False) == ["New York"] + assert value_by_key(payload, "location[].name", flat=False) == ["home", "work"] + assert value_by_key(payload, "location[0].name", flat=False) == ["home"] + assert value_by_key(payload, "location[1].name", flat=False) == ["work"] + assert value_by_key(payload, "location[2].name", flat=False) is None + assert value_by_key(payload, "location[].name[0]", flat=False) is None + assert value_by_key(payload, "location[0]", flat=False) == [ + {"name": "home", "counts": [1, 2, 3]} + ] + assert value_by_key(payload, "not_exist", flat=False) is None + assert value_by_key(payload, "address", flat=False) == [{"city": "New York"}] + assert value_by_key(payload, "address.city[0]", flat=False) is None + assert value_by_key(payload, "counts", flat=False) == [[1, 2, 3]] + assert value_by_key(payload, "location[].counts", flat=False) == [ + [1, 2, 3], + [4, 5, 6], + ] + assert value_by_key(payload, "nested[].empty", flat=False) == [[], [], None] + assert value_by_key(payload, "the_null", flat=False) == [None] + + assert value_by_key(payload, "age.nested.not_exist") is None + # endregion + + +def test_set_value_by_key() -> None: + # region valid keys + payload: dict[str, Any] = {} + new_value: dict[str, Any] = {} + key = "a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {}}, payload + + payload = {"a": {"a": 2}} + new_value = {} + key = "a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"a": 2}}, payload + + payload = {"a": {"a": 2}} + new_value = {"b": 3} + key = "a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"a": 2, "b": 3}}, payload + + payload = {"a": {"a": 2}} + new_value = {"a": 3} + key = "a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"a": 3}}, payload + + payload = {"a": {"a": 2}} + new_value = {"a": 3} + key = "a.a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"a": {"a": 3}}}, payload + + payload = {"a": {"a": {"a": 1}}} + new_value = {"b": 2} + key = "a.a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"a": {"a": 1, "b": 2}}}, payload + + payload = {"a": {"a": {"a": 1}}} + new_value = {"a": 2} + key = "a.a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"a": {"a": 2}}}, payload + + payload = {"a": []} + new_value = {"b": 2} + key = "a[0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": []}, payload + + payload = {"a": [{}]} + new_value = {"b": 2} + key = "a[0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"b": 2}]}, payload + + payload = {"a": [{"a": 1}]} + new_value = {"b": 2} + key = "a[0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"a": 1, "b": 2}]}, payload + + payload = {"a": [[]]} + new_value = {"b": 2} + key = "a[0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"b": 2}]}, payload + + payload = {"a": [[]]} + new_value = {"b": 2} + key = "a[1]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [[]]}, payload + + payload = {"a": [{"a": []}]} + new_value = {"b": 2} + key = "a[0].a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"a": {"b": 2}}]}, payload + + payload = {"a": [{"a": []}]} + new_value = {"b": 2} + key = "a[].a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"a": {"b": 2}}]}, payload + + payload = {"a": [{"a": []}, {"a": []}]} + new_value = {"b": 2} + key = "a[].a" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"a": {"b": 2}}, {"a": {"b": 2}}]}, payload + + payload = {"a": 1, "b": 2} + new_value = {"c": 3} + key = "c" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": 1, "b": 2, "c": {"c": 3}}, payload + + payload = {"a": {"b": {"c": 1}}} + new_value = {"d": 2} + key = "a.b.d" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": {"c": 1, "d": {"d": 2}}}}, payload + + payload = {"a": {"b": {"c": 1}}} + new_value = {"c": 2} + key = "a.b" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": {"c": 2}}}, payload + + payload = {"a": [{"b": 1}, {"b": 2}]} + new_value = {"c": 3} + key = "a[1]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"b": 1}, {"b": 2, "c": 3}]}, payload + + payload = {"a": []} + new_value = {"b": {"c": 1}} + key = "a[0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": []}, payload + + payload = {"a": {"b": {"c": {"d": {"e": 1}}}}} + new_value = {"f": 2} + key = "a.b.c.d" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": {"c": {"d": {"e": 1, "f": 2}}}}}, payload + + payload = {"a": {"b": {"c": 1}}} + new_value = {"d": {"e": 2}} + key = "a.b.c" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": {"c": {"d": {"e": 2}}}}}, payload + + payload = {"a": [{"b": 1}]} + new_value = {"c": 2} + key = "a[1]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [{"b": 1}]}, payload + + payload = {"a": {"b": [{"c": 1}, {"c": 2}]}} + new_value = {"d": 3} + key = "a.b[0].c" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": [{"c": {"d": 3}}, {"c": 2}]}}, payload + + payload = {"a": {"b": {"c": [{"d": 1}]}}} + new_value = {"e": {"f": 2}} + key = "a.b.c[0].d" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": {"c": [{"d": {"e": {"f": 2}}}]}}}, payload + + payload = {"a": [[{"b": 1}], [{"b": 2}]]} + new_value = {"c": 3} + key = "a[0][0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [[{"b": 1, "c": 3}], [{"b": 2}]]}, payload + + payload = {"a": [[{"b": 1}], [{"b": 2}]]} + new_value = {"c": 3} + key = "a[1][0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [[{"b": 1}], [{"b": 2, "c": 3}]]}, payload + + payload = {"a": [[{"b": 1}], [{"b": 2}]]} + new_value = {"c": 3} + key = "a[1][1]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [[{"b": 1}], [{"b": 2}]]}, payload + + payload = {"a": [[{"b": 1}], [{"b": 2}]]} + new_value = {"c": 3} + key = "a[][0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [[{"b": 1, "c": 3}], [{"b": 2, "c": 3}]]}, payload + + payload = {"a": [[{"b": 1}], [{"b": 2}]]} + new_value = {"c": 3} + key = "a[][]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": [[{"b": 1, "c": 3}], [{"b": 2, "c": 3}]]}, payload + + payload = {"a": []} + new_value = {"c": 3} + key = 'a."b.c"' + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b.c": {"c": 3}}}, payload + + payload = {"a": {"c": [1]}} + new_value = {"a": 1} + key = "a.c[0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"c": [{"a": 1}]}}, payload + + payload = {"a": {"c": [1]}} + new_value = {"a": 1} + key = "a.c[0].d" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"c": [{"d": {"a": 1}}]}}, payload + + payload = {"": 2} + new_value = {"a": 1} + key = '""' + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"": {"a": 1}}, payload + # endregion + + # region exceptions + + try: + payload = {"a": []} + new_value = {"c": 3} + key = "a.'b.c'" + set_value_by_key(payload, parse_json_path(key), new_value) + assert False, f"Should've raised an exception due to the key with incorrect quotes: {key}" + except Exception: + assert True + + try: + payload = {"a": [{"b": 1}, {"b": 2}]} + new_value = {"c": 3} + key = "a[-1]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert False, "Negative indexation is not supported" + except Exception: + assert True + + try: + payload = {"a": [{"b": 1}, {"b": 2}]} + new_value = {"c": 3} + key = "a[" + set_value_by_key(payload, parse_json_path(key), new_value) + assert False, f"Should've raised an exception due to the incorrect key: {key}" + except Exception: + assert True + + try: + payload = {"a": [{"b": 1}, {"b": 2}]} + new_value = {"c": 3} + key = "a]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert False, f"Should've raise an exception due to the incorrect key: {key}" + except Exception: + assert True + + # endregion + + # region wrong keys + payload = {"a": []} + new_value = {} + key = "a.b[0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": []}}, payload + + payload = {"a": []} + new_value = {} + key = "a.b" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": {}}}, payload + + payload = {"a": []} + new_value = {"c": 2} + key = "a.b" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": {"c": 2}}}, payload + + payload = {"a": [[{"a": 1}]]} + new_value = {"a": 2} + key = "a.b[0][0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"b": []}}, payload + + payload = {"a": {"c": 2}} + new_value = {"a": 1} + key = "a[]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": []}, payload + + payload = {"a": {"c": 2}} + new_value = {"a": 1} + key = "a[].b" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": []}, payload + + payload = {"a": {"c": [1]}} + new_value = {"a": 1} + key = "a.c[][][0]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"c": [[]]}}, payload + + payload = {"a": {"c": [{"d": 1}]}} + new_value = {"a": 1} + key = "a.c[][]" + set_value_by_key(payload, parse_json_path(key), new_value) + assert payload == {"a": {"c": [[]]}}, payload + # endregion diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_referenced_vectors.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_referenced_vectors.py new file mode 100644 index 0000000000000000000000000000000000000000..65ede0e4d99c170fbd1eaab0f3776a6849b59ff7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_referenced_vectors.py @@ -0,0 +1,135 @@ +import copy + +import pytest + + +from qdrant_client.local.qdrant_local import QdrantLocal +from qdrant_client import models + + +@pytest.fixture(scope="module", autouse=True) +def client(): + """ + Sets up multiple collections with a bunch of points + """ + client = QdrantLocal(":memory:") + client.create_collection( + "collection_default", + vectors_config=models.VectorParams( + size=4, + distance=models.Distance.DOT, + ), + ) + + client.create_collection( + "collection_multiple_vectors", + vectors_config={ + "": models.VectorParams( + size=4, + distance=models.Distance.DOT, + ), + "byte": models.VectorParams( + size=4, distance=models.Distance.DOT, datatype=models.Datatype.UINT8 + ), + "colbert": models.VectorParams( + size=4, + distance=models.Distance.DOT, + multivector_config=models.MultiVectorConfig( + comparator=models.MultiVectorComparator.MAX_SIM + ), + ), + }, + sparse_vectors_config={"sparse": models.SparseVectorParams()}, + ) + + client.upsert( + "collection_default", + [ + models.PointStruct(id=1, vector=[0.25, 0.0, 0.0, 0.0]), + ], + ) + + client.upsert( + "collection_multiple_vectors", + [ + models.PointStruct( + id=1, + vector={ + "": [0.0, 0.25, 0.0, 0.0], + "byte": [0, 25, 0, 0], + "colbert": [[0.0, 0.25, 0.0, 0.0], [0.0, 0.25, 0.0, 0.0]], + "sparse": models.SparseVector(indices=[1], values=[0.25]), + }, + ), + ], + ) + + return client + + +@pytest.mark.parametrize( + "query", + [ + models.NearestQuery(nearest=1), + models.RecommendQuery(recommend=models.RecommendInput(positive=[1], negative=[1])), + models.DiscoverQuery( + discover=models.DiscoverInput( + target=1, context=[models.ContextPair(**{"positive": 1, "negative": 1})] + ) + ), + models.ContextQuery(context=[models.ContextPair(**{"positive": 1, "negative": 1})]), + models.OrderByQuery(order_by=models.OrderBy(key="price", direction=models.Direction.ASC)), + models.FusionQuery(fusion=models.Fusion.RRF), + ], +) +@pytest.mark.parametrize( + "using, lookup_from, expected, mentioned", + [ + (None, None, [0.25, 0.0, 0.0, 0.0], True), + ("", None, [0.25, 0.0, 0.0, 0.0], True), + ( + "byte", + models.LookupLocation(collection="collection_multiple_vectors"), + [0, 25, 0, 0], + False, + ), + ( + "", + models.LookupLocation(collection="collection_multiple_vectors", vector="colbert"), + [[0.0, 0.25, 0.0, 0.0], [0.0, 0.25, 0.0, 0.0]], + False, + ), + ( + None, + models.LookupLocation(collection="collection_multiple_vectors", vector="sparse"), + models.SparseVector(indices=[1], values=[0.25]), + False, + ), + ], +) +def test_vector_dereferencing(client, query, using, lookup_from, expected, mentioned): + resolved, mentioned_ids = client._resolve_query_input( + collection_name="collection_default", + query=copy.deepcopy(query), + using=using, + lookup_from=lookup_from, + ) + + if isinstance(resolved, models.NearestQuery): + assert resolved.nearest == expected + elif isinstance(resolved, models.RecommendQuery): + assert resolved.recommend.positive == [expected] + assert resolved.recommend.negative == [expected] + elif isinstance(resolved, models.DiscoverQuery): + assert resolved.discover.target == expected + assert resolved.discover.context[0].positive == expected + assert resolved.discover.context[0].negative == expected + elif isinstance(resolved, models.ContextQuery): + assert resolved.context[0].positive == expected + assert resolved.context[0].negative == expected + else: + mentioned = False + assert resolved == query + + if mentioned: + assert mentioned_ids == {1} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_vectors.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_vectors.py new file mode 100644 index 0000000000000000000000000000000000000000..361564517b600f4034f4115a116e7de94905c3fd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/local/tests/test_vectors.py @@ -0,0 +1,21 @@ +import random + +from qdrant_client import models +from qdrant_client.local.local_collection import LocalCollection, DEFAULT_VECTOR_NAME + + +def test_get_vectors(): + collection = LocalCollection( + models.CreateCollection( + vectors=models.VectorParams(size=2, distance=models.Distance.MANHATTAN) + ) + ) + collection.upsert( + points=[ + models.PointStruct(id=i, vector=[random.random(), random.random()]) for i in range(10) + ] + ) + + assert collection._get_vectors(idx=1, with_vectors=DEFAULT_VECTOR_NAME) + assert collection._get_vectors(idx=2, with_vectors=True) + assert collection._get_vectors(idx=3, with_vectors=False) is None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/migrate/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/migrate/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef8b35714f65fda96dd5e1bcea24b84e8af1fff0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/migrate/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/migrate/__pycache__/migrate.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/migrate/__pycache__/migrate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd73a1654bd82be61e2a737a1a10d66e669cf44a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/migrate/__pycache__/migrate.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/models/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..726d481a141a7501848eefcac61293af0a67c758 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..049eb7844f13c6840fafa98a9aec4fe1e0185c1e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/grpc_uploader.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/grpc_uploader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ba5eb968ba4ba1c0e5e75085766643886bf676e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/grpc_uploader.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/rest_uploader.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/rest_uploader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c1e600b273b449522cb7195d38984e5bd94773e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/rest_uploader.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/uploader.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/uploader.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0adffc8ef79eaaa4fde5d7be34da2e1caa8db756 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/qdrant_client/uploader/__pycache__/uploader.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95b450155e4c351a48f118ffcca32064bdb8dcca Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/_version.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/_version.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..29646a9e3bdb57d720707b04b1ce0c0e259a3097 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/_version.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/actor.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/actor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..065cbbe6e91b3f31853a39225ab7f1cc229167a6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/actor.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/client_builder.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/client_builder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5af91de88742c3b398528f416a3171bf0358a5fe Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/client_builder.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/cluster_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/cluster_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c8fbf366ff083411cf801080d925a9e4d8552a3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/cluster_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/cross_language.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/cross_language.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c01dbb25ac1e02fcfd1a89abf190a8bcad822dc9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/cross_language.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/exceptions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f44579aa233b9c478662240d5e00753d121faea Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/exceptions.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/job_config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/job_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..844b59c56238ce80cd49092ee7f59ece6ffd6b4d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/job_config.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/remote_function.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/remote_function.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dbc380c18883e39c518e8a8ea85addf2c8e4c163 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/remote_function.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/runtime_context.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/runtime_context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e6fe2535cecf24fb9d7b23a081630fbad58f24b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/runtime_context.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/setup-dev.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/setup-dev.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc8ee220a0b623316ab8ad0a2fd79da30bb1199e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/setup-dev.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/types.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82e2435361fff08b4d53ceb1ffd7ef8eb65e2afc Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/__pycache__/types.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d0258bc7c8d7afcdbf64e66bbb6a7f37ce9e448 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/pydantic_compat.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/pydantic_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d1de7ee7e5129a34958e3afaf3a739d0c5396c9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/pydantic_compat.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/signature.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/signature.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..313ed6a1c2d587287ed37ed2821c4f7fe59edc39 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/signature.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/test_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b002a4cd69bb8601ffff471ff7577a2e6902dfa Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/test_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31ec0fac61a4bd33c4580bcc660b5dd244550e96 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/pydantic_compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/pydantic_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..b405e64ffa8ff77aa3eeb694961bbe141e3a6dd3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/pydantic_compat.py @@ -0,0 +1,108 @@ +# ruff: noqa +import packaging.version + +# Pydantic is a dependency of `ray["default"]` but not the minimal installation, +# so handle the case where it isn't installed. +try: + import pydantic + + PYDANTIC_INSTALLED = True +except ImportError: + pydantic = None + PYDANTIC_INSTALLED = False + + +if not PYDANTIC_INSTALLED: + IS_PYDANTIC_2 = False + BaseModel = None + Extra = None + Field = None + NonNegativeFloat = None + NonNegativeInt = None + PositiveFloat = None + PositiveInt = None + PrivateAttr = None + StrictInt = None + ValidationError = None + root_validator = None + validator = None + is_subclass_of_base_model = lambda obj: False +# In pydantic <1.9.0, __version__ attribute is missing, issue ref: +# https://github.com/pydantic/pydantic/issues/2572, so we need to check +# the existence prior to comparison. +elif not hasattr(pydantic, "__version__") or packaging.version.parse( + pydantic.__version__ +) < packaging.version.parse("2.0"): + IS_PYDANTIC_2 = False + from pydantic import ( + BaseModel, + Extra, + Field, + NonNegativeFloat, + NonNegativeInt, + PositiveFloat, + PositiveInt, + PrivateAttr, + StrictInt, + ValidationError, + root_validator, + validator, + ) + + def is_subclass_of_base_model(obj): + return issubclass(obj, BaseModel) + +else: + IS_PYDANTIC_2 = True + from pydantic.v1 import ( + BaseModel, + Extra, + Field, + NonNegativeFloat, + NonNegativeInt, + PositiveFloat, + PositiveInt, + PrivateAttr, + StrictInt, + ValidationError, + root_validator, + validator, + ) + + def is_subclass_of_base_model(obj): + from pydantic import BaseModel as BaseModelV2 + from pydantic.v1 import BaseModel as BaseModelV1 + + return issubclass(obj, BaseModelV1) or issubclass(obj, BaseModelV2) + + +def register_pydantic_serializers(serialization_context): + if not PYDANTIC_INSTALLED: + return + + if IS_PYDANTIC_2: + # TODO(edoakes): compare against the version that has the fixes. + from pydantic.v1.fields import ModelField + else: + from pydantic.fields import ModelField + + # Pydantic's Cython validators are not serializable. + # https://github.com/cloudpipe/cloudpickle/issues/408 + serialization_context._register_cloudpickle_serializer( + ModelField, + custom_serializer=lambda o: { + "name": o.name, + # outer_type_ is the original type for ModelFields, + # while type_ can be updated later with the nested type + # like int for List[int]. + "type_": o.outer_type_, + "class_validators": o.class_validators, + "model_config": o.model_config, + "default": o.default, + "default_factory": o.default_factory, + "required": o.required, + "alias": o.alias, + "field_info": o.field_info, + }, + custom_deserializer=lambda kwargs: ModelField(**kwargs), + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/signature.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/signature.py new file mode 100644 index 0000000000000000000000000000000000000000..190d18c139062e3ae014bf9b5c61e484a3a101d7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/signature.py @@ -0,0 +1,163 @@ +import inspect +import logging +from inspect import Parameter +from typing import Any, Dict, List, Tuple + +from ray._private.inspect_util import is_cython + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) + +# This dummy type is also defined in ArgumentsBuilder.java. Please keep it +# synced. +DUMMY_TYPE = b"__RAY_DUMMY__" + + +def get_signature(func: Any) -> inspect.Signature: + """Get signature parameters. + + Support Cython functions by grabbing relevant attributes from the Cython + function and attaching to a no-op function. This is somewhat brittle, since + inspect may change, but given that inspect is written to a PEP, we hope + it is relatively stable. Future versions of Python may allow overloading + the inspect 'isfunction' and 'ismethod' functions / create ABC for Python + functions. Until then, it appears that Cython won't do anything about + compatability with the inspect module. + + Args: + func: The function whose signature should be checked. + + Returns: + A function signature object, which includes the names of the keyword + arguments as well as their default values. + + Raises: + TypeError: A type error if the signature is not supported + """ + # The first condition for Cython functions, the latter for Cython instance + # methods + if is_cython(func): + attrs = ["__code__", "__annotations__", "__defaults__", "__kwdefaults__"] + + if all(hasattr(func, attr) for attr in attrs): + original_func = func + + def func(): + return + + for attr in attrs: + setattr(func, attr, getattr(original_func, attr)) + else: + raise TypeError(f"{func!r} is not a Python function we can process") + + return inspect.signature(func) + + +def extract_signature(func: Any, ignore_first: bool = False) -> List[Parameter]: + """Extract the function signature from the function. + + Args: + func: The function whose signature should be extracted. + ignore_first: True if the first argument should be ignored. This should + be used when func is a method of a class. + + Returns: + List of Parameter objects representing the function signature. + """ + signature_parameters = list(get_signature(func).parameters.values()) + + if ignore_first: + if len(signature_parameters) == 0: + raise ValueError( + "Methods must take a 'self' argument, but the " + f"method '{func.__name__}' does not have one." + ) + signature_parameters = signature_parameters[1:] + + return signature_parameters + + +def validate_args( + signature_parameters: List[Parameter], args: Tuple[Any, ...], kwargs: Dict[str, Any] +) -> None: + """Validates the arguments against the signature. + + Args: + signature_parameters: The list of Parameter objects + representing the function signature, obtained from + `extract_signature`. + args: The positional arguments passed into the function. + kwargs: The keyword arguments passed into the function. + + Raises: + TypeError: Raised if arguments do not fit in the function signature. + """ + reconstructed_signature = inspect.Signature(parameters=signature_parameters) + try: + reconstructed_signature.bind(*args, **kwargs) + except TypeError as exc: # capture a friendlier stacktrace + raise TypeError(str(exc)) from None + + +def flatten_args( + signature_parameters: List[Parameter], args: Tuple[Any, ...], kwargs: Dict[str, Any] +) -> List[Any]: + """Validates the arguments against the signature and flattens them. + + The flat list representation is a serializable format for arguments. + Since the flatbuffer representation of function arguments is a list, we + combine both keyword arguments and positional arguments. We represent + this with two entries per argument value - [DUMMY_TYPE, x] for positional + arguments and [KEY, VALUE] for keyword arguments. See the below example. + See `recover_args` for logic restoring the flat list back to args/kwargs. + + Args: + signature_parameters: The list of Parameter objects + representing the function signature, obtained from + `extract_signature`. + args: The positional arguments passed into the function. + kwargs: The keyword arguments passed into the function. + + Returns: + List of args and kwargs. Non-keyword arguments are prefixed + by internal enum DUMMY_TYPE. + + Raises: + TypeError: Raised if arguments do not fit in the function signature. + """ + validate_args(signature_parameters, args, kwargs) + list_args = [] + for arg in args: + list_args += [DUMMY_TYPE, arg] + + for keyword, arg in kwargs.items(): + list_args += [keyword, arg] + return list_args + + +def recover_args(flattened_args: List[Any]) -> Tuple[List[Any], Dict[str, Any]]: + """Recreates `args` and `kwargs` from the flattened arg list. + + Args: + flattened_args: List of args and kwargs. This should be the output of + `flatten_args`. + + Returns: + args: The non-keyword arguments passed into the function. + kwargs: The keyword arguments passed into the function. + """ + assert ( + len(flattened_args) % 2 == 0 + ), "Flattened arguments need to be even-numbered. See `flatten_args`." + args = [] + kwargs = {} + for name_index in range(0, len(flattened_args), 2): + name, arg = flattened_args[name_index], flattened_args[name_index + 1] + if name == DUMMY_TYPE: + args.append(arg) + else: + kwargs[name] = arg + + return args, kwargs diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/test_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..65a8cb356816e8b144155fcfb9c14544f4653228 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/test_utils.py @@ -0,0 +1,249 @@ +"""Test utilities for Ray. + +This module contains test utility classes that are distributed with the Ray package +and can be used by external libraries and tests. These utilities must remain in +_common/ (not in tests/) to be accessible in the Ray package distribution. +""" + +import asyncio +from collections.abc import Awaitable +from contextlib import contextmanager +import inspect +import os +import time +import traceback +from typing import Any, Callable, Dict, Iterator, List, Optional, Set +import uuid +from enum import Enum + + +import ray +import ray._private.utils +import ray._private.usage.usage_lib as ray_usage_lib + + +@ray.remote(num_cpus=0) +class SignalActor: + """A Ray actor for coordinating test execution through signals. + + Useful for testing async coordination, waiting for specific states, + and synchronizing multiple actors or tasks in tests. + """ + + def __init__(self): + self.ready_event = asyncio.Event() + self.num_waiters = 0 + + def send(self, clear: bool = False): + self.ready_event.set() + if clear: + self.ready_event.clear() + + async def wait(self, should_wait: bool = True): + if should_wait: + self.num_waiters += 1 + await self.ready_event.wait() + self.num_waiters -= 1 + + async def cur_num_waiters(self) -> int: + return self.num_waiters + + +@ray.remote(num_cpus=0) +class Semaphore: + """A Ray actor implementing a semaphore for test coordination. + + Useful for testing resource limiting, concurrency control, + and coordination between multiple actors or tasks. + """ + + def __init__(self, value: int = 1): + self._sema = asyncio.Semaphore(value=value) + + async def acquire(self): + await self._sema.acquire() + + async def release(self): + self._sema.release() + + async def locked(self) -> bool: + return self._sema.locked() + + +__all__ = ["SignalActor", "Semaphore"] + + +def wait_for_condition( + condition_predictor: Callable[..., bool], + timeout: float = 10, + retry_interval_ms: float = 100, + raise_exceptions: bool = False, + **kwargs: Any, +): + """Wait until a condition is met or time out with an exception. + + Args: + condition_predictor: A function that predicts the condition. + timeout: Maximum timeout in seconds. + retry_interval_ms: Retry interval in milliseconds. + raise_exceptions: If true, exceptions that occur while executing + condition_predictor won't be caught and instead will be raised. + **kwargs: Arguments to pass to the condition_predictor. + + Returns: + None: Returns when the condition is met. + + Raises: + RuntimeError: If the condition is not met before the timeout expires. + """ + start = time.time() + last_ex = None + while time.time() - start <= timeout: + try: + if condition_predictor(**kwargs): + return + except Exception: + if raise_exceptions: + raise + last_ex = ray._private.utils.format_error_message(traceback.format_exc()) + time.sleep(retry_interval_ms / 1000.0) + message = "The condition wasn't met before the timeout expired." + if last_ex is not None: + message += f" Last exception: {last_ex}" + raise RuntimeError(message) + + +async def async_wait_for_condition( + condition_predictor: Callable[..., Awaitable[bool]], + timeout: float = 10, + retry_interval_ms: float = 100, + **kwargs: Any, +): + """Wait until a condition is met or time out with an exception. + + Args: + condition_predictor: A function that predicts the condition. + timeout: Maximum timeout in seconds. + retry_interval_ms: Retry interval in milliseconds. + **kwargs: Arguments to pass to the condition_predictor. + + Returns: + None: Returns when the condition is met. + + Raises: + RuntimeError: If the condition is not met before the timeout expires. + """ + start = time.time() + last_ex = None + while time.time() - start <= timeout: + try: + if inspect.iscoroutinefunction(condition_predictor): + if await condition_predictor(**kwargs): + return + else: + if condition_predictor(**kwargs): + return + except Exception as ex: + last_ex = ex + await asyncio.sleep(retry_interval_ms / 1000.0) + message = "The condition wasn't met before the timeout expired." + if last_ex is not None: + message += f" Last exception: {last_ex}" + raise RuntimeError(message) + + +@contextmanager +def simulate_s3_bucket( + port: int = 5002, + region: str = "us-west-2", +) -> Iterator[str]: + """Context manager that simulates an S3 bucket and yields the URI. + + Args: + port: The port of the localhost endpoint where S3 is being served. + region: The S3 region. + + Yields: + str: URI for the simulated S3 bucket. + """ + from moto.server import ThreadedMotoServer + + old_env = os.environ + os.environ["AWS_ACCESS_KEY_ID"] = "testing" + os.environ["AWS_SECRET_ACCESS_KEY"] = "testing" + os.environ["AWS_SECURITY_TOKEN"] = "testing" + os.environ["AWS_SESSION_TOKEN"] = "testing" + + s3_server = f"http://localhost:{port}" + server = ThreadedMotoServer(port=port) + server.start() + url = f"s3://{uuid.uuid4().hex}?region={region}&endpoint_override={s3_server}" + yield url + server.stop() + os.environ = old_env + + +class TelemetryCallsite(Enum): + DRIVER = "driver" + ACTOR = "actor" + TASK = "task" + + +def _get_library_usages() -> Set[str]: + return set( + ray_usage_lib.get_library_usages_to_report( + ray.experimental.internal_kv.internal_kv_get_gcs_client() + ) + ) + + +def _get_extra_usage_tags() -> Dict[str, str]: + return ray_usage_lib.get_extra_usage_tags_to_report( + ray.experimental.internal_kv.internal_kv_get_gcs_client() + ) + + +def check_library_usage_telemetry( + use_lib_fn: Callable[[], None], + *, + callsite: TelemetryCallsite, + expected_library_usages: List[Set[str]], + expected_extra_usage_tags: Optional[Dict[str, str]] = None, +): + """Helper for writing tests to validate library usage telemetry. + + `use_lib_fn` is a callable that will be called from the provided callsite. + After calling it, the telemetry data to export will be validated against + expected_library_usages and expected_extra_usage_tags. + """ + assert len(_get_library_usages()) == 0, _get_library_usages() + + if callsite == TelemetryCallsite.DRIVER: + use_lib_fn() + elif callsite == TelemetryCallsite.ACTOR: + + @ray.remote + class A: + def __init__(self): + use_lib_fn() + + a = A.remote() + ray.get(a.__ray_ready__.remote()) + elif callsite == TelemetryCallsite.TASK: + + @ray.remote + def f(): + use_lib_fn() + + ray.get(f.remote()) + else: + assert False, f"Unrecognized callsite: {callsite}" + + library_usages = _get_library_usages() + extra_usage_tags = _get_extra_usage_tags() + + assert library_usages in expected_library_usages, library_usages + if expected_extra_usage_tags: + assert all( + [extra_usage_tags[k] == v for k, v in expected_extra_usage_tags.items()] + ), extra_usage_tags diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..103c40397801a80e59b8678bdc29627501cba19d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_common/utils.py @@ -0,0 +1,353 @@ +import asyncio +import binascii +import errno +import importlib +import inspect +from inspect import signature +import os +import psutil +import random +import string +import sys +import tempfile +from typing import Any, Coroutine, Dict, Optional + + +def import_attr(full_path: str, *, reload_module: bool = False): + """Given a full import path to a module attr, return the imported attr. + + If `reload_module` is set, the module will be reloaded using `importlib.reload`. + + For example, the following are equivalent: + MyClass = import_attr("module.submodule:MyClass") + MyClass = import_attr("module.submodule.MyClass") + from module.submodule import MyClass + + Returns: + Imported attr + """ + if full_path is None: + raise TypeError("import path cannot be None") + + if ":" in full_path: + if full_path.count(":") > 1: + raise ValueError( + f'Got invalid import path "{full_path}". An ' + "import path may have at most one colon." + ) + module_name, attr_name = full_path.split(":") + else: + last_period_idx = full_path.rfind(".") + module_name = full_path[:last_period_idx] + attr_name = full_path[last_period_idx + 1 :] + + module = importlib.import_module(module_name) + if reload_module: + importlib.reload(module) + return getattr(module, attr_name) + + +def get_or_create_event_loop() -> asyncio.AbstractEventLoop: + """Get a running async event loop if one exists, otherwise create one. + + This function serves as a proxy for the deprecating get_event_loop(). + It tries to get the running loop first, and if no running loop + could be retrieved: + - For python version <3.10: it falls back to the get_event_loop + call. + - For python version >= 3.10: it uses the same python implementation + of _get_event_loop() at asyncio/events.py. + + Ideally, one should use high level APIs like asyncio.run() with python + version >= 3.7, if not possible, one should create and manage the event + loops explicitly. + """ + vers_info = sys.version_info + if vers_info.major >= 3 and vers_info.minor >= 10: + # This follows the implementation of the deprecating `get_event_loop` + # in python3.10's asyncio. See python3.10/asyncio/events.py + # _get_event_loop() + try: + loop = asyncio.get_running_loop() + assert loop is not None + return loop + except RuntimeError as e: + # No running loop, relying on the error message as for now to + # differentiate runtime errors. + assert "no running event loop" in str(e) + return asyncio.get_event_loop_policy().get_event_loop() + + return asyncio.get_event_loop() + + +_BACKGROUND_TASKS = set() + + +def run_background_task(coroutine: Coroutine) -> asyncio.Task: + """Schedule a task reliably to the event loop. + + This API is used when you don't want to cache the reference of `asyncio.Task`. + For example, + + ``` + get_event_loop().create_task(coroutine(*args)) + ``` + + The above code doesn't guarantee to schedule the coroutine to the event loops + + When using create_task in a "fire and forget" way, we should keep the references + alive for the reliable execution. This API is used to fire and forget + asynchronous execution. + + https://docs.python.org/3/library/asyncio-task.html#creating-tasks + """ + task = get_or_create_event_loop().create_task(coroutine) + # Add task to the set. This creates a strong reference. + _BACKGROUND_TASKS.add(task) + + # To prevent keeping references to finished tasks forever, + # make each task remove its own reference from the set after + # completion: + task.add_done_callback(_BACKGROUND_TASKS.discard) + return task + + +# Used in gpu detection +RESOURCE_CONSTRAINT_PREFIX = "accelerator_type:" +PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME = "bundle" + + +def resources_from_ray_options(options_dict: Dict[str, Any]) -> Dict[str, Any]: + """Determine a task's resource requirements. + + Args: + options_dict: The dictionary that contains resources requirements. + + Returns: + A dictionary of the resource requirements for the task. + """ + resources = (options_dict.get("resources") or {}).copy() + + if "CPU" in resources or "GPU" in resources: + raise ValueError( + "The resources dictionary must not contain the key 'CPU' or 'GPU'" + ) + elif "memory" in resources or "object_store_memory" in resources: + raise ValueError( + "The resources dictionary must not " + "contain the key 'memory' or 'object_store_memory'" + ) + elif PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME in resources: + raise ValueError( + "The resource should not include `bundle` which " + f"is reserved for Ray. resources: {resources}" + ) + + num_cpus = options_dict.get("num_cpus") + num_gpus = options_dict.get("num_gpus") + memory = options_dict.get("memory") + object_store_memory = options_dict.get("object_store_memory") + accelerator_type = options_dict.get("accelerator_type") + + if num_cpus is not None: + resources["CPU"] = num_cpus + if num_gpus is not None: + resources["GPU"] = num_gpus + if memory is not None: + resources["memory"] = int(memory) + if object_store_memory is not None: + resources["object_store_memory"] = object_store_memory + if accelerator_type is not None: + resources[f"{RESOURCE_CONSTRAINT_PREFIX}{accelerator_type}"] = 0.001 + + return resources + + +# Match the standard alphabet used for UUIDs. +RANDOM_STRING_ALPHABET = string.ascii_lowercase + string.digits + + +def get_random_alphanumeric_string(length: int): + """Generates random string of length consisting exclusively of + - Lower-case ASCII chars + - Digits + """ + return "".join(random.choices(RANDOM_STRING_ALPHABET, k=length)) + + +_PRINTED_WARNING = set() + + +def get_call_location(back: int = 1): + """ + Get the location (filename and line number) of a function caller, `back` + frames up the stack. + + Args: + back: The number of frames to go up the stack, not including this + function. + + Returns: + A string with the filename and line number of the caller. + For example, "myfile.py:123". + """ + stack = inspect.stack() + try: + frame = stack[back + 1] + return f"{frame.filename}:{frame.lineno}" + except IndexError: + return "UNKNOWN" + + +def get_user_temp_dir(): + if "RAY_TMPDIR" in os.environ: + return os.environ["RAY_TMPDIR"] + elif sys.platform.startswith("linux") and "TMPDIR" in os.environ: + return os.environ["TMPDIR"] + elif sys.platform.startswith("darwin") or sys.platform.startswith("linux"): + # Ideally we wouldn't need this fallback, but keep it for now for + # for compatibility + tempdir = os.path.join(os.sep, "tmp") + else: + tempdir = tempfile.gettempdir() + return tempdir + + +def get_ray_temp_dir(): + return os.path.join(get_user_temp_dir(), "ray") + + +def get_ray_address_file(temp_dir: Optional[str]): + if temp_dir is None: + temp_dir = get_ray_temp_dir() + return os.path.join(temp_dir, "ray_current_cluster") + + +def reset_ray_address(temp_dir: Optional[str] = None): + address_file = get_ray_address_file(temp_dir) + if os.path.exists(address_file): + try: + os.remove(address_file) + except OSError: + pass + + +def load_class(path): + """Load a class at runtime given a full path. + + Example of the path: mypkg.mysubpkg.myclass + """ + class_data = path.split(".") + if len(class_data) < 2: + raise ValueError("You need to pass a valid path like mymodule.provider_class") + module_path = ".".join(class_data[:-1]) + class_str = class_data[-1] + module = importlib.import_module(module_path) + return getattr(module, class_str) + + +def get_system_memory( + # For cgroups v1: + memory_limit_filename: str = "/sys/fs/cgroup/memory/memory.limit_in_bytes", + # For cgroups v2: + memory_limit_filename_v2: str = "/sys/fs/cgroup/memory.max", +): + """Return the total amount of system memory in bytes. + + Args: + memory_limit_filename: The path to the file that contains the memory + limit for the Docker container. Defaults to + /sys/fs/cgroup/memory/memory.limit_in_bytes. + memory_limit_filename_v2: The path to the file that contains the memory + limit for the Docker container in cgroups v2. Defaults to + /sys/fs/cgroup/memory.max. + + Returns: + The total amount of system memory in bytes. + """ + # Try to accurately figure out the memory limit if we are in a docker + # container. Note that this file is not specific to Docker and its value is + # often much larger than the actual amount of memory. + docker_limit = None + if os.path.exists(memory_limit_filename): + with open(memory_limit_filename, "r") as f: + docker_limit = int(f.read().strip()) + elif os.path.exists(memory_limit_filename_v2): + with open(memory_limit_filename_v2, "r") as f: + # Don't forget to strip() the newline: + max_file = f.read().strip() + if max_file.isnumeric(): + docker_limit = int(max_file) + else: + # max_file is "max", i.e. is unset. + docker_limit = None + + # Use psutil if it is available. + psutil_memory_in_bytes = psutil.virtual_memory().total + + if docker_limit is not None: + # We take the min because the cgroup limit is very large if we aren't + # in Docker. + return min(docker_limit, psutil_memory_in_bytes) + + return psutil_memory_in_bytes + + +def binary_to_hex(identifier): + hex_identifier = binascii.hexlify(identifier) + hex_identifier = hex_identifier.decode() + return hex_identifier + + +def hex_to_binary(hex_identifier): + return binascii.unhexlify(hex_identifier) + + +def try_make_directory_shared(directory_path): + try: + os.chmod(directory_path, 0o0777) + except OSError as e: + # Silently suppress the PermissionError that is thrown by the chmod. + # This is done because the user attempting to change the permissions + # on a directory may not own it. The chmod is attempted whether the + # directory is new or not to avoid race conditions. + # ray-project/ray/#3591 + if e.errno in [errno.EACCES, errno.EPERM]: + pass + else: + raise + + +def try_to_create_directory(directory_path): + # Attempt to create a directory that is globally readable/writable. + directory_path = os.path.expanduser(directory_path) + os.makedirs(directory_path, exist_ok=True) + # Change the log directory permissions so others can use it. This is + # important when multiple people are using the same machine. + try_make_directory_shared(directory_path) + + +def get_function_args(callable): + all_parameters = frozenset(signature(callable).parameters) + return list(all_parameters) + + +def decode(byte_str: str, allow_none: bool = False, encode_type: str = "utf-8"): + """Make this unicode in Python 3, otherwise leave it as bytes. + + Args: + byte_str: The byte string to decode. + allow_none: If true, then we will allow byte_str to be None in which + case we will return an empty string. TODO(rkn): Remove this flag. + This is only here to simplify upgrading to flatbuffers 1.10.0. + encode_type: The encoding type to use for decoding. Defaults to "utf-8". + + Returns: + A byte string in Python 2 and a unicode string in Python 3. + """ + if byte_str is None and allow_none: + return "" + + if not isinstance(byte_str, bytes): + raise ValueError(f"The argument {byte_str} must be a bytes object.") + return byte_str.decode(encode_type) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ddaf4185d4d1a255225e927973cbef7e8bd8a054 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/arrow_serialization.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/arrow_serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a425de10ce0288bb5b2b2fb8f171aebe8f57ec04 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/arrow_serialization.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/arrow_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/arrow_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ce480141fbbf25e9bce326691f001410bcde4b0e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/arrow_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/async_compat.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/async_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c435918c8b499dd0ddb59af9ffb4030ccb169301 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/async_compat.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/async_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/async_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de70553c649441c53ed3c516162bbea7886bb603 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/async_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/auto_init_hook.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/auto_init_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa787d48d1756bc1d4d8295dda1e845e69352f6f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/auto_init_hook.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/client_mode_hook.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/client_mode_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f22553adf21b31ef29ab62b31252c1e796765622 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/client_mode_hook.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/collections_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/collections_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3373f680eac94e4144e49b088d2bd9edc1c7755b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/collections_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/compat.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa3b278dddbe90ee199e1d0bb50c7798f74b0cde Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/compat.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/conftest_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/conftest_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..750d9385ff7a41a5730e2d51bd98315ac16567de Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/conftest_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/custom_types.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/custom_types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20a96da1667e9cfd495a896610db43a7b035a753 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/custom_types.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/dict.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/dict.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbb7c05f6ee19f82c3e5a382e0fb2ce616435c93 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/dict.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/external_storage.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/external_storage.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7b553b7e407cf13c3f11d35d2ce4d20a5e86d1d6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/external_storage.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/function_manager.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/function_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26f9edbe24ea07ffe68bb9f4dbeb6e975d3f4a82 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/function_manager.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/gcs_pubsub.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/gcs_pubsub.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..101d3d5d5d4d2bb9cd6e147fd3fab99c5e95a8c0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/gcs_pubsub.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/gcs_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/gcs_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa11c71bd2cc29b24af0e68d9911bd10a6deb7f8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/gcs_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/inspect_util.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/inspect_util.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc0200c6f2c2a0828771bf682c31a7e757097b81 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/inspect_util.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/internal_api.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/internal_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e233a435f377944768d1f382abaaa6c836304e1a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/internal_api.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/label_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/label_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67b69578663d310988cfa5e35906151f18148b52 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/label_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/log.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b6af193cc41a4ba137e0c59d2090104c8ec940b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/log.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/log_monitor.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/log_monitor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e0e2ab39c81b243f0fce9b0b109e38f4cd92ed7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/log_monitor.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/logging_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/logging_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6430a22c9e911314a253f864b289652af619a1df Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/logging_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/memory_monitor.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/memory_monitor.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50b81603099af72b3e6c08e044556ff6aa764b3d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/memory_monitor.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/metrics_agent.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/metrics_agent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa16fb0bc50d495c06a606fcbf516b752ebf40e4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/metrics_agent.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/node.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/node.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ebee8d4f695d19283209dbc893ba4a12061657d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/node.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/object_ref_generator.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/object_ref_generator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c11e60099a4d95754fdde324e39d7ee2514a073a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/object_ref_generator.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/parameter.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/parameter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..47b3e4bd0bbe796f1c98ed6054ed548c3d4db32b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/parameter.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/path_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/path_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ff5198b99cee5bdbce55555cd94a36ece5084df9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/path_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/process_watcher.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/process_watcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..73cdd0907df1f1fa83292cdd136576eb5e035ada Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/process_watcher.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/profiling.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/profiling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3db5652a6eaa5e28f4ae456b8c206b40f7fcaec Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/profiling.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/prometheus_exporter.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/prometheus_exporter.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..85d1661bb6093d2730a9a2cc83fcb15a990e79c1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/prometheus_exporter.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/protobuf_compat.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/protobuf_compat.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46912c65992f17fb6eb2960ae1617c514eaee3d9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/protobuf_compat.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_client_microbenchmark.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_client_microbenchmark.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1c4b64f56fdf4bb176e908d48773e4e1f1d320c5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_client_microbenchmark.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_cluster_perf.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_cluster_perf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdd4a449cd24684663efb80a46a7c43201ef3c40 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_cluster_perf.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_constants.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f9479402f9d7a1dd4a6761596d814f467aafe41d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_constants.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_experimental_perf.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_experimental_perf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b01e24d9db34aa41ebfe8c90b5375e3ec8c532e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_experimental_perf.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_microbenchmark_helpers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_microbenchmark_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d4157663b955fccb72129c429b5909fadb8f21bb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_microbenchmark_helpers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_option_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_option_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c484d36bb3ffa1b65713c7e931700ffb9471a88 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_option_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_perf.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_perf.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5e447b9b70b21aca3eccf8d5798815f7cab67757 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_perf.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_process_reaper.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_process_reaper.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..266ad827c3d9c0c11de48e2c3f3441964ba81fc3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/ray_process_reaper.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/resource_isolation_config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/resource_isolation_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b13b68d2e3b374df9b950ad398828249c8bf0869 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/resource_isolation_config.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/resource_spec.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/resource_spec.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9168ac6558d8aa51ac7ad222f40c29a87140f56a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/resource_spec.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/serialization.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/serialization.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bbc70a0e076c5385a5f8519047c72dbffc43415a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/serialization.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/services.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/services.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cc809d7121630eab97695849995c653df5c375db Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/services.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/state.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba1591985a0bdfb0a999ebf33d593b036a2ad1f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/state.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/state_api_test_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/state_api_test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d417cf8b4177b0b385ea4abe8decf4909ae2c188 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/state_api_test_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/test_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f33c6946782aae7cd9f81e41eb5c87ce11c6059 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/test_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/tls_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/tls_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37b0a2b10b91000dbe1dd6419247c17eaf63fefe Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/tls_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2cb2f85585ba4b9ae6d24df7faf8748678eb7311 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/worker.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8d9d403ab9dcd99e3550c4dc9c15b6358ce7e5c8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/__pycache__/worker.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a2b91f92a9a814ad430c80bf10afc8950fc216f3c1389f46442f80947f898f42 +size 150662 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e76e38eb00726bb2a0e0a9967780cd316a2514c3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__init__.py @@ -0,0 +1,77 @@ +from typing import Optional, Set + +from ray._private.accelerators.accelerator import AcceleratorManager +from ray._private.accelerators.amd_gpu import AMDGPUAcceleratorManager +from ray._private.accelerators.hpu import HPUAcceleratorManager +from ray._private.accelerators.intel_gpu import IntelGPUAcceleratorManager +from ray._private.accelerators.neuron import NeuronAcceleratorManager +from ray._private.accelerators.npu import NPUAcceleratorManager +from ray._private.accelerators.nvidia_gpu import NvidiaGPUAcceleratorManager +from ray._private.accelerators.tpu import TPUAcceleratorManager + + +def get_all_accelerator_managers() -> Set[AcceleratorManager]: + """Get all accelerator managers supported by Ray.""" + return { + NvidiaGPUAcceleratorManager, + IntelGPUAcceleratorManager, + AMDGPUAcceleratorManager, + TPUAcceleratorManager, + NeuronAcceleratorManager, + HPUAcceleratorManager, + NPUAcceleratorManager, + } + + +def get_all_accelerator_resource_names() -> Set[str]: + """Get all resource names for accelerators.""" + return { + accelerator_manager.get_resource_name() + for accelerator_manager in get_all_accelerator_managers() + } + + +def get_accelerator_manager_for_resource( + resource_name: str, +) -> Optional[AcceleratorManager]: + """Get the corresponding accelerator manager for the given + accelerator resource name + + E.g., TPUAcceleratorManager is returned if resource name is "TPU" + """ + try: + return get_accelerator_manager_for_resource._resource_name_to_accelerator_manager.get( # noqa: E501 + resource_name, None + ) + except AttributeError: + # Lazy initialization. + resource_name_to_accelerator_manager = { + accelerator_manager.get_resource_name(): accelerator_manager + for accelerator_manager in get_all_accelerator_managers() + } + # Special handling for GPU resource name since multiple accelerator managers + # have the same GPU resource name. + if AMDGPUAcceleratorManager.get_current_node_num_accelerators() > 0: + resource_name_to_accelerator_manager["GPU"] = AMDGPUAcceleratorManager + elif IntelGPUAcceleratorManager.get_current_node_num_accelerators() > 0: + resource_name_to_accelerator_manager["GPU"] = IntelGPUAcceleratorManager + else: + resource_name_to_accelerator_manager["GPU"] = NvidiaGPUAcceleratorManager + get_accelerator_manager_for_resource._resource_name_to_accelerator_manager = ( + resource_name_to_accelerator_manager + ) + return resource_name_to_accelerator_manager.get(resource_name, None) + + +__all__ = [ + "NvidiaGPUAcceleratorManager", + "IntelGPUAcceleratorManager", + "AMDGPUAcceleratorManager", + "TPUAcceleratorManager", + "NeuronAcceleratorManager", + "HPUAcceleratorManager", + "NPUAcceleratorManager", + "get_all_accelerator_managers", + "get_all_accelerator_resource_names", + "get_accelerator_manager_for_resource", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc0668443093fa1e45038044f99fabd703c4e38e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/accelerator.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/accelerator.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc7aeeb2dcb0f9c7256b8f4f3daad631be89d70f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/accelerator.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/amd_gpu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/amd_gpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f20f699101b30805a39dc0f8b885932e09c40c1d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/amd_gpu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/hpu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/hpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a502a4b116124d0321f8ad410ade251787c1086 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/hpu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/intel_gpu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/intel_gpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adb2fb8c2973c153bef54d594a1331be1a8a8074 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/intel_gpu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/neuron.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/neuron.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05bb4c81dfe0e48f7bd87fd76dcd49a48ec81ce1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/neuron.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/npu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/npu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9c7400793bd7a1ad7cd685683ce5f0db455827c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/npu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/nvidia_gpu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/nvidia_gpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c173b4820ee94040d7c07c23ee7bbfd80db016f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/nvidia_gpu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/tpu.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/tpu.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0cb5dabc4004b0cf03ddf94ac6e18a419243eca Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/__pycache__/tpu.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/accelerator.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/accelerator.py new file mode 100644 index 0000000000000000000000000000000000000000..b2fb21287c878d5e069654003a1e2b37b8effc0f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/accelerator.py @@ -0,0 +1,138 @@ +from abc import ABC, abstractmethod +from typing import Dict, List, Optional, Tuple + + +class AcceleratorManager(ABC): + """This class contains all the functions needed for supporting + an accelerator family in Ray.""" + + @staticmethod + @abstractmethod + def get_resource_name() -> str: + """Get the name of the resource representing this accelerator family. + + Returns: + The resource name: e.g., the resource name for NVIDIA GPUs is "GPU" + """ + + @staticmethod + @abstractmethod + def get_visible_accelerator_ids_env_var() -> str: + """Get the env var that sets the ids of visible accelerators of this family. + + Returns: + The env var for setting visible accelerator ids: e.g., + CUDA_VISIBLE_DEVICES for NVIDIA GPUs. + """ + + @staticmethod + @abstractmethod + def get_current_node_num_accelerators() -> int: + """Get the total number of accelerators of this family on the current node. + + Returns: + The detected total number of accelerators of this family. + Return 0 if the current node doesn't contain accelerators of this family. + """ + + @staticmethod + @abstractmethod + def get_current_node_accelerator_type() -> Optional[str]: + """Get the type of the accelerator of this family on the current node. + + Currently Ray only supports single accelerator type of + an accelerator family on each node. + + The result should only be used when get_current_node_num_accelerators() > 0. + + Returns: + The detected accelerator type of this family: e.g., H100 for NVIDIA GPU. + Return None if it's unknown or the node doesn't have + accelerators of this family. + """ + + @staticmethod + @abstractmethod + def get_current_node_additional_resources() -> Optional[Dict[str, float]]: + """Get any additional resources required for the current node. + + In case a particular accelerator type requires considerations for + additional resources (e.g. for TPUs, providing the TPU pod type and + TPU name), this function can be used to provide the + additional logical resources. + + Returns: + A dictionary representing additional resources that may be + necessary for a particular accelerator type. + """ + + @staticmethod + @abstractmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + """Validate the resource request quantity of this accelerator resource. + + Args: + quantity: The resource request quantity to be validated. + + Returns: + (valid, error_message) tuple: the first element of the tuple + indicates whether the given quantity is valid or not, + the second element is the error message + if the given quantity is invalid. + """ + + @staticmethod + @abstractmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + """Get the ids of accelerators of this family that are visible to the current process. + + Returns: + The list of visiable accelerator ids. + Return None if all accelerators are visible. + """ + + @staticmethod + @abstractmethod + def set_current_process_visible_accelerator_ids(ids: List[str]) -> None: + """Set the ids of accelerators of this family that are visible to the current process. + + Args: + ids: The ids of visible accelerators of this family. + """ + + @staticmethod + def get_ec2_instance_num_accelerators( + instance_type: str, instances: dict + ) -> Optional[int]: + """Get the number of accelerators of this family on ec2 instance with given type. + + Args: + instance_type: The ec2 instance type. + instances: Map from ec2 instance type to instance metadata returned by + ec2 `describe-instance-types`. + + Returns: + The number of accelerators of this family on the ec2 instance + with given type. + Return None if it's unknown. + """ + return None + + @staticmethod + def get_ec2_instance_accelerator_type( + instance_type: str, instances: dict + ) -> Optional[str]: + """Get the accelerator type of this family on ec2 instance with given type. + + Args: + instance_type: The ec2 instance type. + instances: Map from ec2 instance type to instance metadata returned by + ec2 `describe-instance-types`. + + Returns: + The accelerator type of this family on the ec2 instance with given type. + Return None if it's unknown. + """ + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/amd_gpu.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/amd_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..3810de61232b27bacf98320d48325b8fbdf79cca --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/amd_gpu.py @@ -0,0 +1,159 @@ +import logging +import os +from typing import List, Optional, Tuple + +from ray._private.accelerators.accelerator import AcceleratorManager +from ray._private.accelerators.nvidia_gpu import CUDA_VISIBLE_DEVICES_ENV_VAR + +logger = logging.getLogger(__name__) + +HIP_VISIBLE_DEVICES_ENV_VAR = "HIP_VISIBLE_DEVICES" +NOSET_HIP_VISIBLE_DEVICES_ENV_VAR = "RAY_EXPERIMENTAL_NOSET_HIP_VISIBLE_DEVICES" + +amd_product_dict = { + "0x738c": "AMD-Instinct-MI100", + "0x7408": "AMD-Instinct-MI250X", + "0x740c": "AMD-Instinct-MI250X-MI250", + "0x740f": "AMD-Instinct-MI210", + "0x74a0": "AMD-Instinct-MI300A", + "0x74a1": "AMD-Instinct-MI300X-OAM", + "0x74a2": "AMD-Instinct-MI308X-OAM", + "0x74a9": "AMD-Instinct-MI300X-HF", + "0x74a5": "AMD-Instinct-MI325X-OAM", + "0x6798": "AMD-Radeon-R9-200-HD-7900", + "0x6799": "AMD-Radeon-HD-7900", + "0x679A": "AMD-Radeon-HD-7900", + "0x679B": "AMD-Radeon-HD-7900", +} + + +class AMDGPUAcceleratorManager(AcceleratorManager): + """AMD GPU accelerators.""" + + @staticmethod + def get_resource_name() -> str: + return "GPU" + + @staticmethod + def get_visible_accelerator_ids_env_var() -> str: + if ( + HIP_VISIBLE_DEVICES_ENV_VAR not in os.environ + and "ROCR_VISIBLE_DEVICES" in os.environ + ): + raise RuntimeError( + f"Please use {HIP_VISIBLE_DEVICES_ENV_VAR} instead of ROCR_VISIBLE_DEVICES" + ) + + env_var = HIP_VISIBLE_DEVICES_ENV_VAR + if cuda_val := os.environ.get(CUDA_VISIBLE_DEVICES_ENV_VAR, None) is not None: + if hip_val := os.environ.get(HIP_VISIBLE_DEVICES_ENV_VAR, None) is None: + env_var = CUDA_VISIBLE_DEVICES_ENV_VAR + elif hip_val != cuda_val: + raise ValueError( + f"Inconsistant values found. Please use either {HIP_VISIBLE_DEVICES_ENV_VAR} or {CUDA_VISIBLE_DEVICES_ENV_VAR}." + ) + + return env_var + + @staticmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + amd_visible_devices = os.environ.get( + AMDGPUAcceleratorManager.get_visible_accelerator_ids_env_var(), None + ) + + if amd_visible_devices is None: + return None + + if amd_visible_devices == "": + return [] + + if amd_visible_devices == "NoDevFiles": + return [] + + return list(amd_visible_devices.split(",")) + + @staticmethod + def get_current_node_num_accelerators() -> int: + import ray._private.thirdparty.pyamdsmi as pyamdsmi + + num_gpus = 0 + + try: + pyamdsmi.smi_initialize() + num_gpus = pyamdsmi.smi_get_device_count() + except Exception: + pass + finally: + try: + pyamdsmi.smi_shutdown() + except Exception: + pass + + return num_gpus + + @staticmethod + def get_current_node_accelerator_type() -> Optional[str]: + try: + device_ids = AMDGPUAcceleratorManager._get_amd_device_ids() + if device_ids is None: + return None + return AMDGPUAcceleratorManager._gpu_name_to_accelerator_type(device_ids[0]) + except Exception: + return None + + @staticmethod + def _gpu_name_to_accelerator_type(name): + if name is None: + return None + try: + match = amd_product_dict[name] + return match + except Exception: + return None + + @staticmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + return (True, None) + + @staticmethod + def set_current_process_visible_accelerator_ids( + visible_amd_devices: List[str], + ) -> None: + if os.environ.get(NOSET_HIP_VISIBLE_DEVICES_ENV_VAR): + return + + os.environ[ + AMDGPUAcceleratorManager.get_visible_accelerator_ids_env_var() + ] = ",".join([str(i) for i in visible_amd_devices]) + + @staticmethod + def _get_amd_device_ids() -> List[str]: + """Get the list of GPUs IDs + Example: + On a node with 2x MI210 GPUs + pyamdsmi library python bindings + return: ['0x740f', '0x740f'] + Returns: + A list of strings containing GPU IDs + """ + import ray._private.thirdparty.pyamdsmi as pyamdsmi + + device_ids = [] + try: + pyamdsmi.smi_initialize() + num_devices = pyamdsmi.smi_get_device_count() + for i in range(num_devices): + did = pyamdsmi.smi_get_device_id(i) + if did >= 0: + device_ids.append(hex(did)) + except Exception: + return None + finally: + try: + pyamdsmi.pyamdsmi_shutdown() + except Exception: + pass + + return device_ids diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/hpu.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/hpu.py new file mode 100644 index 0000000000000000000000000000000000000000..0f5d16b2761e57f76d15db70ec4f8696310e28b2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/hpu.py @@ -0,0 +1,121 @@ +import logging +import os +from functools import lru_cache +from importlib.util import find_spec +from typing import List, Optional, Tuple + +from ray._private.accelerators.accelerator import AcceleratorManager + +logger = logging.getLogger(__name__) + +HABANA_VISIBLE_DEVICES_ENV_VAR = "HABANA_VISIBLE_MODULES" +NOSET_HABANA_VISIBLE_MODULES_ENV_VAR = "RAY_EXPERIMENTAL_NOSET_HABANA_VISIBLE_MODULES" + + +@lru_cache() +def is_package_present(package_name: str) -> bool: + try: + return find_spec(package_name) is not None + except ModuleNotFoundError: + return False + + +HPU_PACKAGE_AVAILABLE = is_package_present("habana_frameworks") + + +class HPUAcceleratorManager(AcceleratorManager): + """Intel Habana(HPU) accelerators.""" + + @staticmethod + def get_resource_name() -> str: + return "HPU" + + @staticmethod + def get_visible_accelerator_ids_env_var() -> str: + return HABANA_VISIBLE_DEVICES_ENV_VAR + + @staticmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + hpu_visible_devices = os.environ.get( + HPUAcceleratorManager.get_visible_accelerator_ids_env_var(), None + ) + + if hpu_visible_devices is None: + return None + + if hpu_visible_devices == "": + return [] + + return list(hpu_visible_devices.split(",")) + + @staticmethod + def get_current_node_num_accelerators() -> int: + """Attempt to detect the number of HPUs on this machine. + Returns: + The number of HPUs if any were detected, otherwise 0. + """ + if HPU_PACKAGE_AVAILABLE: + import habana_frameworks.torch.hpu as torch_hpu + + if torch_hpu.is_available(): + return torch_hpu.device_count() + else: + logging.info("HPU devices not available") + return 0 + else: + return 0 + + @staticmethod + def is_initialized() -> bool: + """Attempt to check if HPU backend is initialized. + Returns: + True if backend initialized else False. + """ + if HPU_PACKAGE_AVAILABLE: + import habana_frameworks.torch.hpu as torch_hpu + + if torch_hpu.is_available() and torch_hpu.is_initialized(): + return True + else: + return False + else: + return False + + @staticmethod + def get_current_node_accelerator_type() -> Optional[str]: + """Attempt to detect the HPU family type. + Returns: + The device name (GAUDI, GAUDI2) if detected else None. + """ + if HPUAcceleratorManager.is_initialized(): + import habana_frameworks.torch.hpu as torch_hpu + + return f"Intel-{torch_hpu.get_device_name()}" + else: + logging.info("HPU type cannot be detected") + return None + + @staticmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + if isinstance(quantity, float) and not quantity.is_integer(): + return ( + False, + f"{HPUAcceleratorManager.get_resource_name()} resource quantity" + " must be whole numbers. " + f"The specified quantity {quantity} is invalid.", + ) + else: + return (True, None) + + @staticmethod + def set_current_process_visible_accelerator_ids( + visible_hpu_devices: List[str], + ) -> None: + if os.environ.get(NOSET_HABANA_VISIBLE_MODULES_ENV_VAR): + return + + os.environ[ + HPUAcceleratorManager.get_visible_accelerator_ids_env_var() + ] = ",".join([str(i) for i in visible_hpu_devices]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/intel_gpu.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/intel_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..8bace1f203668f8d23329922673fc131592335c5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/intel_gpu.py @@ -0,0 +1,103 @@ +import logging +import os +from typing import List, Optional, Tuple + +from ray._private.accelerators.accelerator import AcceleratorManager + +logger = logging.getLogger(__name__) + +ONEAPI_DEVICE_SELECTOR_ENV_VAR = "ONEAPI_DEVICE_SELECTOR" +NOSET_ONEAPI_DEVICE_SELECTOR_ENV_VAR = "RAY_EXPERIMENTAL_NOSET_ONEAPI_DEVICE_SELECTOR" +ONEAPI_DEVICE_BACKEND_TYPE = "level_zero" +ONEAPI_DEVICE_TYPE = "gpu" + + +class IntelGPUAcceleratorManager(AcceleratorManager): + """Intel GPU accelerators.""" + + @staticmethod + def get_resource_name() -> str: + return "GPU" + + @staticmethod + def get_visible_accelerator_ids_env_var() -> str: + return ONEAPI_DEVICE_SELECTOR_ENV_VAR + + @staticmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + oneapi_visible_devices = os.environ.get( + IntelGPUAcceleratorManager.get_visible_accelerator_ids_env_var(), None + ) + if oneapi_visible_devices is None: + return None + + if oneapi_visible_devices == "": + return [] + + if oneapi_visible_devices == "NoDevFiles": + return [] + + prefix = ONEAPI_DEVICE_BACKEND_TYPE + ":" + + return list(oneapi_visible_devices.split(prefix)[1].split(",")) + + @staticmethod + def get_current_node_num_accelerators() -> int: + try: + import dpctl + except ImportError: + dpctl = None + if dpctl is None: + return 0 + + num_gpus = 0 + try: + dev_info = ONEAPI_DEVICE_BACKEND_TYPE + ":" + ONEAPI_DEVICE_TYPE + context = dpctl.SyclContext(dev_info) + num_gpus = context.device_count + except Exception: + num_gpus = 0 + return num_gpus + + @staticmethod + def get_current_node_accelerator_type() -> Optional[str]: + """Get the name of first Intel GPU. (supposed only one GPU type on a node) + Example: + name: 'Intel(R) Data Center GPU Max 1550' + return name: 'Intel-GPU-Max-1550' + Returns: + A string representing the name of Intel GPU type. + """ + try: + import dpctl + except ImportError: + dpctl = None + if dpctl is None: + return None + + accelerator_type = None + try: + dev_info = ONEAPI_DEVICE_BACKEND_TYPE + ":" + ONEAPI_DEVICE_TYPE + ":0" + dev = dpctl.SyclDevice(dev_info) + accelerator_type = "Intel-GPU-" + "-".join(dev.name.split(" ")[-2:]) + except Exception: + accelerator_type = None + return accelerator_type + + @staticmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + return (True, None) + + @staticmethod + def set_current_process_visible_accelerator_ids( + visible_xpu_devices: List[str], + ) -> None: + if os.environ.get(NOSET_ONEAPI_DEVICE_SELECTOR_ENV_VAR): + return + + prefix = ONEAPI_DEVICE_BACKEND_TYPE + ":" + os.environ[ + IntelGPUAcceleratorManager.get_visible_accelerator_ids_env_var() + ] = prefix + ",".join([str(i) for i in visible_xpu_devices]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/neuron.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/neuron.py new file mode 100644 index 0000000000000000000000000000000000000000..a2799e3e8110b973cb5e78d086f5f4560588570f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/neuron.py @@ -0,0 +1,132 @@ +import json +import logging +import os +import subprocess +import sys +from typing import List, Optional, Tuple + +from ray._private.accelerators.accelerator import AcceleratorManager + +logger = logging.getLogger(__name__) + +NEURON_RT_VISIBLE_CORES_ENV_VAR = "NEURON_RT_VISIBLE_CORES" +NOSET_AWS_NEURON_RT_VISIBLE_CORES_ENV_VAR = ( + "RAY_EXPERIMENTAL_NOSET_NEURON_RT_VISIBLE_CORES" +) + +# https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/neuron-hardware/inf2-arch.html#aws-inf2-arch +# https://awsdocs-neuron.readthedocs-hosted.com/en/latest/general/arch/neuron-hardware/trn1-arch.html#aws-trn1-arch +# Subject to removal after the information is available via public API +AWS_NEURON_INSTANCE_MAP = { + "trn1.2xlarge": 2, + "trn1.32xlarge": 32, + "trn1n.32xlarge": 32, + "inf2.xlarge": 2, + "inf2.8xlarge": 2, + "inf2.24xlarge": 12, + "inf2.48xlarge": 24, +} + + +class NeuronAcceleratorManager(AcceleratorManager): + """AWS Inferentia and Trainium accelerators.""" + + @staticmethod + def get_resource_name() -> str: + return "neuron_cores" + + @staticmethod + def get_visible_accelerator_ids_env_var() -> str: + return NEURON_RT_VISIBLE_CORES_ENV_VAR + + @staticmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + neuron_visible_cores = os.environ.get( + NeuronAcceleratorManager.get_visible_accelerator_ids_env_var(), None + ) + + if neuron_visible_cores is None: + return None + + if neuron_visible_cores == "": + return [] + + return list(neuron_visible_cores.split(",")) + + @staticmethod + def get_current_node_num_accelerators() -> int: + """ + Attempt to detect the number of Neuron cores on this machine. + + Returns: + The number of Neuron cores if any were detected, otherwise 0. + """ + nc_count: int = 0 + neuron_path = "/opt/aws/neuron/bin/" + if sys.platform.startswith("linux") and os.path.isdir(neuron_path): + result = subprocess.run( + [os.path.join(neuron_path, "neuron-ls"), "--json-output"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + if result.returncode == 0 and result.stdout: + neuron_devices = json.loads(result.stdout) + for neuron_device in neuron_devices: + nc_count += neuron_device.get("nc_count", 0) + return nc_count + + @staticmethod + def get_current_node_accelerator_type() -> Optional[str]: + from ray.util.accelerators import AWS_NEURON_CORE + + return AWS_NEURON_CORE + + @staticmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + if isinstance(quantity, float) and not quantity.is_integer(): + return ( + False, + f"{NeuronAcceleratorManager.get_resource_name()} resource quantity" + " must be whole numbers. " + f"The specified quantity {quantity} is invalid.", + ) + else: + return (True, None) + + @staticmethod + def set_current_process_visible_accelerator_ids( + visible_neuron_core_ids: List[str], + ) -> None: + """Set the NEURON_RT_VISIBLE_CORES environment variable based on + given visible_neuron_core_ids. + + Args: + visible_neuron_core_ids (List[str]): List of int representing core IDs. + """ + if os.environ.get(NOSET_AWS_NEURON_RT_VISIBLE_CORES_ENV_VAR): + return + + os.environ[ + NeuronAcceleratorManager.get_visible_accelerator_ids_env_var() + ] = ",".join([str(i) for i in visible_neuron_core_ids]) + + @staticmethod + def get_ec2_instance_num_accelerators( + instance_type: str, instances: dict + ) -> Optional[int]: + # TODO: AWS SDK (public API) doesn't yet expose the NeuronCore + # information. It will be available (work-in-progress) + # as xxAcceleratorInfo in InstanceTypeInfo. + # https://docs.aws.amazon.com/AWSEC2/latest/APIReference/API_InstanceTypeInfo.html + # See https://github.com/ray-project/ray/issues/38473 + return AWS_NEURON_INSTANCE_MAP.get(instance_type.lower(), None) + + @staticmethod + def get_ec2_instance_accelerator_type( + instance_type: str, instances: dict + ) -> Optional[str]: + from ray.util.accelerators import AWS_NEURON_CORE + + return AWS_NEURON_CORE diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/npu.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/npu.py new file mode 100644 index 0000000000000000000000000000000000000000..ab470619e0453c4810b20846f73630d7e62a14fa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/npu.py @@ -0,0 +1,99 @@ +import glob +import logging +import os +from typing import List, Optional, Tuple + +from ray._private.accelerators.accelerator import AcceleratorManager + +logger = logging.getLogger(__name__) + +ASCEND_RT_VISIBLE_DEVICES_ENV_VAR = "ASCEND_RT_VISIBLE_DEVICES" +NOSET_ASCEND_RT_VISIBLE_DEVICES_ENV_VAR = ( + "RAY_EXPERIMENTAL_NOSET_ASCEND_RT_VISIBLE_DEVICES" +) + + +class NPUAcceleratorManager(AcceleratorManager): + """Ascend NPU accelerators.""" + + @staticmethod + def get_resource_name() -> str: + return "NPU" + + @staticmethod + def get_visible_accelerator_ids_env_var() -> str: + return ASCEND_RT_VISIBLE_DEVICES_ENV_VAR + + @staticmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + ascend_visible_devices = os.environ.get( + NPUAcceleratorManager.get_visible_accelerator_ids_env_var(), None + ) + + if ascend_visible_devices is None: + return None + + if ascend_visible_devices == "": + return [] + + if ascend_visible_devices == "NoDevFiles": + return [] + + return list(ascend_visible_devices.split(",")) + + @staticmethod + def get_current_node_num_accelerators() -> int: + """Attempt to detect the number of NPUs on this machine. + + NPU chips are represented as devices within `/dev/`, either as `/dev/davinci?`. + + Returns: + The number of NPUs if any were detected, otherwise 0. + """ + try: + import acl + + device_count, ret = acl.rt.get_device_count() + if ret == 0: + return device_count + except Exception as e: + logger.debug("Could not import AscendCL: %s", e) + + try: + npu_files = glob.glob("/dev/davinci[0-9]*") + return len(npu_files) + except Exception as e: + logger.debug("Failed to detect number of NPUs: %s", e) + return 0 + + @staticmethod + def get_current_node_accelerator_type() -> Optional[str]: + """Get the type of the Ascend NPU on the current node. + + Returns: + A string of the type, such as "Ascend910A", "Ascend910B", "Ascend310P1". + """ + try: + import acl + + return acl.get_soc_name() + except Exception: + logger.exception("Failed to detect NPU type.") + return None + + @staticmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + return (True, None) + + @staticmethod + def set_current_process_visible_accelerator_ids( + visible_npu_devices: List[str], + ) -> None: + if os.environ.get(NOSET_ASCEND_RT_VISIBLE_DEVICES_ENV_VAR): + return + + os.environ[ + NPUAcceleratorManager.get_visible_accelerator_ids_env_var() + ] = ",".join([str(i) for i in visible_npu_devices]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/nvidia_gpu.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/nvidia_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..bfd98ab377d6e71bd3123ef84c0db75f05031656 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/nvidia_gpu.py @@ -0,0 +1,128 @@ +import logging +import os +import re +from typing import List, Optional, Tuple + +from ray._private.accelerators.accelerator import AcceleratorManager + +logger = logging.getLogger(__name__) + +CUDA_VISIBLE_DEVICES_ENV_VAR = "CUDA_VISIBLE_DEVICES" +NOSET_CUDA_VISIBLE_DEVICES_ENV_VAR = "RAY_EXPERIMENTAL_NOSET_CUDA_VISIBLE_DEVICES" + +# TODO(Alex): This pattern may not work for non NVIDIA Tesla GPUs (which have +# the form "Tesla V100-SXM2-16GB" or "Tesla K80"). +NVIDIA_GPU_NAME_PATTERN = re.compile(r"\w+\s+([A-Z0-9]+)") + + +class NvidiaGPUAcceleratorManager(AcceleratorManager): + """NVIDIA GPU accelerators.""" + + @staticmethod + def get_resource_name() -> str: + return "GPU" + + @staticmethod + def get_visible_accelerator_ids_env_var() -> str: + return CUDA_VISIBLE_DEVICES_ENV_VAR + + @staticmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + cuda_visible_devices = os.environ.get( + NvidiaGPUAcceleratorManager.get_visible_accelerator_ids_env_var(), None + ) + if cuda_visible_devices is None: + return None + + if cuda_visible_devices == "": + return [] + + if cuda_visible_devices == "NoDevFiles": + return [] + + return list(cuda_visible_devices.split(",")) + + @staticmethod + def get_current_node_num_accelerators() -> int: + import ray._private.thirdparty.pynvml as pynvml + + try: + pynvml.nvmlInit() + except pynvml.NVMLError: + return 0 # pynvml init failed + device_count = pynvml.nvmlDeviceGetCount() + pynvml.nvmlShutdown() + return device_count + + @staticmethod + def get_current_node_accelerator_type() -> Optional[str]: + import ray._private.thirdparty.pynvml as pynvml + + try: + pynvml.nvmlInit() + except pynvml.NVMLError: + return None # pynvml init failed + device_count = pynvml.nvmlDeviceGetCount() + cuda_device_type = None + if device_count > 0: + handle = pynvml.nvmlDeviceGetHandleByIndex(0) + device_name = pynvml.nvmlDeviceGetName(handle) + if isinstance(device_name, bytes): + device_name = device_name.decode("utf-8") + cuda_device_type = ( + NvidiaGPUAcceleratorManager._gpu_name_to_accelerator_type(device_name) + ) + pynvml.nvmlShutdown() + return cuda_device_type + + @staticmethod + def _gpu_name_to_accelerator_type(name): + if name is None: + return None + match = NVIDIA_GPU_NAME_PATTERN.match(name) + return match.group(1) if match else None + + @staticmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + return (True, None) + + @staticmethod + def set_current_process_visible_accelerator_ids( + visible_cuda_devices: List[str], + ) -> None: + if os.environ.get(NOSET_CUDA_VISIBLE_DEVICES_ENV_VAR): + return + + os.environ[ + NvidiaGPUAcceleratorManager.get_visible_accelerator_ids_env_var() + ] = ",".join([str(i) for i in visible_cuda_devices]) + + @staticmethod + def get_ec2_instance_num_accelerators( + instance_type: str, instances: dict + ) -> Optional[int]: + if instance_type not in instances: + return None + + gpus = instances[instance_type].get("GpuInfo", {}).get("Gpus") + if gpus is not None: + # TODO(ameer): currently we support one gpu type per node. + assert len(gpus) == 1 + return gpus[0]["Count"] + return None + + @staticmethod + def get_ec2_instance_accelerator_type( + instance_type: str, instances: dict + ) -> Optional[str]: + if instance_type not in instances: + return None + + gpus = instances[instance_type].get("GpuInfo", {}).get("Gpus") + if gpus is not None: + # TODO(ameer): currently we support one gpu type per node. + assert len(gpus) == 1 + return gpus[0]["Name"] + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/tpu.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..190fa6f0b0158feb412d3b00c9aa78cd910642ac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/accelerators/tpu.py @@ -0,0 +1,439 @@ +import glob +import logging +import os +import re +from functools import lru_cache +from typing import Dict, List, Optional, Tuple + +import requests + +from ray._private.accelerators.accelerator import AcceleratorManager + +logger = logging.getLogger(__name__) + + +TPU_VALID_CHIP_OPTIONS = (1, 2, 4, 8) +GKE_TPU_ACCELERATOR_TYPE_ENV_VAR = "TPU_ACCELERATOR_TYPE" +GKE_TPU_WORKER_ID_ENV_VAR = "TPU_WORKER_ID" +GKE_TPU_NAME_ENV_VAR = "TPU_NAME" + +# Constants for accessing the `accelerator-type` from TPU VM +# instance metadata. +# See https://cloud.google.com/compute/docs/metadata/overview +# for more details about VM instance metadata. +GCE_TPU_ACCELERATOR_ENDPOINT = ( + "http://metadata.google.internal/computeMetadata/v1/instance/attributes/" +) +GCE_TPU_HEADERS = {"Metadata-Flavor": "Google"} +GCE_TPU_ACCELERATOR_KEY = "accelerator-type" +GCE_TPU_INSTANCE_ID_KEY = "instance-id" +GCE_TPU_WORKER_ID_KEY = "agent-worker-number" + +TPU_VISIBLE_CHIPS_ENV_VAR = "TPU_VISIBLE_CHIPS" + +NOSET_TPU_VISIBLE_CHIPS_ENV_VAR = "RAY_EXPERIMENTAL_NOSET_TPU_VISIBLE_CHIPS" + +# The following defines environment variables that allow +# us to access a subset of TPU visible chips. +# +# See: https://github.com/google/jax/issues/14977 for an example/more details. +TPU_CHIPS_PER_HOST_BOUNDS_ENV_VAR = "TPU_CHIPS_PER_HOST_BOUNDS" +TPU_CHIPS_PER_HOST_BOUNDS_1_CHIP_CONFIG = "1,1,1" +TPU_CHIPS_PER_HOST_BOUNDS_2_CHIP_CONFIG = "1,2,1" + +TPU_HOST_BOUNDS_ENV_VAR = "TPU_HOST_BOUNDS" +TPU_SINGLE_HOST_BOUNDS = "1,1,1" + +# By default TPU VMs come with 4 chips per host and 2 tensorcores per chip. +# For more details: https://cloud.google.com/tpu/docs/system-architecture-tpu-vm +DEFAULT_TPU_NUM_CHIPS_PER_HOST = 4 +DEFAULT_TPU_NUM_CORES_PER_CHIP = 2 + +# Accelerators that are 4 chips per host: v2, v3, v4, v5p +# Accelerators that are 8 chips per host: v5e, v6e +SINGLE_HOST_8_CHIPS_TPU_TYPES = ("v5litepod", "v6e") + +# Accelerators that are 2 cores per chip: v2, v3, v4, v5p +# Accelerators that are 1 core per chip: v5e, v6e +SINGLE_CORE_TPU_TYPES = ("v5litepod", "v6e") + +# The valid TPU types. +VALID_TPU_TYPES = ("v2", "v3", "v4", "v5p", "v5litepod", "v6e") + + +def _get_tpu_metadata(key: str) -> Optional[str]: + """Poll and get TPU metadata.""" + try: + accelerator_type_request = requests.get( + os.path.join(GCE_TPU_ACCELERATOR_ENDPOINT, key), + headers=GCE_TPU_HEADERS, + ) + if ( + accelerator_type_request.status_code == 200 + and accelerator_type_request.text + ): + return accelerator_type_request.text + else: + logging.debug( + "Unable to poll TPU GCE Metadata. Got " + f"status code: {accelerator_type_request.status_code} and " + f"content: {accelerator_type_request.text}" + ) + except requests.RequestException as e: + logging.debug("Unable to poll the TPU GCE Metadata: %s", e) + return None + + +def _accelerator_type_check(accelerator_type: str): + if not accelerator_type.startswith(VALID_TPU_TYPES): + raise ValueError( + f"Invalid accelerator type: {accelerator_type}. Must start with one of: {VALID_TPU_TYPES}" + ) + + +def get_num_tpu_visible_chips_per_host(accelerator_type: str) -> int: + _accelerator_type_check(accelerator_type) + if accelerator_type.startswith(SINGLE_HOST_8_CHIPS_TPU_TYPES): + return 8 + + return DEFAULT_TPU_NUM_CHIPS_PER_HOST + + +def get_tpu_cores_per_chip(accelerator_type: str) -> int: + _accelerator_type_check(accelerator_type) + if accelerator_type.startswith(SINGLE_CORE_TPU_TYPES): + return 1 + + return DEFAULT_TPU_NUM_CORES_PER_CHIP + + +class TPUAcceleratorManager(AcceleratorManager): + """Google TPU accelerators.""" + + @staticmethod + def get_resource_name() -> str: + return "TPU" + + @staticmethod + def get_visible_accelerator_ids_env_var() -> str: + return TPU_VISIBLE_CHIPS_ENV_VAR + + @staticmethod + def get_current_process_visible_accelerator_ids() -> Optional[List[str]]: + tpu_visible_chips = os.environ.get( + TPUAcceleratorManager.get_visible_accelerator_ids_env_var(), None + ) + + if tpu_visible_chips is None: + return None + + if tpu_visible_chips == "": + return [] + + return list(tpu_visible_chips.split(",")) + + @staticmethod + @lru_cache() + def get_current_node_num_accelerators() -> int: + """Attempt to detect the number of TPUs on this machine. + + TPU chips are represented as devices within `/dev/`, either as + `/dev/accel*` or `/dev/vfio/*`. + + Returns: + The number of TPUs if any were detected, otherwise 0. + """ + accel_files = glob.glob("/dev/accel*") + if accel_files: + return len(accel_files) + + try: + vfio_entries = os.listdir("/dev/vfio") + numeric_entries = [int(entry) for entry in vfio_entries if entry.isdigit()] + return len(numeric_entries) + except FileNotFoundError as e: + logger.debug("Failed to detect number of TPUs: %s", e) + return 0 + + @staticmethod + def is_valid_tpu_accelerator_type(tpu_accelerator_type: str) -> bool: + """Check whether the tpu accelerator_type is formatted correctly. + + The accelerator_type field follows a form of v{generation}-{cores/chips}. + + See the following for more information: + https://cloud.google.com/sdk/gcloud/reference/compute/tpus/tpu-vm/accelerator-types/describe + + Args: + tpu_accelerator_type: The string representation of the accelerator type + to be checked for validity. + + Returns: + True if it's valid, false otherwise. + """ + expected_pattern = re.compile(r"^v\d+[a-zA-Z]*-\d+$") + if not expected_pattern.match(tpu_accelerator_type): + return False + return True + + @staticmethod + def validate_resource_request_quantity( + quantity: float, + ) -> Tuple[bool, Optional[str]]: + if quantity not in TPU_VALID_CHIP_OPTIONS: + return ( + False, + f"The number of requested 'TPU' was set to {quantity} which " + "is not a supported chip configuration. Supported configs: " + f"{TPU_VALID_CHIP_OPTIONS}", + ) + else: + return (True, None) + + @staticmethod + def set_current_process_visible_accelerator_ids( + visible_tpu_chips: List[str], + ) -> None: + """Set TPU environment variables based on the provided visible_tpu_chips. + + To access a subset of the TPU visible chips, we must use a combination of + environment variables that tells the compiler (via ML framework) the: + - Visible chips + - The physical bounds of chips per host + - The host bounds within the context of a TPU pod. + + See: https://github.com/google/jax/issues/14977 for an example/more details. + + Args: + visible_tpu_chips (List[str]): List of int representing TPU chips. + """ + if os.environ.get(NOSET_TPU_VISIBLE_CHIPS_ENV_VAR): + return + + num_visible_tpu_chips = len(visible_tpu_chips) + num_accelerators_on_node = ( + TPUAcceleratorManager.get_current_node_num_accelerators() + ) + if num_visible_tpu_chips == num_accelerators_on_node: + # Let the ML framework use the defaults + os.environ.pop(TPU_CHIPS_PER_HOST_BOUNDS_ENV_VAR, None) + os.environ.pop(TPU_HOST_BOUNDS_ENV_VAR, None) + return + os.environ[ + TPUAcceleratorManager.get_visible_accelerator_ids_env_var() + ] = ",".join([str(i) for i in visible_tpu_chips]) + if num_visible_tpu_chips == 1: + os.environ[ + TPU_CHIPS_PER_HOST_BOUNDS_ENV_VAR + ] = TPU_CHIPS_PER_HOST_BOUNDS_1_CHIP_CONFIG + os.environ[TPU_HOST_BOUNDS_ENV_VAR] = TPU_SINGLE_HOST_BOUNDS + elif num_visible_tpu_chips == 2: + os.environ[ + TPU_CHIPS_PER_HOST_BOUNDS_ENV_VAR + ] = TPU_CHIPS_PER_HOST_BOUNDS_2_CHIP_CONFIG + os.environ[TPU_HOST_BOUNDS_ENV_VAR] = TPU_SINGLE_HOST_BOUNDS + + @staticmethod + def _get_current_node_tpu_pod_type() -> Optional[str]: + """Get the TPU pod type of the current node if applicable. + + Individual TPU VMs within a TPU pod must know what type + of pod it is a part of. This is necessary for the + ML framework to work properly. + + The logic is different if the TPU was provisioned via: + ``` + gcloud tpus tpu-vm create ... + ``` + (i.e. a GCE VM), vs through GKE: + - GCE VMs will always have a metadata server to poll this info + - GKE VMS will have environment variables preset. + + Returns: + A string representing the current TPU pod type, e.g. + v4-16. + + """ + # Start with GKE-based check + accelerator_type = os.getenv(GKE_TPU_ACCELERATOR_TYPE_ENV_VAR, "") + if not accelerator_type: + # GCE-based VM check + accelerator_type = _get_tpu_metadata(key=GCE_TPU_ACCELERATOR_KEY) + if accelerator_type and TPUAcceleratorManager.is_valid_tpu_accelerator_type( + tpu_accelerator_type=accelerator_type + ): + return accelerator_type + logging.debug("Failed to get a valid accelerator type.") + return None + + @staticmethod + def get_current_node_tpu_name() -> Optional[str]: + """Return the name of the TPU pod that this worker node is a part of. + + For instance, if the TPU was created with name "my-tpu", this function + will return "my-tpu". + + If created through the Ray cluster launcher, the + name will typically be something like "ray-my-tpu-cluster-worker-aa946781-tpu". + + In case the TPU was created through KubeRay, we currently expect that the + environment variable TPU_NAME is set per TPU pod slice, in which case + this function will return the value of that environment variable. + + """ + try: + # Start with GKE-based check + tpu_name = os.getenv(GKE_TPU_NAME_ENV_VAR, None) + if not tpu_name: + # GCE-based VM check + tpu_name = _get_tpu_metadata(key=GCE_TPU_INSTANCE_ID_KEY) + return tpu_name + except ValueError as e: + logging.debug("Could not get TPU name: %s", e) + return None + + @staticmethod + def _get_current_node_tpu_worker_id() -> Optional[int]: + """Return the worker index of the TPU pod.""" + try: + # Start with GKE-based check + worker_id = os.getenv(GKE_TPU_WORKER_ID_ENV_VAR, None) + if not worker_id: + # GCE-based VM check + worker_id = _get_tpu_metadata(key=GCE_TPU_WORKER_ID_KEY) + if worker_id: + return int(worker_id) + else: + return None + except ValueError as e: + logging.debug("Could not get TPU worker id: %s", e) + return None + + @staticmethod + def get_num_workers_in_current_tpu_pod() -> Optional[int]: + """Return the total number of workers in a TPU pod.""" + tpu_pod_type = TPUAcceleratorManager._get_current_node_tpu_pod_type() + chips_per_host = TPUAcceleratorManager.get_current_node_num_accelerators() + cores_per_chip = get_tpu_cores_per_chip(tpu_pod_type) # Hard-coded map. + cores_per_host = chips_per_host * cores_per_chip + if tpu_pod_type and cores_per_host > 0: + num_cores = int(tpu_pod_type.split("-")[1]) + num_workers = num_cores // cores_per_host + # If the chip count doesn't fill a full host, a sub-host is still treated as a host. + if num_cores % cores_per_host != 0: + num_workers += 1 + return num_workers + else: + logging.debug("Could not get num workers in TPU pod.") + return None + + @staticmethod + def get_current_node_accelerator_type() -> Optional[str]: + """Attempt to detect the TPU accelerator type. + + The output of this function will return the "ray accelerator type" + resource (e.g. TPU-V4) that indicates the TPU version. + + We also expect that our TPU nodes contain a "TPU pod type" + resource, which indicates information about the topology of + the TPU pod slice. + + We expect that the "TPU pod type" resource to be used when + running multi host workers, i.e. when TPU units are pod slices. + + We expect that the "ray accelerator type" resource to be used when + running single host workers, i.e. when TPU units are single hosts. + + Returns: + A string representing the TPU accelerator type, + e.g. "TPU-V2", "TPU-V3", "TPU-V4" if applicable, else None. + + """ + + def tpu_pod_type_to_ray_accelerator_type( + tpu_pod_type: str, + ) -> Optional[str]: + return "TPU-" + str(tpu_pod_type.split("-")[0].upper()) + + ray_accelerator_type = None + tpu_pod_type = TPUAcceleratorManager._get_current_node_tpu_pod_type() + + if tpu_pod_type is not None: + ray_accelerator_type = tpu_pod_type_to_ray_accelerator_type( + tpu_pod_type=tpu_pod_type + ) + if ray_accelerator_type is None: + logger.info( + "While trying to autodetect a TPU type, " + f"received malformed accelerator_type: {tpu_pod_type}" + ) + + if ray_accelerator_type is None: + logging.info("Failed to auto-detect TPU type.") + + return ray_accelerator_type + + def get_current_node_additional_resources() -> Optional[Dict[str, float]]: + """Get additional resources required for TPU nodes. + + This will populate the TPU pod type and the TPU name which + is used for TPU pod execution. + + When running workloads on a TPU pod, we need a way to run + the same binary on every worker in the TPU pod. + + See https://jax.readthedocs.io/en/latest/multi_process.html + for more information. + + To do this in ray, we take advantage of custom resources. We + mark worker 0 of the TPU pod as a "coordinator" that identifies + the other workers in the TPU pod. We therefore need: + - worker 0 to be targetable. + - all workers in the TPU pod to have a unique identifier consistent + within a TPU pod. + + So assuming we want to run the following workload: + + @ray.remote + def my_jax_fn(): + import jax + return jax.device_count() + + We could broadcast this on a TPU pod (e.g. a v4-16) as follows: + + @ray.remote(resources={"TPU-v4-16-head"}) + def run_jax_fn(executable): + # Note this will execute on worker 0 + tpu_name = ray.util.accelerators.tpu.get_tpu_pod_name() + num_workers = ray.util.accelerators.tpu.get_tpu_num_workers() + tpu_executable = executable.options(resources={"TPU": 4, tpu_name: 1}) + return [tpu_executable.remote() for _ in range(num_workers)] + + Returns: + A dictionary representing additional resources that may be + necessary for a particular accelerator type. + + """ + resources = {} + tpu_name = TPUAcceleratorManager.get_current_node_tpu_name() + worker_id = TPUAcceleratorManager._get_current_node_tpu_worker_id() + tpu_pod_type = TPUAcceleratorManager._get_current_node_tpu_pod_type() + + if tpu_name and worker_id is not None and tpu_pod_type: + pod_head_resource_name = f"TPU-{tpu_pod_type}-head" + # Add the name of the TPU to the resource. + resources[tpu_name] = 1 + # Only add in the TPU pod type resource to worker 0. + if worker_id == 0: + resources[pod_head_resource_name] = 1 + else: + logging.info( + "Failed to configure TPU pod. Got: " + "tpu_name: %s, worker_id: %s, accelerator_type: %s", + tpu_name, + worker_id, + tpu_pod_type, + ) + if resources: + return resources + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/arrow_serialization.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/arrow_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..925557d6d3d77312df47eb08c49199a0b4fa9e7b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/arrow_serialization.py @@ -0,0 +1,804 @@ +# arrow_serialization.py must resides outside of ray.data, otherwise +# it causes circular dependency issues for AsyncActors due to +# ray.data's lazy import. +# see https://github.com/ray-project/ray/issues/30498 for more context. +import logging +import os +import sys +from dataclasses import dataclass +from typing import TYPE_CHECKING, List, Optional, Tuple + +from ray._private.utils import is_in_test + +if TYPE_CHECKING: + import pyarrow + + from ray.data.extensions import ArrowTensorArray + +RAY_DISABLE_CUSTOM_ARROW_JSON_OPTIONS_SERIALIZATION = ( + "RAY_DISABLE_CUSTOM_ARROW_JSON_OPTIONS_SERIALIZATION" +) +RAY_DISABLE_CUSTOM_ARROW_DATA_SERIALIZATION = ( + "RAY_DISABLE_CUSTOM_ARROW_DATA_SERIALIZATION" +) + +logger = logging.getLogger(__name__) + +# Whether we have already warned the user about bloated fallback serialization. +_serialization_fallback_set = set() + + +def _register_custom_datasets_serializers(serialization_context): + try: + import pyarrow as pa # noqa: F401 + except ModuleNotFoundError: + # No pyarrow installed so not using Arrow, so no need for custom serializers. + return + + # Register all custom serializers required by Datasets. + _register_arrow_data_serializer(serialization_context) + _register_arrow_json_readoptions_serializer(serialization_context) + _register_arrow_json_parseoptions_serializer(serialization_context) + + +# Register custom Arrow JSON ReadOptions serializer to workaround it not being picklable +# in Arrow < 8.0.0. +def _register_arrow_json_readoptions_serializer(serialization_context): + if ( + os.environ.get( + RAY_DISABLE_CUSTOM_ARROW_JSON_OPTIONS_SERIALIZATION, + "0", + ) + == "1" + ): + return + + import pyarrow.json as pajson + + serialization_context._register_cloudpickle_serializer( + pajson.ReadOptions, + custom_serializer=lambda opts: (opts.use_threads, opts.block_size), + custom_deserializer=lambda args: pajson.ReadOptions(*args), + ) + + +def _register_arrow_json_parseoptions_serializer(serialization_context): + if ( + os.environ.get( + RAY_DISABLE_CUSTOM_ARROW_JSON_OPTIONS_SERIALIZATION, + "0", + ) + == "1" + ): + return + + import pyarrow.json as pajson + + serialization_context._register_cloudpickle_serializer( + pajson.ParseOptions, + custom_serializer=lambda opts: ( + opts.explicit_schema, + opts.newlines_in_values, + opts.unexpected_field_behavior, + ), + custom_deserializer=lambda args: pajson.ParseOptions(*args), + ) + + +# Register custom Arrow data serializer to work around zero-copy slice pickling bug. +# See https://issues.apache.org/jira/browse/ARROW-10739. +def _register_arrow_data_serializer(serialization_context): + """Custom reducer for Arrow data that works around a zero-copy slicing pickling + bug by using the Arrow IPC format for the underlying serialization. + + Background: + Arrow has both array-level slicing and buffer-level slicing; both are zero-copy, + but the former has a serialization bug where the entire buffer is serialized + instead of just the slice, while the latter's serialization works as expected + and only serializes the slice of the buffer. I.e., array-level slicing doesn't + propagate the slice down to the buffer when serializing the array. + + We work around this by registering a custom cloudpickle reducers for Arrow + Tables that delegates serialization to the Arrow IPC format; thankfully, Arrow's + IPC serialization has fixed this buffer truncation bug. + + See https://issues.apache.org/jira/browse/ARROW-10739. + """ + if os.environ.get(RAY_DISABLE_CUSTOM_ARROW_DATA_SERIALIZATION, "0") == "1": + return + + import pyarrow as pa + + serialization_context._register_cloudpickle_reducer(pa.Table, _arrow_table_reduce) + + +def _arrow_table_reduce(t: "pyarrow.Table"): + """Custom reducer for Arrow Tables that works around a zero-copy slice pickling bug. + Background: + Arrow has both array-level slicing and buffer-level slicing; both are zero-copy, + but the former has a serialization bug where the entire buffer is serialized + instead of just the slice, while the latter's serialization works as expected + and only serializes the slice of the buffer. I.e., array-level slicing doesn't + propagate the slice down to the buffer when serializing the array. + All that these copy methods do is, at serialization time, take the array-level + slicing and translate them to buffer-level slicing, so only the buffer slice is + sent over the wire instead of the entire buffer. + See https://issues.apache.org/jira/browse/ARROW-10739. + """ + global _serialization_fallback_set + + # Reduce the ChunkedArray columns. + reduced_columns = [] + for column_name in t.column_names: + column = t[column_name] + try: + # Delegate to ChunkedArray reducer. + reduced_column = _arrow_chunked_array_reduce(column) + except Exception as e: + if not _is_dense_union(column.type) and is_in_test(): + # If running in a test and the column is not a dense union array + # (which we expect to need a fallback), we want to raise the error, + # not fall back. + raise e from None + if type(column.type) not in _serialization_fallback_set: + logger.warning( + "Failed to complete optimized serialization of Arrow Table, " + f"serialization of column '{column_name}' of type {column.type} " + "failed, so we're falling back to Arrow IPC serialization for the " + "table. Note that this may result in slower serialization and more " + "worker memory utilization. Serialization error:", + exc_info=True, + ) + _serialization_fallback_set.add(type(column.type)) + # Fall back to Arrow IPC-based workaround for the entire table. + return _arrow_table_ipc_reduce(t) + else: + # Column reducer succeeded, add reduced column to list. + reduced_columns.append(reduced_column) + return _reconstruct_table, (reduced_columns, t.schema) + + +def _reconstruct_table( + reduced_columns: List[Tuple[List["pyarrow.Array"], "pyarrow.DataType"]], + schema: "pyarrow.Schema", +) -> "pyarrow.Table": + """Restore a serialized Arrow Table, reconstructing each reduced column.""" + import pyarrow as pa + + # Reconstruct each reduced column. + columns = [] + for chunks_payload, type_ in reduced_columns: + columns.append(_reconstruct_chunked_array(chunks_payload, type_)) + + return pa.Table.from_arrays(columns, schema=schema) + + +def _arrow_chunked_array_reduce( + ca: "pyarrow.ChunkedArray", +) -> Tuple[List["PicklableArrayPayload"], "pyarrow.DataType"]: + """Custom reducer for Arrow ChunkedArrays that works around a zero-copy slice + pickling bug. This reducer does not return a reconstruction function, since it's + expected to be reconstructed by the Arrow Table reconstructor. + """ + # Convert chunks to serialization payloads. + chunk_payloads = [] + for chunk in ca.chunks: + chunk_payload = PicklableArrayPayload.from_array(chunk) + chunk_payloads.append(chunk_payload) + return chunk_payloads, ca.type + + +def _reconstruct_chunked_array( + chunks: List["PicklableArrayPayload"], type_: "pyarrow.DataType" +) -> "pyarrow.ChunkedArray": + """Restore a serialized Arrow ChunkedArray from chunks and type.""" + import pyarrow as pa + + # Reconstruct chunks from serialization payloads. + chunks = [chunk.to_array() for chunk in chunks] + + return pa.chunked_array(chunks, type_) + + +@dataclass +class PicklableArrayPayload: + """Picklable array payload, holding data buffers and array metadata. + + This is a helper container for pickling and reconstructing nested Arrow Arrays while + ensuring that the buffers that underly zero-copy slice views are properly truncated. + """ + + # Array type. + type: "pyarrow.DataType" + # Length of array. + length: int + # Underlying data buffers. + buffers: List["pyarrow.Buffer"] + # Cached null count. + null_count: int + # Slice offset into base array. + offset: int + # Serialized array payloads for nested (child) arrays. + children: List["PicklableArrayPayload"] + + @classmethod + def from_array(self, a: "pyarrow.Array") -> "PicklableArrayPayload": + """Create a picklable array payload from an Arrow Array. + + This will recursively accumulate data buffer and metadata payloads that are + ready for pickling; namely, the data buffers underlying zero-copy slice views + will be properly truncated. + """ + return _array_to_array_payload(a) + + def to_array(self) -> "pyarrow.Array": + """Reconstruct an Arrow Array from this picklable payload.""" + return _array_payload_to_array(self) + + +def _array_payload_to_array(payload: "PicklableArrayPayload") -> "pyarrow.Array": + """Reconstruct an Arrow Array from a possibly nested PicklableArrayPayload.""" + import pyarrow as pa + + from ray.air.util.tensor_extensions.arrow import get_arrow_extension_tensor_types + + children = [child_payload.to_array() for child_payload in payload.children] + + tensor_extension_types = get_arrow_extension_tensor_types() + + if pa.types.is_dictionary(payload.type): + # Dedicated path for reconstructing a DictionaryArray, since + # Array.from_buffers() doesn't work for DictionaryArrays. + assert len(children) == 2, len(children) + indices, dictionary = children + return pa.DictionaryArray.from_arrays(indices, dictionary) + elif pa.types.is_map(payload.type) and len(children) > 1: + # In pyarrow<7.0.0, the underlying map child array is not exposed, so we work + # with the key and item arrays. + assert len(children) == 3, len(children) + offsets, keys, items = children + return pa.MapArray.from_arrays(offsets, keys, items) + elif isinstance( + payload.type, + tensor_extension_types, + ): + # Dedicated path for reconstructing an ArrowTensorArray or + # ArrowVariableShapedTensorArray, both of which can't be reconstructed by the + # Array.from_buffers() API. + assert len(children) == 1, len(children) + storage = children[0] + return pa.ExtensionArray.from_storage(payload.type, storage) + else: + # Common case: use Array.from_buffers() to construct an array of a certain type. + return pa.Array.from_buffers( + type=payload.type, + length=payload.length, + buffers=payload.buffers, + null_count=payload.null_count, + offset=payload.offset, + children=children, + ) + + +def _array_to_array_payload(a: "pyarrow.Array") -> "PicklableArrayPayload": + """Serialize an Arrow Array to an PicklableArrayPayload for later pickling. + + This function's primary purpose is to dispatch to the handler for the input array + type. + """ + import pyarrow as pa + + from ray.air.util.tensor_extensions.arrow import get_arrow_extension_tensor_types + + tensor_extension_types = get_arrow_extension_tensor_types() + + if _is_dense_union(a.type): + # Dense unions are not supported. + # TODO(Clark): Support dense unions. + raise NotImplementedError( + "Custom slice view serialization of dense union arrays is not yet " + "supported." + ) + + # Dispatch to handler for array type. + if pa.types.is_null(a.type): + return _null_array_to_array_payload(a) + elif _is_primitive(a.type): + return _primitive_array_to_array_payload(a) + elif _is_binary(a.type): + return _binary_array_to_array_payload(a) + elif pa.types.is_list(a.type) or pa.types.is_large_list(a.type): + return _list_array_to_array_payload(a) + elif pa.types.is_fixed_size_list(a.type): + return _fixed_size_list_array_to_array_payload(a) + elif pa.types.is_struct(a.type): + return _struct_array_to_array_payload(a) + elif pa.types.is_union(a.type): + return _union_array_to_array_payload(a) + elif pa.types.is_dictionary(a.type): + return _dictionary_array_to_array_payload(a) + elif pa.types.is_map(a.type): + return _map_array_to_array_payload(a) + elif isinstance(a.type, tensor_extension_types): + return _tensor_array_to_array_payload(a) + elif isinstance(a.type, pa.ExtensionType): + return _extension_array_to_array_payload(a) + else: + raise ValueError("Unhandled Arrow array type:", a.type) + + +def _is_primitive(type_: "pyarrow.DataType") -> bool: + """Whether the provided Array type is primitive (boolean, numeric, temporal or + fixed-size binary).""" + import pyarrow as pa + + return ( + pa.types.is_integer(type_) + or pa.types.is_floating(type_) + or pa.types.is_decimal(type_) + or pa.types.is_boolean(type_) + or pa.types.is_temporal(type_) + or pa.types.is_fixed_size_binary(type_) + ) + + +def _is_binary(type_: "pyarrow.DataType") -> bool: + """Whether the provided Array type is a variable-sized binary type.""" + import pyarrow as pa + + return ( + pa.types.is_string(type_) + or pa.types.is_large_string(type_) + or pa.types.is_binary(type_) + or pa.types.is_large_binary(type_) + ) + + +def _null_array_to_array_payload(a: "pyarrow.NullArray") -> "PicklableArrayPayload": + """Serialize null array to PicklableArrayPayload.""" + # Buffer scheme: [None] + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[None], # Single null buffer is expected. + null_count=a.null_count, + offset=0, + children=[], + ) + + +def _primitive_array_to_array_payload(a: "pyarrow.Array") -> "PicklableArrayPayload": + """Serialize primitive (numeric, temporal, boolean) arrays to + PicklableArrayPayload. + """ + assert _is_primitive(a.type), a.type + # Buffer scheme: [bitmap, data] + buffers = a.buffers() + assert len(buffers) == 2, len(buffers) + + # Copy bitmap buffer, if needed. + bitmap_buf = buffers[0] + if a.null_count > 0: + bitmap_buf = _copy_bitpacked_buffer_if_needed(bitmap_buf, a.offset, len(a)) + else: + bitmap_buf = None + + # Copy data buffer, if needed. + data_buf = buffers[1] + if data_buf is not None: + data_buf = _copy_buffer_if_needed(buffers[1], a.type, a.offset, len(a)) + + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[bitmap_buf, data_buf], + null_count=a.null_count, + offset=0, + children=[], + ) + + +def _binary_array_to_array_payload(a: "pyarrow.Array") -> "PicklableArrayPayload": + """Serialize binary (variable-sized binary, string) arrays to + PicklableArrayPayload. + """ + assert _is_binary(a.type), a.type + # Buffer scheme: [bitmap, value_offsets, data] + buffers = a.buffers() + assert len(buffers) == 3, len(buffers) + + # Copy bitmap buffer, if needed. + if a.null_count > 0: + bitmap_buf = _copy_bitpacked_buffer_if_needed(buffers[0], a.offset, len(a)) + else: + bitmap_buf = None + + # Copy offset buffer, if needed. + offset_buf = buffers[1] + offset_buf, data_offset, data_length = _copy_offsets_buffer_if_needed( + offset_buf, a.type, a.offset, len(a) + ) + data_buf = buffers[2] + data_buf = _copy_buffer_if_needed(data_buf, None, data_offset, data_length) + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[bitmap_buf, offset_buf, data_buf], + null_count=a.null_count, + offset=0, + children=[], + ) + + +def _list_array_to_array_payload(a: "pyarrow.Array") -> "PicklableArrayPayload": + """Serialize list (regular and large) arrays to PicklableArrayPayload.""" + # Dedicated path for ListArrays. These arrays have a nested set of bitmap and + # offset buffers, eventually bottoming out on a data buffer. + # Buffer scheme: + # [bitmap, offsets, bitmap, offsets, ..., bitmap, data] + buffers = a.buffers() + assert len(buffers) > 1, len(buffers) + + # Copy bitmap buffer, if needed. + if a.null_count > 0: + bitmap_buf = _copy_bitpacked_buffer_if_needed(buffers[0], a.offset, len(a)) + else: + bitmap_buf = None + + # Copy offset buffer, if needed. + offset_buf = buffers[1] + offset_buf, child_offset, child_length = _copy_offsets_buffer_if_needed( + offset_buf, a.type, a.offset, len(a) + ) + + # Propagate slice to child. + child = a.values.slice(child_offset, child_length) + + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[bitmap_buf, offset_buf], + null_count=a.null_count, + offset=0, + children=[_array_to_array_payload(child)], + ) + + +def _fixed_size_list_array_to_array_payload( + a: "pyarrow.FixedSizeListArray", +) -> "PicklableArrayPayload": + """Serialize fixed size list arrays to PicklableArrayPayload.""" + # Dedicated path for fixed-size lists. + # Buffer scheme: + # [bitmap, values_bitmap, values_data, values_subbuffers...] + buffers = a.buffers() + assert len(buffers) >= 1, len(buffers) + + # Copy bitmap buffer, if needed. + if a.null_count > 0: + bitmap_buf = _copy_bitpacked_buffer_if_needed(buffers[0], a.offset, len(a)) + else: + bitmap_buf = None + + # Propagate slice to child. + child_offset = a.type.list_size * a.offset + child_length = a.type.list_size * len(a) + child = a.values.slice(child_offset, child_length) + + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[bitmap_buf], + null_count=a.null_count, + offset=0, + children=[_array_to_array_payload(child)], + ) + + +def _struct_array_to_array_payload(a: "pyarrow.StructArray") -> "PicklableArrayPayload": + """Serialize struct arrays to PicklableArrayPayload.""" + # Dedicated path for StructArrays. + # StructArrays have a top-level bitmap buffer and one or more children arrays. + # Buffer scheme: [bitmap, None, child_bitmap, child_data, ...] + buffers = a.buffers() + assert len(buffers) >= 1, len(buffers) + + # Copy bitmap buffer, if needed. + if a.null_count > 0: + bitmap_buf = _copy_bitpacked_buffer_if_needed(buffers[0], a.offset, len(a)) + else: + bitmap_buf = None + + # Get field children payload. + # Offsets and truncations are already propagated to the field arrays, so we can + # serialize them as-is. + children = [_array_to_array_payload(a.field(i)) for i in range(a.type.num_fields)] + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[bitmap_buf], + null_count=a.null_count, + offset=0, + children=children, + ) + + +def _union_array_to_array_payload(a: "pyarrow.UnionArray") -> "PicklableArrayPayload": + """Serialize union arrays to PicklableArrayPayload.""" + import pyarrow as pa + + # Dedicated path for UnionArrays. + # UnionArrays have a top-level bitmap buffer and type code buffer, and one or + # more children arrays. + # Buffer scheme: [None, typecodes, child_bitmap, child_data, ...] + assert not _is_dense_union(a.type) + buffers = a.buffers() + assert len(buffers) > 1, len(buffers) + + bitmap_buf = buffers[0] + assert bitmap_buf is None, bitmap_buf + + # Copy type code buffer, if needed. + type_code_buf = buffers[1] + type_code_buf = _copy_buffer_if_needed(type_code_buf, pa.int8(), a.offset, len(a)) + + # Get field children payload. + # Offsets and truncations are already propagated to the field arrays, so we can + # serialize them as-is. + children = [_array_to_array_payload(a.field(i)) for i in range(a.type.num_fields)] + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[bitmap_buf, type_code_buf], + null_count=a.null_count, + offset=0, + children=children, + ) + + +def _dictionary_array_to_array_payload( + a: "pyarrow.DictionaryArray", +) -> "PicklableArrayPayload": + """Serialize dictionary arrays to PicklableArrayPayload.""" + # Dedicated path for DictionaryArrays. + # Buffer scheme: [indices_bitmap, indices_data] (dictionary stored separately) + indices_payload = _array_to_array_payload(a.indices) + dictionary_payload = _array_to_array_payload(a.dictionary) + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[], + null_count=a.null_count, + offset=0, + children=[indices_payload, dictionary_payload], + ) + + +def _map_array_to_array_payload(a: "pyarrow.MapArray") -> "PicklableArrayPayload": + """Serialize map arrays to PicklableArrayPayload.""" + import pyarrow as pa + + # Dedicated path for MapArrays. + # Buffer scheme: [bitmap, offsets, child_struct_array_buffers, ...] + buffers = a.buffers() + assert len(buffers) > 0, len(buffers) + + # Copy bitmap buffer, if needed. + if a.null_count > 0: + bitmap_buf = _copy_bitpacked_buffer_if_needed(buffers[0], a.offset, len(a)) + else: + bitmap_buf = None + + new_buffers = [bitmap_buf] + + # Copy offsets buffer, if needed. + offset_buf = buffers[1] + offset_buf, data_offset, data_length = _copy_offsets_buffer_if_needed( + offset_buf, a.type, a.offset, len(a) + ) + + if isinstance(a, pa.lib.ListArray): + # Map arrays directly expose the one child struct array in pyarrow>=7.0.0, which + # is easier to work with than the raw buffers. + new_buffers.append(offset_buf) + children = [_array_to_array_payload(a.values.slice(data_offset, data_length))] + else: + # In pyarrow<7.0.0, the child struct array is not exposed, so we work with the + # key and item arrays. + buffers = a.buffers() + assert len(buffers) > 2, len(buffers) + # Reconstruct offsets array. + offsets = pa.Array.from_buffers( + pa.int32(), len(a) + 1, [bitmap_buf, offset_buf] + ) + # Propagate slice to keys. + keys = a.keys.slice(data_offset, data_length) + # Propagate slice to items. + items = a.items.slice(data_offset, data_length) + children = [ + _array_to_array_payload(offsets), + _array_to_array_payload(keys), + _array_to_array_payload(items), + ] + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=new_buffers, + null_count=a.null_count, + offset=0, + children=children, + ) + + +def _tensor_array_to_array_payload(a: "ArrowTensorArray") -> "PicklableArrayPayload": + """Serialize tensor arrays to PicklableArrayPayload.""" + # Offset is propagated to storage array, and the storage array items align with the + # tensor elements, so we only need to do the straightforward creation of the storage + # array payload. + storage_payload = _array_to_array_payload(a.storage) + return PicklableArrayPayload( + type=a.type, + length=len(a), + buffers=[], + null_count=a.null_count, + offset=0, + children=[storage_payload], + ) + + +def _extension_array_to_array_payload( + a: "pyarrow.ExtensionArray", +) -> "PicklableArrayPayload": + payload = _array_to_array_payload(a.storage) + payload.type = a.type + payload.length = len(a) + payload.null_count = a.null_count + return payload + + +def _copy_buffer_if_needed( + buf: "pyarrow.Buffer", + type_: Optional["pyarrow.DataType"], + offset: int, + length: int, +) -> "pyarrow.Buffer": + """Copy buffer, if needed.""" + import pyarrow as pa + + if type_ is not None and pa.types.is_boolean(type_): + # Arrow boolean array buffers are bit-packed, with 8 entries per byte, + # and are accessed via bit offsets. + buf = _copy_bitpacked_buffer_if_needed(buf, offset, length) + else: + type_bytewidth = type_.bit_width // 8 if type_ is not None else 1 + buf = _copy_normal_buffer_if_needed(buf, type_bytewidth, offset, length) + return buf + + +def _copy_normal_buffer_if_needed( + buf: "pyarrow.Buffer", + byte_width: int, + offset: int, + length: int, +) -> "pyarrow.Buffer": + """Copy buffer, if needed.""" + byte_offset = offset * byte_width + byte_length = length * byte_width + if offset > 0 or byte_length < buf.size: + # Array is a zero-copy slice, so we need to copy to a new buffer before + # serializing; this slice of the underlying buffer (not the array) will ensure + # that the buffer is properly copied at pickle-time. + buf = buf.slice(byte_offset, byte_length) + return buf + + +def _copy_bitpacked_buffer_if_needed( + buf: "pyarrow.Buffer", + offset: int, + length: int, +) -> "pyarrow.Buffer": + """Copy bit-packed binary buffer, if needed.""" + bit_offset = offset % 8 + byte_offset = offset // 8 + byte_length = _bytes_for_bits(bit_offset + length) // 8 + if offset > 0 or byte_length < buf.size: + buf = buf.slice(byte_offset, byte_length) + if bit_offset != 0: + # Need to manually shift the buffer to eliminate the bit offset. + buf = _align_bit_offset(buf, bit_offset, byte_length) + return buf + + +def _copy_offsets_buffer_if_needed( + buf: "pyarrow.Buffer", + arr_type: "pyarrow.DataType", + offset: int, + length: int, +) -> Tuple["pyarrow.Buffer", int, int]: + """Copy the provided offsets buffer, returning the copied buffer and the + offset + length of the underlying data. + """ + import pyarrow as pa + import pyarrow.compute as pac + + if ( + pa.types.is_large_list(arr_type) + or pa.types.is_large_string(arr_type) + or pa.types.is_large_binary(arr_type) + or pa.types.is_large_unicode(arr_type) + ): + offset_type = pa.int64() + else: + offset_type = pa.int32() + # Copy offset buffer, if needed. + buf = _copy_buffer_if_needed(buf, offset_type, offset, length + 1) + # Reconstruct the offset array so we can determine the offset and length + # of the child array. + offsets = pa.Array.from_buffers(offset_type, length + 1, [None, buf]) + child_offset = offsets[0].as_py() + child_length = offsets[-1].as_py() - child_offset + # Create new offsets aligned to 0 for the copied data buffer slice. + offsets = pac.subtract(offsets, child_offset) + if pa.types.is_int32(offset_type): + # We need to cast the resulting Int64Array back down to an Int32Array. + offsets = offsets.cast(offset_type, safe=False) + buf = offsets.buffers()[1] + return buf, child_offset, child_length + + +def _bytes_for_bits(n: int) -> int: + """Round up n to the nearest multiple of 8. + This is used to get the byte-padded number of bits for n bits. + """ + return (n + 7) & (-8) + + +def _align_bit_offset( + buf: "pyarrow.Buffer", + bit_offset: int, + byte_length: int, +) -> "pyarrow.Buffer": + """Align the bit offset into the buffer with the front of the buffer by shifting + the buffer and eliminating the offset. + """ + import pyarrow as pa + + bytes_ = buf.to_pybytes() + bytes_as_int = int.from_bytes(bytes_, sys.byteorder) + bytes_as_int >>= bit_offset + bytes_ = bytes_as_int.to_bytes(byte_length, sys.byteorder) + return pa.py_buffer(bytes_) + + +def _arrow_table_ipc_reduce(table: "pyarrow.Table"): + """Custom reducer for Arrow Table that works around a zero-copy slicing pickling + bug by using the Arrow IPC format for the underlying serialization. + + This is currently used as a fallback for unsupported types (or unknown bugs) for + the manual buffer truncation workaround, e.g. for dense unions. + """ + from pyarrow.ipc import RecordBatchStreamWriter + from pyarrow.lib import BufferOutputStream + + output_stream = BufferOutputStream() + with RecordBatchStreamWriter(output_stream, schema=table.schema) as wr: + wr.write_table(table) + # NOTE: output_stream.getvalue() materializes the serialized table to a single + # contiguous bytestring, resulting in a few copy. This adds 1-2 extra copies on the + # serialization side, and 1 extra copy on the deserialization side. + return _restore_table_from_ipc, (output_stream.getvalue(),) + + +def _restore_table_from_ipc(buf: bytes) -> "pyarrow.Table": + """Restore an Arrow Table serialized to Arrow IPC format.""" + from pyarrow.ipc import RecordBatchStreamReader + + with RecordBatchStreamReader(buf) as reader: + return reader.read_all() + + +def _is_dense_union(type_: "pyarrow.DataType") -> bool: + """Whether the provided Arrow type is a dense union.""" + import pyarrow as pa + + return pa.types.is_union(type_) and type_.mode == "dense" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/arrow_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/arrow_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..e46b6fcf26fb868cb7962e814710db1170a8b728 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/arrow_utils.py @@ -0,0 +1,91 @@ +import json +from typing import Dict, Optional +from urllib.parse import parse_qsl, unquote, urlencode, urlparse, urlunparse + +from packaging.version import Version, parse as parse_version + +_PYARROW_INSTALLED: Optional[bool] = None +_PYARROW_VERSION: Optional[Version] = None + + +def get_pyarrow_version() -> Optional[Version]: + """Get the version of the pyarrow package or None if not installed.""" + global _PYARROW_INSTALLED, _PYARROW_VERSION + if _PYARROW_INSTALLED is False: + return None + + if _PYARROW_INSTALLED is None: + try: + import pyarrow + + _PYARROW_INSTALLED = True + if hasattr(pyarrow, "__version__"): + _PYARROW_VERSION = parse_version(pyarrow.__version__) + except ModuleNotFoundError: + _PYARROW_INSTALLED = False + + return _PYARROW_VERSION + + +def _add_url_query_params(url: str, params: Dict[str, str]) -> str: + """Add params to the provided url as query parameters. + + If url already contains query parameters, they will be merged with params, with the + existing query parameters overriding any in params with the same parameter name. + + Args: + url: The URL to add query parameters to. + params: The query parameters to add. + + Returns: + URL with params added as query parameters. + """ + # Unquote URL first so we don't lose existing args. + url = unquote(url) + # Parse URL. + parsed_url = urlparse(url) + # Merge URL query string arguments dict with new params. + base_params = params + params = dict(parse_qsl(parsed_url.query)) + base_params.update(params) + # bool and dict values should be converted to json-friendly values. + base_params.update( + { + k: json.dumps(v) + for k, v in base_params.items() + if isinstance(v, (bool, dict)) + } + ) + + # Convert URL arguments to proper query string. + encoded_params = urlencode(base_params, doseq=True) + # Replace query string in parsed URL with updated query string. + parsed_url = parsed_url._replace(query=encoded_params) + # Convert back to URL. + return urlunparse(parsed_url) + + +def add_creatable_buckets_param_if_s3_uri(uri: str) -> str: + """If the provided URI is an S3 URL, add allow_bucket_creation=true as a query + parameter. For pyarrow >= 9.0.0, this is required in order to allow + ``S3FileSystem.create_dir()`` to create S3 buckets. + + If the provided URI is not an S3 URL or if pyarrow < 9.0.0 is installed, we return + the URI unchanged. + + Args: + uri: The URI that we'll add the query parameter to, if it's an S3 URL. + + Returns: + A URI with the added allow_bucket_creation=true query parameter, if the provided + URI is an S3 URL; uri will be returned unchanged otherwise. + """ + + pyarrow_version = get_pyarrow_version() + if pyarrow_version is not None and pyarrow_version < parse_version("9.0.0"): + # This bucket creation query parameter is not required for pyarrow < 9.0.0. + return uri + parsed_uri = urlparse(uri) + if parsed_uri.scheme == "s3": + uri = _add_url_query_params(uri, {"allow_bucket_creation": True}) + return uri diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/async_compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/async_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..a9081c2719b34795015394239405af3acbf45ac8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/async_compat.py @@ -0,0 +1,52 @@ +""" +This file should only be imported from Python 3. +It will raise SyntaxError when importing from Python 2. +""" +import asyncio +import inspect +from functools import lru_cache + +try: + import uvloop +except ImportError: + uvloop = None + + +def get_new_event_loop(): + """Construct a new event loop. Ray will use uvloop if it exists""" + if uvloop: + return uvloop.new_event_loop() + else: + return asyncio.new_event_loop() + + +def try_install_uvloop(): + """Installs uvloop as event-loop implementation for asyncio (if available)""" + if uvloop: + uvloop.install() + else: + pass + + +def is_async_func(func) -> bool: + """Return True if the function is an async or async generator method.""" + return inspect.iscoroutinefunction(func) or inspect.isasyncgenfunction(func) + + +@lru_cache(maxsize=2**10) +def has_async_methods(cls: object) -> bool: + """Return True if the class has any async methods.""" + return len(inspect.getmembers(cls, predicate=is_async_func)) > 0 + + +@lru_cache(maxsize=2**10) +def sync_to_async(func): + """Wrap a blocking function in an async function""" + + if is_async_func(func): + return func + + async def wrapper(*args, **kwargs): + return func(*args, **kwargs) + + return wrapper diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/async_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/async_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0c2da0a1ec3054effd2596086bc71296874afa49 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/async_utils.py @@ -0,0 +1,52 @@ +# Adapted from [aiodebug](https://gitlab.com/quantlane/libs/aiodebug) + +# Copyright 2016-2022 Quantlane s.r.o. + +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at + +# http://www.apache.org/licenses/LICENSE-2.0 + +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Modifications: +# - Removed the dependency to `logwood`. +# - Renamed `monitor_loop_lag.enable()` to just `enable_monitor_loop_lag()`. +# - Miscellaneous changes to make it work with Ray. + +import asyncio +import asyncio.events +from typing import Callable, Optional + + +def enable_monitor_loop_lag( + callback: Callable[[float], None], + interval_s: float = 0.25, + loop: Optional[asyncio.AbstractEventLoop] = None, +) -> None: + """ + Start logging event loop lags to the callback. In ideal circumstances they should be + very close to zero. Lags may increase if event loop callbacks block for too long. + + Note: this works for all event loops, including uvloop. + + :param callback: Callback to call with the lag in seconds. + """ + if loop is None: + loop = asyncio.get_running_loop() + if loop is None: + raise ValueError("No provided loop, nor running loop found.") + + async def monitor(): + while loop.is_running(): + t0 = loop.time() + await asyncio.sleep(interval_s) + lag = loop.time() - t0 - interval_s # Should be close to zero. + callback(lag) + + loop.create_task(monitor(), name="async_utils.monitor_loop_lag") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/auto_init_hook.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/auto_init_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..2013051a3294936a6e15526c8d9efa0ffe25ae12 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/auto_init_hook.py @@ -0,0 +1,32 @@ +import os +import threading +from functools import wraps + +import ray + +auto_init_lock = threading.Lock() +enable_auto_connect = os.environ.get("RAY_ENABLE_AUTO_CONNECT", "") != "0" + + +def auto_init_ray(): + if enable_auto_connect and not ray.is_initialized(): + with auto_init_lock: + if not ray.is_initialized(): + ray.init() + + +def wrap_auto_init(fn): + @wraps(fn) + def auto_init_wrapper(*args, **kwargs): + auto_init_ray() + return fn(*args, **kwargs) + + return auto_init_wrapper + + +def wrap_auto_init_for_all_apis(api_names): + """Wrap public APIs with automatic ray.init.""" + for api_name in api_names: + api = getattr(ray, api_name, None) + assert api is not None, api_name + setattr(ray, api_name, wrap_auto_init(api)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/client_mode_hook.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/client_mode_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..acd30fbca1cfa424dcae2b94d7e57b719e57ca70 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/client_mode_hook.py @@ -0,0 +1,185 @@ +import os +import threading +from contextlib import contextmanager +from functools import wraps + +from ray._private.auto_init_hook import auto_init_ray + +# Attr set on func defs to mark they have been converted to client mode. +RAY_CLIENT_MODE_ATTR = "__ray_client_mode_key__" + +# Global setting of whether client mode is enabled. This default to OFF, +# but is enabled upon ray.client(...).connect() or in tests. +is_client_mode_enabled = os.environ.get("RAY_CLIENT_MODE", "0") == "1" + +# When RAY_CLIENT_MODE == 1, we treat it as default enabled client mode +# This is useful for testing +is_client_mode_enabled_by_default = is_client_mode_enabled +os.environ.update({"RAY_CLIENT_MODE": "0"}) + +is_init_called = False + +# Local setting of whether to ignore client hook conversion. This defaults +# to TRUE and is disabled when the underlying 'real' Ray function is needed. +_client_hook_status_on_thread = threading.local() +_client_hook_status_on_thread.status = True + + +def _get_client_hook_status_on_thread(): + """Get's the value of `_client_hook_status_on_thread`. + Since `_client_hook_status_on_thread` is a thread-local variable, we may + need to add and set the 'status' attribute. + """ + global _client_hook_status_on_thread + if not hasattr(_client_hook_status_on_thread, "status"): + _client_hook_status_on_thread.status = True + return _client_hook_status_on_thread.status + + +def _set_client_hook_status(val: bool): + global _client_hook_status_on_thread + _client_hook_status_on_thread.status = val + + +def _disable_client_hook(): + global _client_hook_status_on_thread + out = _get_client_hook_status_on_thread() + _client_hook_status_on_thread.status = False + return out + + +def _explicitly_enable_client_mode(): + """Force client mode to be enabled. + NOTE: This should not be used in tests, use `enable_client_mode`. + """ + global is_client_mode_enabled + is_client_mode_enabled = True + + +def _explicitly_disable_client_mode(): + global is_client_mode_enabled + is_client_mode_enabled = False + + +@contextmanager +def disable_client_hook(): + val = _disable_client_hook() + try: + yield None + finally: + _set_client_hook_status(val) + + +@contextmanager +def enable_client_mode(): + _explicitly_enable_client_mode() + try: + yield None + finally: + _explicitly_disable_client_mode() + + +def client_mode_hook(func: callable): + """Decorator for whether to use the 'regular' ray version of a function, + or the Ray Client version of that function. + + Args: + func: This function. This is set when this function is used + as a decorator. + """ + + from ray.util.client import ray + + @wraps(func) + def wrapper(*args, **kwargs): + # NOTE(hchen): DO NOT use "import" inside this function. + # Because when it's called within a `__del__` method, this error + # will be raised (see #35114): + # ImportError: sys.meta_path is None, Python is likely shutting down. + if client_mode_should_convert(): + # Legacy code + # we only convert init function if RAY_CLIENT_MODE=1 + if func.__name__ != "init" or is_client_mode_enabled_by_default: + return getattr(ray, func.__name__)(*args, **kwargs) + return func(*args, **kwargs) + + return wrapper + + +def client_mode_should_convert(): + """Determines if functions should be converted to client mode.""" + + # `is_client_mode_enabled_by_default` is used for testing with + # `RAY_CLIENT_MODE=1`. This flag means all tests run with client mode. + return ( + is_client_mode_enabled or is_client_mode_enabled_by_default + ) and _get_client_hook_status_on_thread() + + +def client_mode_wrap(func): + """Wraps a function called during client mode for execution as a remote + task. + + Can be used to implement public features of ray client which do not + belong in the main ray API (`ray.*`), yet require server-side execution. + An example is the creation of placement groups: + `ray.util.placement_group.placement_group()`. When called on the client + side, this function is wrapped in a task to facilitate interaction with + the GCS. + """ + + @wraps(func) + def wrapper(*args, **kwargs): + from ray.util.client import ray + + auto_init_ray() + # Directly pass this through since `client_mode_wrap` is for + # Placement Group APIs + if client_mode_should_convert(): + f = ray.remote(num_cpus=0)(func) + ref = f.remote(*args, **kwargs) + return ray.get(ref) + return func(*args, **kwargs) + + return wrapper + + +def client_mode_convert_function(func_cls, in_args, in_kwargs, **kwargs): + """Runs a preregistered ray RemoteFunction through the ray client. + + The common case for this is to transparently convert that RemoteFunction + to a ClientRemoteFunction. This happens in circumstances where the + RemoteFunction is declared early, in a library and only then is Ray used in + client mode -- necessitating a conversion. + """ + from ray.util.client import ray + + key = getattr(func_cls, RAY_CLIENT_MODE_ATTR, None) + + # Second part of "or" is needed in case func_cls is reused between Ray + # client sessions in one Python interpreter session. + if (key is None) or (not ray._converted_key_exists(key)): + key = ray._convert_function(func_cls) + setattr(func_cls, RAY_CLIENT_MODE_ATTR, key) + client_func = ray._get_converted(key) + return client_func._remote(in_args, in_kwargs, **kwargs) + + +def client_mode_convert_actor(actor_cls, in_args, in_kwargs, **kwargs): + """Runs a preregistered actor class on the ray client + + The common case for this decorator is for instantiating an ActorClass + transparently as a ClientActorClass. This happens in circumstances where + the ActorClass is declared early, in a library and only then is Ray used in + client mode -- necessitating a conversion. + """ + from ray.util.client import ray + + key = getattr(actor_cls, RAY_CLIENT_MODE_ATTR, None) + # Second part of "or" is needed in case actor_cls is reused between Ray + # client sessions in one Python interpreter session. + if (key is None) or (not ray._converted_key_exists(key)): + key = ray._convert_actor(actor_cls) + setattr(actor_cls, RAY_CLIENT_MODE_ATTR, key) + client_actor = ray._get_converted(key) + return client_actor._remote(in_args, in_kwargs, **kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/collections_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/collections_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f7512cfb4b987d022e6bea4218f9097ff27ae69a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/collections_utils.py @@ -0,0 +1,10 @@ +from typing import Any, List + + +def split(items: List[Any], chunk_size: int): + """Splits provided list into chunks of given size""" + + assert chunk_size > 0, "Chunk size has to be > 0" + + for i in range(0, len(items), chunk_size): + yield items[i : i + chunk_size] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..f0a3896cce09fc662f2337ad5293dab76421d588 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/compat.py @@ -0,0 +1,40 @@ +import io +import platform + + +def patch_psutil(): + """WSL's /proc/meminfo has an inconsistency where it + nondeterministically omits a space after colons (after "SwapFree:" + in my case). + psutil then splits on spaces and then parses the wrong field, + crashing on the 'int(fields[1])' expression in + psutil._pslinux.virtual_memory(). + Workaround: We ensure there is a space following each colon. + """ + assert ( + platform.system() == "Linux" + and "Microsoft".lower() in platform.release().lower() + ) + + try: + import psutil._pslinux + except ImportError: + psutil = None + psutil_open_binary = None + if psutil: + try: + psutil_open_binary = psutil._pslinux.open_binary + except AttributeError: + pass + # Only patch it if it doesn't seem to have been patched already + if psutil_open_binary and psutil_open_binary.__name__ == "open_binary": + + def psutil_open_binary_patched(fname, *args, **kwargs): + f = psutil_open_binary(fname, *args, **kwargs) + if fname == "/proc/meminfo": + with f: + # Make sure there's a space after colons + return io.BytesIO(f.read().replace(b":", b": ")) + return f + + psutil._pslinux.open_binary = psutil_open_binary_patched diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/conftest_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/conftest_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2dc02a2d62cffd433dcf35c969c85de295be45bf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/conftest_utils.py @@ -0,0 +1,15 @@ +import pytest + +import ray._private.ray_constants as ray_constants + + +@pytest.fixture +def set_override_dashboard_url(monkeypatch, request): + override_url = getattr(request, "param", "https://external_dashboard_url") + with monkeypatch.context() as m: + if override_url: + m.setenv( + ray_constants.RAY_OVERRIDE_DASHBOARD_URL, + override_url, + ) + yield diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/custom_types.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/custom_types.py new file mode 100644 index 0000000000000000000000000000000000000000..2237972c3b6b929ee45f944cd75fa844951db781 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/custom_types.py @@ -0,0 +1,165 @@ +from enum import Enum +from typing import Literal + +from ray.core.generated.common_pb2 import ( + ErrorType, + Language, + TaskStatus, + TaskType, + TensorTransport, + WorkerExitType, + WorkerType, +) +from ray.core.generated.gcs_pb2 import ( + ActorTableData, + GcsNodeInfo, + PlacementGroupTableData, +) + +ACTOR_STATUS = [ + "DEPENDENCIES_UNREADY", + "PENDING_CREATION", + "ALIVE", + "RESTARTING", + "DEAD", +] +TypeActorStatus = Literal[tuple(ACTOR_STATUS)] +PLACEMENT_GROUP_STATUS = [ + "PENDING", + "PREPARED", + "CREATED", + "REMOVED", + "RESCHEDULING", +] +TypePlacementGroupStatus = Literal[tuple(PLACEMENT_GROUP_STATUS)] +TASK_STATUS = [ + "NIL", + "PENDING_ARGS_AVAIL", + "PENDING_NODE_ASSIGNMENT", + "PENDING_OBJ_STORE_MEM_AVAIL", + "PENDING_ARGS_FETCH", + "SUBMITTED_TO_WORKER", + "PENDING_ACTOR_TASK_ARGS_FETCH", + "PENDING_ACTOR_TASK_ORDERING_OR_CONCURRENCY", + "RUNNING", + "RUNNING_IN_RAY_GET", + "RUNNING_IN_RAY_WAIT", + "FINISHED", + "FAILED", +] +TypeTaskStatus = Literal[tuple(TASK_STATUS)] +NODE_STATUS = ["ALIVE", "DEAD"] +TypeNodeStatus = Literal[tuple(NODE_STATUS)] +WORKER_TYPE = [ + "WORKER", + "DRIVER", + "SPILL_WORKER", + "RESTORE_WORKER", +] +TypeWorkerType = Literal[tuple(WORKER_TYPE)] +WORKER_EXIT_TYPE = [ + "SYSTEM_ERROR", + "INTENDED_SYSTEM_EXIT", + "USER_ERROR", + "INTENDED_USER_EXIT", + "NODE_OUT_OF_MEMORY", +] +TypeWorkerExitType = Literal[tuple(WORKER_EXIT_TYPE)] +TASK_TYPE = [ + "NORMAL_TASK", + "ACTOR_CREATION_TASK", + "ACTOR_TASK", + "DRIVER_TASK", +] +TypeTaskType = Literal[tuple(TASK_TYPE)] +# TODO(kevin85421): `class ReferenceType(Enum)` is defined in +# `dashboard/memory_utils.py` to avoid complex dependencies. I redefined +# it here. Eventually, we should remove the one in `dashboard/memory_utils.py` +# and define it under `ray/_private`. +REFERENCE_TYPE = [ + "ACTOR_HANDLE", + "PINNED_IN_MEMORY", + "LOCAL_REFERENCE", + "USED_BY_PENDING_TASK", + "CAPTURED_IN_OBJECT", + "UNKNOWN_STATUS", +] +TypeReferenceType = Literal[tuple(REFERENCE_TYPE)] +# The ErrorType enum is used in the export API so it is public +# and any modifications must be backward compatible. +ERROR_TYPE = [ + "WORKER_DIED", + "ACTOR_DIED", + "OBJECT_UNRECONSTRUCTABLE", + "TASK_EXECUTION_EXCEPTION", + "OBJECT_IN_PLASMA", + "TASK_CANCELLED", + "ACTOR_CREATION_FAILED", + "RUNTIME_ENV_SETUP_FAILED", + "OBJECT_LOST", + "OWNER_DIED", + "OBJECT_DELETED", + "DEPENDENCY_RESOLUTION_FAILED", + "OBJECT_UNRECONSTRUCTABLE_MAX_ATTEMPTS_EXCEEDED", + "OBJECT_UNRECONSTRUCTABLE_LINEAGE_EVICTED", + "OBJECT_FETCH_TIMED_OUT", + "LOCAL_RAYLET_DIED", + "TASK_PLACEMENT_GROUP_REMOVED", + "ACTOR_PLACEMENT_GROUP_REMOVED", + "TASK_UNSCHEDULABLE_ERROR", + "ACTOR_UNSCHEDULABLE_ERROR", + "OUT_OF_DISK_ERROR", + "OBJECT_FREED", + "OUT_OF_MEMORY", + "NODE_DIED", + "END_OF_STREAMING_GENERATOR", + "ACTOR_UNAVAILABLE", + "GENERATOR_TASK_FAILED_FOR_OBJECT_RECONSTRUCTION", +] +# The Language enum is used in the export API so it is public +# and any modifications must be backward compatible. +LANGUAGE = ["PYTHON", "JAVA", "CPP"] + +# See `common.proto` for more details. +class TensorTransportEnum(Enum): + OBJECT_STORE = TensorTransport.Value("OBJECT_STORE") + NCCL = TensorTransport.Value("NCCL") + GLOO = TensorTransport.Value("GLOO") + + @classmethod + def from_str(cls, name: str) -> "TensorTransportEnum": + name = name.upper() + if name not in cls.__members__: + raise ValueError( + f"Invalid tensor transport {name}, must be one of {list(cls.__members__.keys())}." + ) + return cls[name] + + +def validate_protobuf_enum(grpc_enum, custom_enum): + """Validate the literal contains the correct enum values from protobuf""" + enum_vals = set(grpc_enum.DESCRIPTOR.values_by_name.keys()) + # Sometimes, the grpc enum is mocked, and it + # doesn't include any values in that case. + if len(enum_vals) > 0: + assert enum_vals == set( + custom_enum + ), """Literals in `custom_types.py` and `.proto` files are out of sync. \ +Consider building //:install_py_proto with Bazel or updating `custom_types.py`.""" + + +# Do the enum validation here. +# It is necessary to avoid regression. Alternatively, we can auto generate this +# directly by protobuf. +validate_protobuf_enum(ActorTableData.ActorState, ACTOR_STATUS) +validate_protobuf_enum( + PlacementGroupTableData.PlacementGroupState, PLACEMENT_GROUP_STATUS +) +validate_protobuf_enum(TaskStatus, TASK_STATUS) +validate_protobuf_enum(GcsNodeInfo.GcsNodeState, NODE_STATUS) +validate_protobuf_enum(WorkerType, WORKER_TYPE) +validate_protobuf_enum(WorkerExitType, WORKER_EXIT_TYPE) +validate_protobuf_enum(TaskType, TASK_TYPE) +validate_protobuf_enum(ErrorType, ERROR_TYPE) +validate_protobuf_enum(Language, LANGUAGE) +validate_protobuf_enum(TensorTransport, list(TensorTransportEnum.__members__.keys())) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/dict.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/dict.py new file mode 100644 index 0000000000000000000000000000000000000000..3d102b32961f034f4e7af469898cb2fb66c5ec93 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/dict.py @@ -0,0 +1,247 @@ +import copy +from collections import deque +from collections.abc import Mapping, Sequence +from typing import Dict, List, Optional, TypeVar, Union + +from ray.util.annotations import Deprecated + +T = TypeVar("T") + + +@Deprecated +def merge_dicts(d1: dict, d2: dict) -> dict: + """ + Args: + d1 (dict): Dict 1. + d2 (dict): Dict 2. + + Returns: + dict: A new dict that is d1 and d2 deep merged. + """ + merged = copy.deepcopy(d1) + deep_update(merged, d2, True, []) + return merged + + +@Deprecated +def deep_update( + original: dict, + new_dict: dict, + new_keys_allowed: bool = False, + allow_new_subkey_list: Optional[List[str]] = None, + override_all_if_type_changes: Optional[List[str]] = None, + override_all_key_list: Optional[List[str]] = None, +) -> dict: + """Updates original dict with values from new_dict recursively. + + If new key is introduced in new_dict, then if new_keys_allowed is not + True, an error will be thrown. Further, for sub-dicts, if the key is + in the allow_new_subkey_list, then new subkeys can be introduced. + + Args: + original: Dictionary with default values. + new_dict: Dictionary with values to be updated + new_keys_allowed: Whether new keys are allowed. + allow_new_subkey_list: List of keys that + correspond to dict values where new subkeys can be introduced. + This is only at the top level. + override_all_if_type_changes: List of top level + keys with value=dict, for which we always simply override the + entire value (dict), iff the "type" key in that value dict changes. + override_all_key_list: List of top level keys + for which we override the entire value if the key is in the new_dict. + """ + allow_new_subkey_list = allow_new_subkey_list or [] + override_all_if_type_changes = override_all_if_type_changes or [] + override_all_key_list = override_all_key_list or [] + + for k, value in new_dict.items(): + if k not in original and not new_keys_allowed: + raise Exception("Unknown config parameter `{}` ".format(k)) + + # Both orginal value and new one are dicts. + if ( + isinstance(original.get(k), dict) + and isinstance(value, dict) + and k not in override_all_key_list + ): + # Check old type vs old one. If different, override entire value. + if ( + k in override_all_if_type_changes + and "type" in value + and "type" in original[k] + and value["type"] != original[k]["type"] + ): + original[k] = value + # Allowed key -> ok to add new subkeys. + elif k in allow_new_subkey_list: + deep_update( + original[k], + value, + True, + override_all_key_list=override_all_key_list, + ) + # Non-allowed key. + else: + deep_update( + original[k], + value, + new_keys_allowed, + override_all_key_list=override_all_key_list, + ) + # Original value not a dict OR new value not a dict: + # Override entire value. + else: + original[k] = value + return original + + +@Deprecated +def flatten_dict( + dt: Dict, + delimiter: str = "/", + prevent_delimiter: bool = False, + flatten_list: bool = False, +): + """Flatten dict. + + Output and input are of the same dict type. + Input dict remains the same after the operation. + """ + + def _raise_delimiter_exception(): + raise ValueError( + f"Found delimiter `{delimiter}` in key when trying to flatten " + f"array. Please avoid using the delimiter in your specification." + ) + + dt = copy.copy(dt) + if prevent_delimiter and any(delimiter in key for key in dt): + # Raise if delimiter is any of the keys + _raise_delimiter_exception() + + while_check = (dict, list) if flatten_list else dict + + while any(isinstance(v, while_check) for v in dt.values()): + remove = [] + add = {} + for key, value in dt.items(): + if isinstance(value, dict): + for subkey, v in value.items(): + if prevent_delimiter and delimiter in subkey: + # Raise if delimiter is in any of the subkeys + _raise_delimiter_exception() + + add[delimiter.join([key, str(subkey)])] = v + remove.append(key) + elif flatten_list and isinstance(value, list): + for i, v in enumerate(value): + if prevent_delimiter and delimiter in subkey: + # Raise if delimiter is in any of the subkeys + _raise_delimiter_exception() + + add[delimiter.join([key, str(i)])] = v + remove.append(key) + + dt.update(add) + for k in remove: + del dt[k] + return dt + + +@Deprecated +def unflatten_dict(dt: Dict[str, T], delimiter: str = "/") -> Dict[str, T]: + """Unflatten dict. Does not support unflattening lists.""" + dict_type = type(dt) + out = dict_type() + for key, val in dt.items(): + path = key.split(delimiter) + item = out + for k in path[:-1]: + item = item.setdefault(k, dict_type()) + if not isinstance(item, dict_type): + raise TypeError( + f"Cannot unflatten dict due the key '{key}' " + f"having a parent key '{k}', which value is not " + f"of type {dict_type} (got {type(item)}). " + "Change the key names to resolve the conflict." + ) + item[path[-1]] = val + return out + + +@Deprecated +def unflatten_list_dict(dt: Dict[str, T], delimiter: str = "/") -> Dict[str, T]: + """Unflatten nested dict and list. + + This function now has some limitations: + (1) The keys of dt must be str. + (2) If unflattened dt (the result) contains list, the index order must be + ascending when accessing dt. Otherwise, this function will throw + AssertionError. + (3) The unflattened dt (the result) shouldn't contain dict with number + keys. + + Be careful to use this function. If you want to improve this function, + please also improve the unit test. See #14487 for more details. + + Args: + dt: Flattened dictionary that is originally nested by multiple + list and dict. + delimiter: Delimiter of keys. + + Example: + >>> dt = {"aaa/0/bb": 12, "aaa/1/cc": 56, "aaa/1/dd": 92} + >>> unflatten_list_dict(dt) + {'aaa': [{'bb': 12}, {'cc': 56, 'dd': 92}]} + """ + out_type = list if list(dt)[0].split(delimiter, 1)[0].isdigit() else type(dt) + out = out_type() + for key, val in dt.items(): + path = key.split(delimiter) + + item = out + for i, k in enumerate(path[:-1]): + next_type = list if path[i + 1].isdigit() else dict + if isinstance(item, dict): + item = item.setdefault(k, next_type()) + elif isinstance(item, list): + if int(k) >= len(item): + item.append(next_type()) + assert int(k) == len(item) - 1 + item = item[int(k)] + + if isinstance(item, dict): + item[path[-1]] = val + elif isinstance(item, list): + item.append(val) + assert int(path[-1]) == len(item) - 1 + return out + + +@Deprecated +def unflattened_lookup( + flat_key: str, lookup: Union[Mapping, Sequence], delimiter: str = "/", **kwargs +) -> Union[Mapping, Sequence]: + """ + Unflatten `flat_key` and iteratively look up in `lookup`. E.g. + `flat_key="a/0/b"` will try to return `lookup["a"][0]["b"]`. + """ + if flat_key in lookup: + return lookup[flat_key] + keys = deque(flat_key.split(delimiter)) + base = lookup + while keys: + key = keys.popleft() + try: + if isinstance(base, Mapping): + base = base[key] + elif isinstance(base, Sequence): + base = base[int(key)] + else: + raise KeyError() + except KeyError as e: + if "default" in kwargs: + return kwargs["default"] + raise e + return base diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e72bfd8b6aa188b461f6ede4278a5a44f1f00eb1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/event_logger.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/event_logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54bdfe55503a2f18823c0e9932f273d11a725360 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/event_logger.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/export_event_logger.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/export_event_logger.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9921937e82f00c983effb1748f495c44e6f2a181 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/__pycache__/export_event_logger.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/event_logger.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/event_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e54505bdc79656b151dae60edc387ce728d021 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/event_logger.py @@ -0,0 +1,195 @@ +import json +import logging +import os +import pathlib +import random +import socket +import string +import threading +from datetime import datetime +from typing import Dict, Optional + +from google.protobuf.json_format import Parse + +from ray._private.protobuf_compat import message_to_dict +from ray.core.generated.event_pb2 import Event + +global_logger = logging.getLogger(__name__) + + +def get_event_id(): + return "".join([random.choice(string.hexdigits) for _ in range(36)]) + + +class EventLoggerAdapter: + def __init__(self, source: Event.SourceType, logger: logging.Logger): + """Adapter for the Python logger that's used to emit events. + + When events are emitted, they are aggregated and available via + state API and dashboard. + + This class is thread-safe. + """ + self.logger = logger + # Aligned with `event.proto`'s `message Event`` + self.source = source + self.source_hostname = socket.gethostname() + self.source_pid = os.getpid() + + # The below fields must be protected by this lock. + self.lock = threading.Lock() + # {str -> str} typed dict + self.global_context = {} + + def set_global_context(self, global_context: Dict[str, str] = None): + """Set the global metadata. + + This method overwrites the global metadata if it is called more than once. + """ + with self.lock: + self.global_context = {} if not global_context else global_context + + def trace(self, message: str, **kwargs): + self._emit(Event.Severity.TRACE, message, **kwargs) + + def debug(self, message: str, **kwargs): + self._emit(Event.Severity.DEBUG, message, **kwargs) + + def info(self, message: str, **kwargs): + self._emit(Event.Severity.INFO, message, **kwargs) + + def warning(self, message: str, **kwargs): + self._emit(Event.Severity.WARNING, message, **kwargs) + + def error(self, message: str, **kwargs): + self._emit(Event.Severity.ERROR, message, **kwargs) + + def fatal(self, message: str, **kwargs): + self._emit(Event.Severity.FATAL, message, **kwargs) + + def _emit(self, severity: Event.Severity, message: str, **kwargs): + # NOTE: Python logger is thread-safe, + # so we don't need to protect it using locks. + event = Event() + event.event_id = get_event_id() + event.timestamp = int(datetime.now().timestamp()) + event.message = message + event.severity = severity + # TODO(sang): Support event type & schema. + event.label = "" + event.source_type = self.source + event.source_hostname = self.source_hostname + event.source_pid = self.source_pid + custom_fields = event.custom_fields + with self.lock: + for k, v in self.global_context.items(): + if v is not None and k is not None: + custom_fields[k] = v + for k, v in kwargs.items(): + if v is not None and k is not None: + custom_fields[k] = v + + self.logger.info( + json.dumps( + message_to_dict( + event, + always_print_fields_with_no_presence=True, + preserving_proto_field_name=True, + use_integers_for_enums=False, + ) + ) + ) + + # Force flush so that we won't lose events + self.logger.handlers[0].flush() + + +def _build_event_file_logger(source: Event.SourceType, sink_dir: str): + logger = logging.getLogger("_ray_event_logger") + logger.setLevel(logging.INFO) + dir_path = pathlib.Path(sink_dir) / "events" + filepath = dir_path / f"event_{source}.log" + dir_path.mkdir(exist_ok=True) + filepath.touch(exist_ok=True) + # Configure the logger. + handler = logging.FileHandler(filepath) + formatter = logging.Formatter("%(message)s") + handler.setFormatter(formatter) + logger.addHandler(handler) + logger.propagate = False + return logger + + +# This lock must be used when accessing or updating global event logger dict. +_event_logger_lock = threading.Lock() +_event_logger = {} + + +def get_event_logger(source: Event.SourceType, sink_dir: str): + """Get the event logger of the current process. + + There's only 1 event logger per (process, source). + + TODO(sang): Support more impl than file-based logging. + Currently, the interface also ties to the + file-based logging impl. + + Args: + source: The source of the event. + sink_dir: The directory to sink event logs. + """ + with _event_logger_lock: + global _event_logger + source_name = Event.SourceType.Name(source) + if source_name not in _event_logger: + logger = _build_event_file_logger(source_name, sink_dir) + _event_logger[source_name] = EventLoggerAdapter(source, logger) + + return _event_logger[source_name] + + +def parse_event(event_str: str) -> Optional[Event]: + """Parse an event from a string. + + Args: + event_str: The string to parse. Expect to be a JSON serialized + Event protobuf. + + Returns: + The parsed event if parsable, else None + """ + try: + return Parse(event_str, Event()) + except Exception: + global_logger.exception(f"Failed to parse event: {event_str}") + return None + + +def filter_event_by_level(event: Event, filter_event_level: str) -> bool: + """Filter an event based on event level. + + Args: + event: The event to filter. + filter_event_level: The event level string to filter by. Any events + that are lower than this level will be filtered. + + Returns: + True if the event should be filtered, else False. + """ + + event_levels = { + Event.Severity.TRACE: 0, + Event.Severity.DEBUG: 1, + Event.Severity.INFO: 2, + Event.Severity.WARNING: 3, + Event.Severity.ERROR: 4, + Event.Severity.FATAL: 5, + } + + filter_event_level = filter_event_level.upper() + filter_event_level = Event.Severity.Value(filter_event_level) + + if event_levels[event.severity] < event_levels[filter_event_level]: + return True + + return False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/export_event_logger.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/export_event_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..4d47c68fb833545c79187cce8a7d6f0930714c7f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/event/export_event_logger.py @@ -0,0 +1,227 @@ +import json +import logging +import pathlib +import random +import string +import threading +from datetime import datetime +from enum import Enum +from typing import Union + +from ray._private import ray_constants +from ray._private.protobuf_compat import message_to_dict +from ray.core.generated.export_dataset_metadata_pb2 import ( + ExportDatasetMetadata, +) +from ray.core.generated.export_event_pb2 import ExportEvent +from ray.core.generated.export_submission_job_event_pb2 import ( + ExportSubmissionJobEventData, +) +from ray.core.generated.export_train_state_pb2 import ( + ExportTrainRunAttemptEventData, + ExportTrainRunEventData, +) + +global_logger = logging.getLogger(__name__) + +# This contains the union of export event data types which emit events +# using the python ExportEventLoggerAdapter +ExportEventDataType = Union[ + ExportSubmissionJobEventData, + ExportTrainRunEventData, + ExportTrainRunAttemptEventData, + ExportDatasetMetadata, +] + + +class EventLogType(Enum): + """Enum class representing different types of export event logs. + + Each enum value contains a log type name and a set of supported event data types. + + Attributes: + TRAIN_STATE: Export events related to training state, supporting train run and attempt events. + SUBMISSION_JOB: Export events related to job submissions. + DATASET_METADATA: Export events related to dataset metadata. + """ + + TRAIN_STATE = ( + "EXPORT_TRAIN_STATE", + {ExportTrainRunEventData, ExportTrainRunAttemptEventData}, + ) + SUBMISSION_JOB = ("EXPORT_SUBMISSION_JOB", {ExportSubmissionJobEventData}) + DATASET_METADATA = ("EXPORT_DATASET_METADATA", {ExportDatasetMetadata}) + + def __init__(self, log_type_name: str, event_types: set[ExportEventDataType]): + """Initialize an EventLogType enum value. + + Args: + log_type_name: String identifier for the log type. This name is used to construct the log file name. + See `_build_export_event_file_logger` for more details. + event_types: Set of event data types that this log type supports. + """ + self.log_type_name = log_type_name + self.event_types = event_types + + def supports_event_type(self, event_type: ExportEventDataType) -> bool: + """Check if this log type supports the given event data type. + + Args: + event_type: The event data type to check for support. + + Returns: + bool: True if the event type is supported, False otherwise. + """ + return type(event_type) in self.event_types + + +def generate_event_id(): + return "".join([random.choice(string.hexdigits) for _ in range(18)]) + + +class ExportEventLoggerAdapter: + def __init__(self, log_type: EventLogType, logger: logging.Logger): + """Adapter for the Python logger that's used to emit export events.""" + self.logger = logger + self.log_type = log_type + + def send_event(self, event_data: ExportEventDataType): + # NOTE: Python logger is thread-safe, + # so we don't need to protect it using locks. + try: + event = self._create_export_event(event_data) + except TypeError: + global_logger.exception( + "Failed to create ExportEvent from event_data so no " + "event will be written to file." + ) + return + + event_as_str = self._export_event_to_string(event) + + self.logger.info(event_as_str) + # Force flush so that we won't lose events + self.logger.handlers[0].flush() + + def _create_export_event(self, event_data: ExportEventDataType) -> ExportEvent: + event = ExportEvent() + event.event_id = generate_event_id() + event.timestamp = int(datetime.now().timestamp()) + if isinstance(event_data, ExportSubmissionJobEventData): + event.submission_job_event_data.CopyFrom(event_data) + event.source_type = ExportEvent.SourceType.EXPORT_SUBMISSION_JOB + elif isinstance(event_data, ExportTrainRunEventData): + event.train_run_event_data.CopyFrom(event_data) + event.source_type = ExportEvent.SourceType.EXPORT_TRAIN_RUN + elif isinstance(event_data, ExportTrainRunAttemptEventData): + event.train_run_attempt_event_data.CopyFrom(event_data) + event.source_type = ExportEvent.SourceType.EXPORT_TRAIN_RUN_ATTEMPT + elif isinstance(event_data, ExportDatasetMetadata): + event.dataset_metadata.CopyFrom(event_data) + event.source_type = ExportEvent.SourceType.EXPORT_DATASET_METADATA + else: + raise TypeError(f"Invalid event_data type: {type(event_data)}") + if not self.log_type.supports_event_type(event_data): + global_logger.error( + f"event_data has source type {event.source_type}, however " + f"the event was sent to a logger with log type {self.log_type.log_type_name}. " + f"The event will still be written to the file of {self.log_type.log_type_name} " + "but this indicates a bug in the code." + ) + pass + return event + + def _export_event_to_string(self, event: ExportEvent) -> str: + event_data_json = {} + proto_to_dict_options = { + "always_print_fields_with_no_presence": True, + "preserving_proto_field_name": True, + "use_integers_for_enums": False, + } + event_data_field_set = event.WhichOneof("event_data") + if event_data_field_set: + event_data_json = message_to_dict( + getattr(event, event_data_field_set), + **proto_to_dict_options, + ) + else: + global_logger.error( + f"event_data missing from export event with id {event.event_id} " + f"and type {event.source_type}. An empty event will be written, " + "but this indicates a bug in the code. " + ) + pass + event_json = { + "event_id": event.event_id, + "timestamp": event.timestamp, + "source_type": ExportEvent.SourceType.Name(event.source_type), + "event_data": event_data_json, + } + return json.dumps(event_json) + + +def _build_export_event_file_logger( + log_type_name: str, sink_dir: str +) -> logging.Logger: + logger = logging.getLogger("_ray_export_event_logger_" + log_type_name) + logger.setLevel(logging.INFO) + dir_path = pathlib.Path(sink_dir) / "export_events" + filepath = dir_path / f"event_{log_type_name}.log" + dir_path.mkdir(exist_ok=True) + filepath.touch(exist_ok=True) + # Configure the logger. + # Default is 100 MB max file size + handler = logging.handlers.RotatingFileHandler( + filepath, + maxBytes=(ray_constants.RAY_EXPORT_EVENT_MAX_FILE_SIZE_BYTES), + backupCount=ray_constants.RAY_EXPORT_EVENT_MAX_BACKUP_COUNT, + ) + logger.addHandler(handler) + logger.propagate = False + return logger + + +# This lock must be used when accessing or updating global event logger dict. +_export_event_logger_lock = threading.Lock() +_export_event_logger = {} + + +def get_export_event_logger(log_type: EventLogType, sink_dir: str) -> logging.Logger: + """Get the export event logger of the current process. + + There's only one logger per export event source. + + Args: + log_type: The type of the export event. + sink_dir: The directory to sink event logs. + """ + with _export_event_logger_lock: + global _export_event_logger + log_type_name = log_type.log_type_name + if log_type_name not in _export_event_logger: + logger = _build_export_event_file_logger(log_type.log_type_name, sink_dir) + _export_event_logger[log_type_name] = ExportEventLoggerAdapter( + log_type, logger + ) + + return _export_event_logger[log_type_name] + + +def check_export_api_enabled( + source: ExportEvent.SourceType, +) -> bool: + """ + Check RAY_ENABLE_EXPORT_API_WRITE and RAY_ENABLE_EXPORT_API_WRITE_CONFIG environment + variables to verify if export events should be written for the given source type. + + Args: + source: The source of the export event. + """ + if ray_constants.RAY_ENABLE_EXPORT_API_WRITE: + return True + source_name = ExportEvent.SourceType.Name(source) + return ( + source_name in ray_constants.RAY_ENABLE_EXPORT_API_WRITE_CONFIG + if ray_constants.RAY_ENABLE_EXPORT_API_WRITE_CONFIG + else False + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/external_storage.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/external_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..bfe9002f9e17a352db63d3a0258556537bfb47c3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/external_storage.py @@ -0,0 +1,652 @@ +import abc +import logging +import os +import random +import shutil +import time +import urllib +import uuid +from collections import namedtuple +from typing import IO, List, Optional, Tuple, Union + +import ray +from ray._private.ray_constants import DEFAULT_OBJECT_PREFIX +from ray._raylet import ObjectRef + +ParsedURL = namedtuple("ParsedURL", "base_url, offset, size") +logger = logging.getLogger(__name__) + + +def create_url_with_offset(*, url: str, offset: int, size: int) -> str: + """Methods to create a URL with offset. + + When ray spills objects, it fuses multiple objects + into one file to optimize the performance. That says, each object + needs to keep tracking of its own special url to store metadata. + + This method creates an url_with_offset, which is used internally + by Ray. + + Created url_with_offset can be passed to the self._get_base_url method + to parse the filename used to store files. + + Example) file://path/to/file?offset=""&size="" + + Args: + url: url to the object stored in the external storage. + offset: Offset from the beginning of the file to + the first bytes of this object. + size: Size of the object that is stored in the url. + It is used to calculate the last offset. + + Returns: + url_with_offset stored internally to find + objects from external storage. + """ + return f"{url}?offset={offset}&size={size}" + + +def parse_url_with_offset(url_with_offset: str) -> Tuple[str, int, int]: + """Parse url_with_offset to retrieve information. + + base_url is the url where the object ref + is stored in the external storage. + + Args: + url_with_offset: url created by create_url_with_offset. + + Returns: + named tuple of base_url, offset, and size. + """ + parsed_result = urllib.parse.urlparse(url_with_offset) + query_dict = urllib.parse.parse_qs(parsed_result.query) + # Split by ? to remove the query from the url. + base_url = parsed_result.geturl().split("?")[0] + if "offset" not in query_dict or "size" not in query_dict: + raise ValueError(f"Failed to parse URL: {url_with_offset}") + offset = int(query_dict["offset"][0]) + size = int(query_dict["size"][0]) + return ParsedURL(base_url=base_url, offset=offset, size=size) + + +class ExternalStorage(metaclass=abc.ABCMeta): + """The base class for external storage. + + This class provides some useful functions for zero-copy object + put/get from plasma store. Also it specifies the interface for + object spilling. + + When inheriting this class, please make sure to implement validation + logic inside __init__ method. When ray instance starts, it will + instantiating external storage to validate the config. + + Raises: + ValueError: when given configuration for + the external storage is invalid. + """ + + HEADER_LENGTH = 24 + CORE_WORKER_INIT_GRACE_PERIOD_S = 1 + + def __init__(self): + # NOTE(edoakes): do not access this field directly. Use the `core_worker` + # property instead to handle initialization race conditions. + self._core_worker: Optional["ray._raylet.CoreWorker"] = None + + @property + def core_worker(self) -> "ray._raylet.CoreWorker": + """Get the core_worker initialized in this process. + + In rare cases, the core worker may not be fully initialized by the time an I/O + worker begins to execute an operation because there is no explicit flag set to + indicate that the Python layer is ready to execute tasks. + """ + if self._core_worker is None: + worker = ray._private.worker.global_worker + start = time.time() + while not worker.connected: + time.sleep(0.001) + if time.time() - start > self.CORE_WORKER_INIT_GRACE_PERIOD_S: + raise RuntimeError( + "CoreWorker didn't initialize within grace period of " + f"{self.CORE_WORKER_INIT_GRACE_PERIOD_S}s." + ) + + self._core_worker = worker.core_worker + + return self._core_worker + + def _get_objects_from_store(self, object_refs): + # Since the object should always exist in the plasma store before + # spilling, it can directly get the object from the local plasma + # store. + # issue: https://github.com/ray-project/ray/pull/13831 + return self.core_worker.get_if_local(object_refs) + + def _put_object_to_store( + self, metadata, data_size, file_like, object_ref, owner_address + ): + self.core_worker.put_file_like_object( + metadata, data_size, file_like, object_ref, owner_address + ) + + def _write_multiple_objects( + self, f: IO, object_refs: List[ObjectRef], owner_addresses: List[str], url: str + ) -> List[str]: + """Fuse all given objects into a given file handle. + + Args: + f: File handle to fusion all given object refs. + object_refs: Object references to fusion to a single file. + owner_addresses: Owner addresses for the provided objects. + url: url where the object ref is stored + in the external storage. + + Return: + List of urls_with_offset of fused objects. + The order of returned keys are equivalent to the one + with given object_refs. + """ + keys = [] + offset = 0 + ray_object_pairs = self._get_objects_from_store(object_refs) + for ref, (buf, metadata, _), owner_address in zip( + object_refs, ray_object_pairs, owner_addresses + ): + address_len = len(owner_address) + metadata_len = len(metadata) + if buf is None and len(metadata) == 0: + error = f"Object {ref.hex()} does not exist." + raise ValueError(error) + buf_len = 0 if buf is None else len(buf) + payload = ( + address_len.to_bytes(8, byteorder="little") + + metadata_len.to_bytes(8, byteorder="little") + + buf_len.to_bytes(8, byteorder="little") + + owner_address + + metadata + + (memoryview(buf) if buf_len else b"") + ) + # 24 bytes to store owner address, metadata, and buffer lengths. + payload_len = len(payload) + assert ( + self.HEADER_LENGTH + address_len + metadata_len + buf_len == payload_len + ) + written_bytes = f.write(payload) + assert written_bytes == payload_len + url_with_offset = create_url_with_offset( + url=url, offset=offset, size=written_bytes + ) + keys.append(url_with_offset.encode()) + offset += written_bytes + # Necessary because pyarrow.io.NativeFile does not flush() on close(). + f.flush() + return keys + + def _size_check(self, address_len, metadata_len, buffer_len, obtained_data_size): + """Check whether or not the obtained_data_size is as expected. + + Args: + address_len: Length of the address. + metadata_len: Actual metadata length of the object. + buffer_len: Actual buffer length of the object. + obtained_data_size: Data size specified in the url_with_offset. + + Raises: + ValueError: If obtained_data_size is different from + address_len + metadata_len + buffer_len + 24 (first 8 bytes to store length). + """ + data_size_in_bytes = ( + address_len + metadata_len + buffer_len + self.HEADER_LENGTH + ) + if data_size_in_bytes != obtained_data_size: + raise ValueError( + f"Obtained data has a size of {data_size_in_bytes}, " + "although it is supposed to have the " + f"size of {obtained_data_size}." + ) + + @abc.abstractmethod + def spill_objects(self, object_refs, owner_addresses) -> List[str]: + """Spill objects to the external storage. Objects are specified + by their object refs. + + Args: + object_refs: The list of the refs of the objects to be spilled. + owner_addresses: Owner addresses for the provided objects. + Returns: + A list of internal URLs with object offset. + """ + + @abc.abstractmethod + def restore_spilled_objects( + self, object_refs: List[ObjectRef], url_with_offset_list: List[str] + ) -> int: + """Restore objects from the external storage. + + Args: + object_refs: List of object IDs (note that it is not ref). + url_with_offset_list: List of url_with_offset. + + Returns: + The total number of bytes restored. + """ + + @abc.abstractmethod + def delete_spilled_objects(self, urls: List[str]): + """Delete objects that are spilled to the external storage. + + Args: + urls: URLs that store spilled object files. + + NOTE: This function should not fail if some of the urls + do not exist. + """ + + @abc.abstractmethod + def destroy_external_storage(self): + """Destroy external storage when a head node is down. + + NOTE: This is currently working when the cluster is + started by ray.init + """ + + +class NullStorage(ExternalStorage): + """The class that represents an uninitialized external storage.""" + + def spill_objects(self, object_refs, owner_addresses) -> List[str]: + raise NotImplementedError("External storage is not initialized") + + def restore_spilled_objects(self, object_refs, url_with_offset_list): + raise NotImplementedError("External storage is not initialized") + + def delete_spilled_objects(self, urls: List[str]): + raise NotImplementedError("External storage is not initialized") + + def destroy_external_storage(self): + raise NotImplementedError("External storage is not initialized") + + +class FileSystemStorage(ExternalStorage): + """The class for filesystem-like external storage. + + Raises: + ValueError: Raises directory path to + spill objects doesn't exist. + """ + + def __init__( + self, + node_id: str, + directory_path: Union[str, List[str]], + buffer_size: Optional[int] = None, + ): + super().__init__() + + # -- A list of directory paths to spill objects -- + self._directory_paths = [] + # -- Current directory to spill objects -- + self._current_directory_index = 0 + # -- File buffer size to spill objects -- + self._buffer_size = -1 + + # Validation. + assert ( + directory_path is not None + ), "directory_path should be provided to use object spilling." + if isinstance(directory_path, str): + directory_path = [directory_path] + assert isinstance( + directory_path, list + ), "Directory_path must be either a single string or a list of strings" + if buffer_size is not None: + assert isinstance(buffer_size, int), "buffer_size must be an integer." + self._buffer_size = buffer_size + + # Create directories. + for path in directory_path: + full_dir_path = os.path.join(path, f"{DEFAULT_OBJECT_PREFIX}_{node_id}") + os.makedirs(full_dir_path, exist_ok=True) + if not os.path.exists(full_dir_path): + raise ValueError( + "The given directory path to store objects, " + f"{full_dir_path}, could not be created." + ) + self._directory_paths.append(full_dir_path) + assert len(self._directory_paths) == len(directory_path) + # Choose the current directory. + # It chooses a random index to maximize multiple directories that are + # mounted at different point. + self._current_directory_index = random.randrange(0, len(self._directory_paths)) + + def spill_objects(self, object_refs, owner_addresses) -> List[str]: + if len(object_refs) == 0: + return [] + # Choose the current directory path by round robin order. + self._current_directory_index = (self._current_directory_index + 1) % len( + self._directory_paths + ) + directory_path = self._directory_paths[self._current_directory_index] + + filename = _get_unique_spill_filename(object_refs) + url = f"{os.path.join(directory_path, filename)}" + with open(url, "wb", buffering=self._buffer_size) as f: + return self._write_multiple_objects(f, object_refs, owner_addresses, url) + + def restore_spilled_objects( + self, object_refs: List[ObjectRef], url_with_offset_list: List[str] + ): + total = 0 + for i in range(len(object_refs)): + object_ref = object_refs[i] + url_with_offset = url_with_offset_list[i].decode() + # Retrieve the information needed. + parsed_result = parse_url_with_offset(url_with_offset) + base_url = parsed_result.base_url + offset = parsed_result.offset + # Read a part of the file and recover the object. + with open(base_url, "rb") as f: + f.seek(offset) + address_len = int.from_bytes(f.read(8), byteorder="little") + metadata_len = int.from_bytes(f.read(8), byteorder="little") + buf_len = int.from_bytes(f.read(8), byteorder="little") + self._size_check(address_len, metadata_len, buf_len, parsed_result.size) + total += buf_len + owner_address = f.read(address_len) + metadata = f.read(metadata_len) + # read remaining data to our buffer + self._put_object_to_store( + metadata, buf_len, f, object_ref, owner_address + ) + return total + + def delete_spilled_objects(self, urls: List[str]): + for url in urls: + path = parse_url_with_offset(url.decode()).base_url + try: + os.remove(path) + except FileNotFoundError: + # Occurs when the urls are retried during worker crash/failure. + pass + + def destroy_external_storage(self): + for directory_path in self._directory_paths: + self._destroy_external_storage(directory_path) + + def _destroy_external_storage(self, directory_path): + # There's a race condition where IO workers are still + # deleting each objects while we try deleting the + # whole directory. So we should keep trying it until + # The directory is actually deleted. + while os.path.isdir(directory_path): + try: + shutil.rmtree(directory_path) + except (FileNotFoundError): + # If exception occurs when other IO workers are + # deleting the file at the same time. + pass + except Exception: + logger.exception( + "Error cleaning up spill files. " + "You might still have remaining spilled " + "objects inside `ray_spilled_objects` directory." + ) + break + + +class ExternalStorageSmartOpenImpl(ExternalStorage): + """The external storage class implemented by smart_open. + (https://github.com/RaRe-Technologies/smart_open) + + Smart open supports multiple backend with the same APIs. + + To use this implementation, you should pre-create the given uri. + For example, if your uri is a local file path, you should pre-create + the directory. + + Args: + uri: Storage URI used for smart open. + prefix: Prefix of objects that are stored. + override_transport_params: Overriding the default value of + transport_params for smart-open library. + + Raises: + ModuleNotFoundError: If it fails to setup. + For example, if smart open library + is not downloaded, this will fail. + """ + + def __init__( + self, + node_id: str, + uri: str or list, + override_transport_params: dict = None, + buffer_size=1024 * 1024, # For remote spilling, at least 1MB is recommended. + ): + super().__init__() + + try: + from smart_open import open # noqa + except ModuleNotFoundError as e: + raise ModuleNotFoundError( + "Smart open is chosen to be a object spilling " + "external storage, but smart_open and boto3 " + f"is not downloaded. Original error: {e}" + ) + + # Validation + assert uri is not None, "uri should be provided to use object spilling." + if isinstance(uri, str): + uri = [uri] + assert isinstance(uri, list), "uri must be a single string or list of strings." + assert isinstance(buffer_size, int), "buffer_size must be an integer." + + uri_is_s3 = [u.startswith("s3://") for u in uri] + self.is_for_s3 = all(uri_is_s3) + if not self.is_for_s3: + assert not any(uri_is_s3), "all uri's must be s3 or none can be s3." + self._uris = uri + else: + self._uris = [u.strip("/") for u in uri] + assert len(self._uris) == len(uri) + + self._current_uri_index = random.randrange(0, len(self._uris)) + self.prefix = f"{DEFAULT_OBJECT_PREFIX}_{node_id}" + self.override_transport_params = override_transport_params or {} + + if self.is_for_s3: + import boto3 # noqa + + # Setup boto3. It is essential because if we don't create boto + # session, smart_open will create a new session for every + # open call. + self.s3 = boto3.resource(service_name="s3") + + # smart_open always seek to 0 if we don't set this argument. + # This will lead us to call a Object.get when it is not necessary, + # so defer seek and call seek before reading objects instead. + self.transport_params = { + "defer_seek": True, + "resource": self.s3, + "buffer_size": buffer_size, + } + else: + self.transport_params = {} + + self.transport_params.update(self.override_transport_params) + + def spill_objects(self, object_refs, owner_addresses) -> List[str]: + if len(object_refs) == 0: + return [] + from smart_open import open + + # Choose the current uri by round robin order. + self._current_uri_index = (self._current_uri_index + 1) % len(self._uris) + uri = self._uris[self._current_uri_index] + + key = f"{self.prefix}-{_get_unique_spill_filename(object_refs)}" + url = f"{uri}/{key}" + + with open( + url, + mode="wb", + transport_params=self.transport_params, + ) as file_like: + return self._write_multiple_objects( + file_like, object_refs, owner_addresses, url + ) + + def restore_spilled_objects( + self, object_refs: List[ObjectRef], url_with_offset_list: List[str] + ): + from smart_open import open + + total = 0 + for i in range(len(object_refs)): + object_ref = object_refs[i] + url_with_offset = url_with_offset_list[i].decode() + + # Retrieve the information needed. + parsed_result = parse_url_with_offset(url_with_offset) + base_url = parsed_result.base_url + offset = parsed_result.offset + + with open(base_url, "rb", transport_params=self.transport_params) as f: + # smart open seek reads the file from offset-end_of_the_file + # when the seek is called. + f.seek(offset) + address_len = int.from_bytes(f.read(8), byteorder="little") + metadata_len = int.from_bytes(f.read(8), byteorder="little") + buf_len = int.from_bytes(f.read(8), byteorder="little") + self._size_check(address_len, metadata_len, buf_len, parsed_result.size) + owner_address = f.read(address_len) + total += buf_len + metadata = f.read(metadata_len) + # read remaining data to our buffer + self._put_object_to_store( + metadata, buf_len, f, object_ref, owner_address + ) + return total + + def delete_spilled_objects(self, urls: List[str]): + pass + + def destroy_external_storage(self): + pass + + +_external_storage = NullStorage() + + +class UnstableFileStorage(FileSystemStorage): + """This class is for testing with writing failure.""" + + def __init__(self, node_id: str, **kwargs): + super().__init__(node_id, **kwargs) + self._failure_rate = 0.1 + self._partial_failure_ratio = 0.2 + + def spill_objects(self, object_refs, owner_addresses) -> List[str]: + r = random.random() < self._failure_rate + failed = r < self._failure_rate + partial_failed = r < self._partial_failure_ratio + if failed: + raise IOError("Spilling object failed intentionally for testing.") + elif partial_failed: + i = random.choice(range(len(object_refs))) + return super().spill_objects(object_refs[:i], owner_addresses) + else: + return super().spill_objects(object_refs, owner_addresses) + + +class SlowFileStorage(FileSystemStorage): + """This class is for testing slow object spilling.""" + + def __init__(self, node_id: str, **kwargs): + super().__init__(node_id, **kwargs) + self._min_delay = 1 + self._max_delay = 2 + + def spill_objects(self, object_refs, owner_addresses) -> List[str]: + delay = random.random() * (self._max_delay - self._min_delay) + self._min_delay + time.sleep(delay) + return super().spill_objects(object_refs, owner_addresses) + + +def setup_external_storage(config, node_id, session_name): + """Setup the external storage according to the config.""" + assert node_id is not None, "node_id should be provided." + global _external_storage + if config: + storage_type = config["type"] + if storage_type == "filesystem": + _external_storage = FileSystemStorage(node_id, **config["params"]) + elif storage_type == "smart_open": + _external_storage = ExternalStorageSmartOpenImpl( + node_id, **config["params"] + ) + elif storage_type == "mock_distributed_fs": + # This storage is used to unit test distributed external storages. + # TODO(sang): Delete it after introducing the mock S3 test. + _external_storage = FileSystemStorage(node_id, **config["params"]) + elif storage_type == "unstable_fs": + # This storage is used to unit test unstable file system for fault + # tolerance. + _external_storage = UnstableFileStorage(node_id, **config["params"]) + elif storage_type == "slow_fs": + # This storage is used to unit test slow filesystems. + _external_storage = SlowFileStorage(node_id, **config["params"]) + else: + raise ValueError(f"Unknown external storage type: {storage_type}") + else: + _external_storage = NullStorage() + return _external_storage + + +def reset_external_storage(): + global _external_storage + _external_storage = NullStorage() + + +def spill_objects(object_refs, owner_addresses): + """Spill objects to the external storage. Objects are specified + by their object refs. + + Args: + object_refs: The list of the refs of the objects to be spilled. + owner_addresses: The owner addresses of the provided object refs. + Returns: + A list of keys corresponding to the input object refs. + """ + return _external_storage.spill_objects(object_refs, owner_addresses) + + +def restore_spilled_objects( + object_refs: List[ObjectRef], url_with_offset_list: List[str] +): + """Restore objects from the external storage. + + Args: + object_refs: List of object IDs (note that it is not ref). + url_with_offset_list: List of url_with_offset. + """ + return _external_storage.restore_spilled_objects(object_refs, url_with_offset_list) + + +def delete_spilled_objects(urls: List[str]): + """Delete objects that are spilled to the external storage. + + Args: + urls: URLs that store spilled object files. + """ + _external_storage.delete_spilled_objects(urls) + + +def _get_unique_spill_filename(object_refs: List[ObjectRef]): + """Generate a unqiue spill file name. + + Args: + object_refs: objects to be spilled in this file. + """ + return f"{uuid.uuid4().hex}-multi-{len(object_refs)}" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/function_manager.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/function_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..854a50249d0a34fca6b1771a097cff4484e67baf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/function_manager.py @@ -0,0 +1,699 @@ +import dis +import hashlib +import importlib +import inspect +import json +import logging +import os +import sys +import threading +import time +import traceback +from collections import defaultdict, namedtuple +from typing import Callable, Optional + +import ray +import ray._private.profiling as profiling +from ray import cloudpickle as pickle +from ray._private import ray_constants +from ray._private.inspect_util import ( + is_class_method, + is_function_or_method, + is_static_method, +) +from ray._private.ray_constants import KV_NAMESPACE_FUNCTION_TABLE +from ray._private.serialization import pickle_dumps +from ray._private.utils import ( + check_oversized_function, + ensure_str, + format_error_message, +) +from ray._raylet import ( + WORKER_PROCESS_SETUP_HOOK_KEY_NAME_GCS, + JobID, + PythonFunctionDescriptor, +) +from ray.remote_function import RemoteFunction + +FunctionExecutionInfo = namedtuple( + "FunctionExecutionInfo", ["function", "function_name", "max_calls"] +) +ImportedFunctionInfo = namedtuple( + "ImportedFunctionInfo", + ["job_id", "function_id", "function_name", "function", "module", "max_calls"], +) + +"""FunctionExecutionInfo: A named tuple storing remote function information.""" + +logger = logging.getLogger(__name__) + + +def make_function_table_key(key_type: bytes, job_id: JobID, key: Optional[bytes]): + if key is None: + return b":".join([key_type, job_id.hex().encode()]) + else: + return b":".join([key_type, job_id.hex().encode(), key]) + + +class FunctionActorManager: + """A class used to export/load remote functions and actors. + Attributes: + _worker: The associated worker that this manager related. + _functions_to_export: The remote functions to export when + the worker gets connected. + _actors_to_export: The actors to export when the worker gets + connected. + _function_execution_info: The function_id + and execution_info. + _num_task_executions: The function + execution times. + imported_actor_classes: The set of actor classes keys (format: + ActorClass:function_id) that are already in GCS. + """ + + def __init__(self, worker): + self._worker = worker + self._functions_to_export = [] + self._actors_to_export = [] + # This field is a dictionary that maps function IDs + # to a FunctionExecutionInfo object. This should only be used on + # workers that execute remote functions. + self._function_execution_info = defaultdict(lambda: {}) + self._num_task_executions = defaultdict(lambda: {}) + # A set of all of the actor class keys that have been imported by the + # import thread. It is safe to convert this worker into an actor of + # these types. + self.imported_actor_classes = set() + self._loaded_actor_classes = {} + # Deserialize an ActorHandle will call load_actor_class(). If a + # function closure captured an ActorHandle, the deserialization of the + # function will be: + # -> fetch_and_register_remote_function (acquire lock) + # -> _load_actor_class_from_gcs (acquire lock, too) + # So, the lock should be a reentrant lock. + self.lock = threading.RLock() + + self.execution_infos = {} + # This is the counter to keep track of how many keys have already + # been exported so that we can find next key quicker. + self._num_exported = 0 + # This is to protect self._num_exported when doing exporting + self._export_lock = threading.Lock() + + def increase_task_counter(self, function_descriptor): + function_id = function_descriptor.function_id + self._num_task_executions[function_id] += 1 + + def get_task_counter(self, function_descriptor): + function_id = function_descriptor.function_id + return self._num_task_executions[function_id] + + def compute_collision_identifier(self, function_or_class): + """The identifier is used to detect excessive duplicate exports. + The identifier is used to determine when the same function or class is + exported many times. This can yield false positives. + Args: + function_or_class: The function or class to compute an identifier + for. + Returns: + The identifier. Note that different functions or classes can give + rise to same identifier. However, the same function should + hopefully always give rise to the same identifier. TODO(rkn): + verify if this is actually the case. Note that if the + identifier is incorrect in any way, then we may give warnings + unnecessarily or fail to give warnings, but the application's + behavior won't change. + """ + import io + + string_file = io.StringIO() + dis.dis(function_or_class, file=string_file, depth=2) + collision_identifier = function_or_class.__name__ + ":" + string_file.getvalue() + + # Return a hash of the identifier in case it is too large. + return hashlib.sha1(collision_identifier.encode("utf-8")).digest() + + def load_function_or_class_from_local(self, module_name, function_or_class_name): + """Try to load a function or class in the module from local.""" + module = importlib.import_module(module_name) + parts = [part for part in function_or_class_name.split(".") if part] + object = module + try: + for part in parts: + object = getattr(object, part) + return object + except Exception: + return None + + def export_setup_func( + self, setup_func: Callable, timeout: Optional[int] = None + ) -> bytes: + """Export the setup hook function and return the key.""" + pickled_function = pickle_dumps( + setup_func, + "Cannot serialize the worker_process_setup_hook " f"{setup_func.__name__}", + ) + + function_to_run_id = hashlib.shake_128(pickled_function).digest( + ray_constants.ID_SIZE + ) + key = make_function_table_key( + # This value should match with gcs_function_manager.h. + # Otherwise, it won't be GC'ed. + WORKER_PROCESS_SETUP_HOOK_KEY_NAME_GCS.encode(), + # b"FunctionsToRun", + self._worker.current_job_id.binary(), + function_to_run_id, + ) + + check_oversized_function( + pickled_function, setup_func.__name__, "function", self._worker + ) + + try: + self._worker.gcs_client.internal_kv_put( + key, + pickle.dumps( + { + "job_id": self._worker.current_job_id.binary(), + "function_id": function_to_run_id, + "function": pickled_function, + } + ), + # overwrite + True, + ray_constants.KV_NAMESPACE_FUNCTION_TABLE, + timeout=timeout, + ) + except Exception as e: + logger.exception( + "Failed to export the setup hook " f"{setup_func.__name__}." + ) + raise e + + return key + + def export(self, remote_function): + """Pickle a remote function and export it to redis. + Args: + remote_function: the RemoteFunction object. + """ + if self._worker.load_code_from_local: + function_descriptor = remote_function._function_descriptor + module_name, function_name = ( + function_descriptor.module_name, + function_descriptor.function_name, + ) + # If the function is dynamic, we still export it to GCS + # even if load_code_from_local is set True. + if ( + self.load_function_or_class_from_local(module_name, function_name) + is not None + ): + return + function = remote_function._function + pickled_function = remote_function._pickled_function + + check_oversized_function( + pickled_function, + remote_function._function_name, + "remote function", + self._worker, + ) + key = make_function_table_key( + b"RemoteFunction", + self._worker.current_job_id, + remote_function._function_descriptor.function_id.binary(), + ) + if self._worker.gcs_client.internal_kv_exists(key, KV_NAMESPACE_FUNCTION_TABLE): + return + val = pickle.dumps( + { + "job_id": self._worker.current_job_id.binary(), + "function_id": remote_function._function_descriptor.function_id.binary(), # noqa: E501 + "function_name": remote_function._function_name, + "module": function.__module__, + "function": pickled_function, + "collision_identifier": self.compute_collision_identifier(function), + "max_calls": remote_function._max_calls, + } + ) + self._worker.gcs_client.internal_kv_put( + key, val, True, KV_NAMESPACE_FUNCTION_TABLE + ) + + def fetch_registered_method( + self, key: str, timeout: Optional[int] = None + ) -> Optional[ImportedFunctionInfo]: + vals = self._worker.gcs_client.internal_kv_get( + key, KV_NAMESPACE_FUNCTION_TABLE, timeout=timeout + ) + if vals is None: + return None + else: + vals = pickle.loads(vals) + fields = [ + "job_id", + "function_id", + "function_name", + "function", + "module", + "max_calls", + ] + return ImportedFunctionInfo._make(vals.get(field) for field in fields) + + def fetch_and_register_remote_function(self, key): + """Import a remote function.""" + remote_function_info = self.fetch_registered_method(key) + if not remote_function_info: + return False + ( + job_id_str, + function_id_str, + function_name, + serialized_function, + module, + max_calls, + ) = remote_function_info + + function_id = ray.FunctionID(function_id_str) + job_id = ray.JobID(job_id_str) + max_calls = int(max_calls) + + # This function is called by ImportThread. This operation needs to be + # atomic. Otherwise, there is race condition. Another thread may use + # the temporary function above before the real function is ready. + with self.lock: + self._num_task_executions[function_id] = 0 + + try: + function = pickle.loads(serialized_function) + except Exception: + # If an exception was thrown when the remote function was + # imported, we record the traceback and notify the scheduler + # of the failure. + traceback_str = format_error_message(traceback.format_exc()) + + def f(*args, **kwargs): + raise RuntimeError( + "The remote function failed to import on the " + "worker. This may be because needed library " + "dependencies are not installed in the worker " + "environment or cannot be found from sys.path " + f"{sys.path}:\n\n{traceback_str}" + ) + + # Use a placeholder method when function pickled failed + self._function_execution_info[function_id] = FunctionExecutionInfo( + function=f, function_name=function_name, max_calls=max_calls + ) + + # Log the error message. Log at DEBUG level to avoid overly + # spamming the log on import failure. The user gets the error + # via the RuntimeError message above. + logger.debug( + "Failed to unpickle the remote function " + f"'{function_name}' with " + f"function ID {function_id.hex()}. " + f"Job ID:{job_id}." + f"Traceback:\n{traceback_str}. " + ) + else: + # The below line is necessary. Because in the driver process, + # if the function is defined in the file where the python + # script was started from, its module is `__main__`. + # However in the worker process, the `__main__` module is a + # different module, which is `default_worker.py` + function.__module__ = module + self._function_execution_info[function_id] = FunctionExecutionInfo( + function=function, function_name=function_name, max_calls=max_calls + ) + return True + + def get_execution_info(self, job_id, function_descriptor): + """Get the FunctionExecutionInfo of a remote function. + Args: + job_id: ID of the job that the function belongs to. + function_descriptor: The FunctionDescriptor of the function to get. + Returns: + A FunctionExecutionInfo object. + """ + function_id = function_descriptor.function_id + # If the function has already been loaded, + # There's no need to load again + if function_id in self._function_execution_info: + return self._function_execution_info[function_id] + if self._worker.load_code_from_local: + # Load function from local code. + if not function_descriptor.is_actor_method(): + # If the function is not able to be loaded, + # try to load it from GCS, + # even if load_code_from_local is set True + if self._load_function_from_local(function_descriptor) is True: + return self._function_execution_info[function_id] + # Load function from GCS. + # Wait until the function to be executed has actually been + # registered on this worker. We will push warnings to the user if + # we spend too long in this loop. + # The driver function may not be found in sys.path. Try to load + # the function from GCS. + with profiling.profile("wait_for_function"): + self._wait_for_function(function_descriptor, job_id) + try: + function_id = function_descriptor.function_id + info = self._function_execution_info[function_id] + except KeyError as e: + message = ( + "Error occurs in get_execution_info: " + "job_id: %s, function_descriptor: %s. Message: %s" + % (job_id, function_descriptor, e) + ) + raise KeyError(message) + return info + + def _load_function_from_local(self, function_descriptor): + assert not function_descriptor.is_actor_method() + function_id = function_descriptor.function_id + + module_name, function_name = ( + function_descriptor.module_name, + function_descriptor.function_name, + ) + + object = self.load_function_or_class_from_local(module_name, function_name) + if object is not None: + # Directly importing from local may break function with dynamic ray.remote, + # such as the _start_controller function utilized for the Ray service. + if isinstance(object, RemoteFunction): + function = object._function + else: + function = object + self._function_execution_info[function_id] = FunctionExecutionInfo( + function=function, + function_name=function_name, + max_calls=0, + ) + self._num_task_executions[function_id] = 0 + return True + else: + return False + + def _wait_for_function(self, function_descriptor, job_id: str, timeout=10): + """Wait until the function to be executed is present on this worker. + This method will simply loop until the import thread has imported the + relevant function. If we spend too long in this loop, that may indicate + a problem somewhere and we will push an error message to the user. + If this worker is an actor, then this will wait until the actor has + been defined. + Args: + function_descriptor : The FunctionDescriptor of the function that + we want to execute. + job_id: The ID of the job to push the error message to + if this times out. + """ + start_time = time.time() + # Only send the warning once. + warning_sent = False + while True: + with self.lock: + if self._worker.actor_id.is_nil(): + if function_descriptor.function_id in self._function_execution_info: + break + else: + key = make_function_table_key( + b"RemoteFunction", + job_id, + function_descriptor.function_id.binary(), + ) + if self.fetch_and_register_remote_function(key) is True: + break + else: + assert not self._worker.actor_id.is_nil() + # Actor loading will happen when execute_task is called. + assert self._worker.actor_id in self._worker.actors + break + + if time.time() - start_time > timeout: + warning_message = ( + "This worker was asked to execute a function " + f"that has not been registered ({function_descriptor}, " + f"node={self._worker.node_ip_address}, " + f"worker_id={self._worker.worker_id.hex()}, " + f"pid={os.getpid()}). You may have to restart Ray." + ) + if not warning_sent: + logger.error(warning_message) + ray._private.utils.push_error_to_driver( + self._worker, + ray_constants.WAIT_FOR_FUNCTION_PUSH_ERROR, + warning_message, + job_id=job_id, + ) + warning_sent = True + time.sleep(0.001) + + def export_actor_class( + self, Class, actor_creation_function_descriptor, actor_method_names + ): + if self._worker.load_code_from_local: + module_name, class_name = ( + actor_creation_function_descriptor.module_name, + actor_creation_function_descriptor.class_name, + ) + # If the class is dynamic, we still export it to GCS + # even if load_code_from_local is set True. + if ( + self.load_function_or_class_from_local(module_name, class_name) + is not None + ): + return + + # `current_job_id` shouldn't be NIL, unless: + # 1) This worker isn't an actor; + # 2) And a previous task started a background thread, which didn't + # finish before the task finished, and still uses Ray API + # after that. + assert not self._worker.current_job_id.is_nil(), ( + "You might have started a background thread in a non-actor " + "task, please make sure the thread finishes before the " + "task finishes." + ) + job_id = self._worker.current_job_id + key = make_function_table_key( + b"ActorClass", + job_id, + actor_creation_function_descriptor.function_id.binary(), + ) + serialized_actor_class = pickle_dumps( + Class, + f"Could not serialize the actor class " + f"{actor_creation_function_descriptor.repr}", + ) + actor_class_info = { + "class_name": actor_creation_function_descriptor.class_name.split(".")[-1], + "module": actor_creation_function_descriptor.module_name, + "class": serialized_actor_class, + "job_id": job_id.binary(), + "collision_identifier": self.compute_collision_identifier(Class), + "actor_method_names": json.dumps(list(actor_method_names)), + } + + check_oversized_function( + actor_class_info["class"], + actor_class_info["class_name"], + "actor", + self._worker, + ) + + self._worker.gcs_client.internal_kv_put( + key, pickle.dumps(actor_class_info), True, KV_NAMESPACE_FUNCTION_TABLE + ) + # TODO(rkn): Currently we allow actor classes to be defined + # within tasks. I tried to disable this, but it may be necessary + # because of https://github.com/ray-project/ray/issues/1146. + + def load_actor_class(self, job_id, actor_creation_function_descriptor): + """Load the actor class. + Args: + job_id: job ID of the actor. + actor_creation_function_descriptor: Function descriptor of + the actor constructor. + Returns: + The actor class. + """ + function_id = actor_creation_function_descriptor.function_id + # Check if the actor class already exists in the cache. + actor_class = self._loaded_actor_classes.get(function_id, None) + if actor_class is None: + # Load actor class. + if self._worker.load_code_from_local: + # Load actor class from local code first. + actor_class = self._load_actor_class_from_local( + actor_creation_function_descriptor + ) + # If the actor is unable to be loaded + # from local, try to load it + # from GCS even if load_code_from_local is set True + if actor_class is None: + actor_class = self._load_actor_class_from_gcs( + job_id, actor_creation_function_descriptor + ) + + else: + # Load actor class from GCS. + actor_class = self._load_actor_class_from_gcs( + job_id, actor_creation_function_descriptor + ) + # Save the loaded actor class in cache. + self._loaded_actor_classes[function_id] = actor_class + + # Generate execution info for the methods of this actor class. + module_name = actor_creation_function_descriptor.module_name + actor_class_name = actor_creation_function_descriptor.class_name + actor_methods = inspect.getmembers( + actor_class, predicate=is_function_or_method + ) + for actor_method_name, actor_method in actor_methods: + # Actor creation function descriptor use a unique function + # hash to solve actor name conflict. When constructing an + # actor, the actor creation function descriptor will be the + # key to find __init__ method execution info. So, here we + # use actor creation function descriptor as method descriptor + # for generating __init__ method execution info. + if actor_method_name == "__init__": + method_descriptor = actor_creation_function_descriptor + else: + method_descriptor = PythonFunctionDescriptor( + module_name, actor_method_name, actor_class_name + ) + method_id = method_descriptor.function_id + executor = self._make_actor_method_executor( + actor_method_name, actor_method + ) + self._function_execution_info[method_id] = FunctionExecutionInfo( + function=executor, + function_name=actor_method_name, + max_calls=0, + ) + self._num_task_executions[method_id] = 0 + self._num_task_executions[function_id] = 0 + return actor_class + + def _load_actor_class_from_local(self, actor_creation_function_descriptor): + """Load actor class from local code.""" + module_name, class_name = ( + actor_creation_function_descriptor.module_name, + actor_creation_function_descriptor.class_name, + ) + + object = self.load_function_or_class_from_local(module_name, class_name) + + if object is not None: + if isinstance(object, ray.actor.ActorClass): + return object.__ray_metadata__.modified_class + else: + return object + else: + return None + + def _create_fake_actor_class( + self, actor_class_name, actor_method_names, traceback_str + ): + class TemporaryActor: + pass + + def temporary_actor_method(*args, **kwargs): + raise RuntimeError( + f"The actor with name {actor_class_name} " + "failed to import on the worker. This may be because " + "needed library dependencies are not installed in the " + f"worker environment:\n\n{traceback_str}" + ) + + for method in actor_method_names: + setattr(TemporaryActor, method, temporary_actor_method) + + return TemporaryActor + + def _load_actor_class_from_gcs(self, job_id, actor_creation_function_descriptor): + """Load actor class from GCS.""" + key = make_function_table_key( + b"ActorClass", + job_id, + actor_creation_function_descriptor.function_id.binary(), + ) + + # Fetch raw data from GCS. + vals = self._worker.gcs_client.internal_kv_get(key, KV_NAMESPACE_FUNCTION_TABLE) + fields = ["job_id", "class_name", "module", "class", "actor_method_names"] + if vals is None: + vals = {} + else: + vals = pickle.loads(vals) + (job_id_str, class_name, module, pickled_class, actor_method_names) = ( + vals.get(field) for field in fields + ) + + class_name = ensure_str(class_name) + module_name = ensure_str(module) + job_id = ray.JobID(job_id_str) + actor_method_names = json.loads(ensure_str(actor_method_names)) + + actor_class = None + try: + with self.lock: + actor_class = pickle.loads(pickled_class) + except Exception: + logger.debug("Failed to load actor class %s.", class_name) + # If an exception was thrown when the actor was imported, we record + # the traceback and notify the scheduler of the failure. + traceback_str = format_error_message(traceback.format_exc()) + # The actor class failed to be unpickled, create a fake actor + # class instead (just to produce error messages and to prevent + # the driver from hanging). + actor_class = self._create_fake_actor_class( + class_name, actor_method_names, traceback_str + ) + + # The below line is necessary. Because in the driver process, + # if the function is defined in the file where the python script + # was started from, its module is `__main__`. + # However in the worker process, the `__main__` module is a + # different module, which is `default_worker.py` + actor_class.__module__ = module_name + return actor_class + + def _make_actor_method_executor(self, method_name: str, method): + """Make an executor that wraps a user-defined actor method. + The wrapped method updates the worker's internal state and performs any + necessary checkpointing operations. + Args: + method_name: The name of the actor method. + method: The actor method to wrap. This should be a + method defined on the actor class and should therefore take an + instance of the actor as the first argument. + Returns: + A function that executes the given actor method on the worker's + stored instance of the actor. The function also updates the + worker's internal state to record the executed method. + """ + + def actor_method_executor(__ray_actor, *args, **kwargs): + # Execute the assigned method. + is_bound = is_class_method(method) or is_static_method( + type(__ray_actor), method_name + ) + if is_bound: + return method(*args, **kwargs) + else: + return method(__ray_actor, *args, **kwargs) + + # Set method_name and method as attributes to the executor closure + # so we can make decision based on these attributes in task executor. + # Precisely, asyncio support requires to know whether: + # - the method is a ray internal method: starts with __ray + # - the method is a coroutine function: defined by async def + actor_method_executor.name = method_name + actor_method_executor.method = method + + return actor_method_executor diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/gcs_pubsub.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/gcs_pubsub.py new file mode 100644 index 0000000000000000000000000000000000000000..e40d74b72bec7cf9d2c374db09d4dd44d24eccdf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/gcs_pubsub.py @@ -0,0 +1,274 @@ +import asyncio +import logging +import random +from collections import deque +from typing import List, Tuple + +import grpc +from grpc import aio as aiogrpc + +import ray._private.gcs_utils as gcs_utils +from ray._common.utils import get_or_create_event_loop +from ray.core.generated import ( + gcs_pb2, + gcs_service_pb2, + gcs_service_pb2_grpc, + pubsub_pb2, +) + +logger = logging.getLogger(__name__) + + +class _SubscriberBase: + def __init__(self, worker_id: bytes = None): + self._worker_id = worker_id + # self._subscriber_id needs to match the binary format of a random + # SubscriberID / UniqueID, which is 28 (kUniqueIDSize) random bytes. + self._subscriber_id = bytes(bytearray(random.getrandbits(8) for _ in range(28))) + self._last_batch_size = 0 + self._max_processed_sequence_id = 0 + self._publisher_id = b"" + + # Batch size of the result from last poll. Used to indicate whether the + # subscriber can keep up. + @property + def last_batch_size(self): + return self._last_batch_size + + def _subscribe_request(self, channel): + cmd = pubsub_pb2.Command(channel_type=channel, subscribe_message={}) + req = gcs_service_pb2.GcsSubscriberCommandBatchRequest( + subscriber_id=self._subscriber_id, sender_id=self._worker_id, commands=[cmd] + ) + return req + + def _poll_request(self): + return gcs_service_pb2.GcsSubscriberPollRequest( + subscriber_id=self._subscriber_id, + max_processed_sequence_id=self._max_processed_sequence_id, + publisher_id=self._publisher_id, + ) + + def _unsubscribe_request(self, channels): + req = gcs_service_pb2.GcsSubscriberCommandBatchRequest( + subscriber_id=self._subscriber_id, sender_id=self._worker_id, commands=[] + ) + for channel in channels: + req.commands.append( + pubsub_pb2.Command(channel_type=channel, unsubscribe_message={}) + ) + return req + + @staticmethod + def _should_terminate_polling(e: grpc.RpcError) -> None: + # Caller only expects polling to be terminated after deadline exceeded. + if e.code() == grpc.StatusCode.DEADLINE_EXCEEDED: + return True + # Could be a temporary connection issue. Suppress error. + # TODO: reconnect GRPC channel? + if e.code() == grpc.StatusCode.UNAVAILABLE: + return True + return False + + +class _AioSubscriber(_SubscriberBase): + """Async io subscriber to GCS. + + Usage example common to Aio subscribers: + subscriber = GcsAioXxxSubscriber(address="...") + await subscriber.subscribe() + while running: + ...... = await subscriber.poll() + ...... + await subscriber.close() + """ + + def __init__( + self, + pubsub_channel_type, + worker_id: bytes = None, + address: str = None, + channel: aiogrpc.Channel = None, + ): + super().__init__(worker_id) + + if address: + assert channel is None, "address and channel cannot both be specified" + channel = gcs_utils.create_gcs_channel(address, aio=True) + else: + assert channel is not None, "One of address and channel must be specified" + # GRPC stub to GCS pubsub. + self._stub = gcs_service_pb2_grpc.InternalPubSubGcsServiceStub(channel) + + # Type of the channel. + self._channel = pubsub_channel_type + # A queue of received PubMessage. + self._queue = deque() + # Indicates whether the subscriber has closed. + self._close = asyncio.Event() + + async def subscribe(self) -> None: + """Registers a subscription for the subscriber's channel type. + + Before the registration, published messages in the channel will not be + saved for the subscriber. + """ + if self._close.is_set(): + return + req = self._subscribe_request(self._channel) + await self._stub.GcsSubscriberCommandBatch(req, timeout=30) + + async def _poll_call(self, req, timeout=None): + # Wrap GRPC _AioCall as a coroutine. + return await self._stub.GcsSubscriberPoll(req, timeout=timeout) + + async def _poll(self, timeout=None) -> None: + while len(self._queue) == 0: + req = self._poll_request() + poll = get_or_create_event_loop().create_task( + self._poll_call(req, timeout=timeout) + ) + close = get_or_create_event_loop().create_task(self._close.wait()) + done, others = await asyncio.wait( + [poll, close], timeout=timeout, return_when=asyncio.FIRST_COMPLETED + ) + # Cancel the other task if needed to prevent memory leak. + other_task = others.pop() + if not other_task.done(): + other_task.cancel() + if poll not in done or close in done: + # Request timed out or subscriber closed. + break + try: + self._last_batch_size = len(poll.result().pub_messages) + if poll.result().publisher_id != self._publisher_id: + if self._publisher_id != "": + logger.debug( + f"replied publisher_id {poll.result().publisher_id}" + f"different from {self._publisher_id}, this should " + "only happens during gcs failover." + ) + self._publisher_id = poll.result().publisher_id + self._max_processed_sequence_id = 0 + for msg in poll.result().pub_messages: + if msg.sequence_id <= self._max_processed_sequence_id: + logger.warning(f"Ignoring out of order message {msg}") + continue + self._max_processed_sequence_id = msg.sequence_id + self._queue.append(msg) + except grpc.RpcError as e: + if self._should_terminate_polling(e): + return + raise + + async def close(self) -> None: + """Closes the subscriber and its active subscription.""" + + # Mark close to terminate inflight polling and prevent future requests. + if self._close.is_set(): + return + self._close.set() + req = self._unsubscribe_request(channels=[self._channel]) + try: + await self._stub.GcsSubscriberCommandBatch(req, timeout=5) + except Exception: + pass + self._stub = None + + +class GcsAioResourceUsageSubscriber(_AioSubscriber): + def __init__( + self, + worker_id: bytes = None, + address: str = None, + channel: grpc.Channel = None, + ): + super().__init__( + pubsub_pb2.RAY_NODE_RESOURCE_USAGE_CHANNEL, worker_id, address, channel + ) + + async def poll(self, timeout=None) -> Tuple[bytes, str]: + """Polls for new resource usage message. + + Returns: + A tuple of string reporter ID and resource usage json string. + """ + await self._poll(timeout=timeout) + return self._pop_resource_usage(self._queue) + + @staticmethod + def _pop_resource_usage(queue): + if len(queue) == 0: + return None, None + msg = queue.popleft() + return msg.key_id.decode(), msg.node_resource_usage_message.json + + +class GcsAioActorSubscriber(_AioSubscriber): + def __init__( + self, + worker_id: bytes = None, + address: str = None, + channel: grpc.Channel = None, + ): + super().__init__(pubsub_pb2.GCS_ACTOR_CHANNEL, worker_id, address, channel) + + @property + def queue_size(self): + return len(self._queue) + + async def poll( + self, batch_size, timeout=None + ) -> List[Tuple[bytes, gcs_pb2.ActorTableData]]: + """Polls for new actor message. + + Returns: + A list of tuples of binary actor ID and actor table data. + """ + await self._poll(timeout=timeout) + return self._pop_actors(self._queue, batch_size=batch_size) + + @staticmethod + def _pop_actors(queue, batch_size): + if len(queue) == 0: + return [] + popped = 0 + msgs = [] + while len(queue) > 0 and popped < batch_size: + msg = queue.popleft() + msgs.append((msg.key_id, msg.actor_message)) + popped += 1 + return msgs + + +class GcsAioNodeInfoSubscriber(_AioSubscriber): + def __init__( + self, + worker_id: bytes = None, + address: str = None, + channel: grpc.Channel = None, + ): + super().__init__(pubsub_pb2.GCS_NODE_INFO_CHANNEL, worker_id, address, channel) + + async def poll( + self, batch_size, timeout=None + ) -> List[Tuple[bytes, gcs_pb2.GcsNodeInfo]]: + """Polls for new node info message. + + Returns: + A list of tuples of (node_id, GcsNodeInfo). + """ + await self._poll(timeout=timeout) + return self._pop_node_infos(self._queue, batch_size=batch_size) + + @staticmethod + def _pop_node_infos(queue, batch_size): + if len(queue) == 0: + return [] + popped = 0 + msgs = [] + while len(queue) > 0 and popped < batch_size: + msg = queue.popleft() + msgs.append((msg.key_id, msg.node_info_message)) + popped += 1 + return msgs diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/gcs_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/gcs_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa9327209f68dc9bc0c3250484a68b231a4f07a5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/gcs_utils.py @@ -0,0 +1,156 @@ +import logging +from typing import Optional + +from ray._private import ray_constants +from ray.core.generated.common_pb2 import ErrorType, JobConfig +from ray.core.generated.gcs_pb2 import ( + ActorTableData, + AvailableResources, + ErrorTableData, + GcsEntry, + GcsNodeInfo, + JobTableData, + PlacementGroupTableData, + PubSubMessage, + ResourceDemand, + ResourceLoad, + ResourcesData, + ResourceUsageBatchData, + TablePrefix, + TablePubsub, + TaskEvents, + TotalResources, + WorkerTableData, +) + +logger = logging.getLogger(__name__) + +__all__ = [ + "ActorTableData", + "GcsNodeInfo", + "AvailableResources", + "TotalResources", + "JobTableData", + "JobConfig", + "ErrorTableData", + "ErrorType", + "GcsEntry", + "ResourceUsageBatchData", + "ResourcesData", + "TablePrefix", + "TablePubsub", + "TaskEvents", + "ResourceDemand", + "ResourceLoad", + "PubSubMessage", + "WorkerTableData", + "PlacementGroupTableData", +] + + +WORKER = 0 +DRIVER = 1 + +# Cap messages at 512MB +_MAX_MESSAGE_LENGTH = 512 * 1024 * 1024 +# Send keepalive every 60s +_GRPC_KEEPALIVE_TIME_MS = 60 * 1000 +# Keepalive should be replied < 60s +_GRPC_KEEPALIVE_TIMEOUT_MS = 60 * 1000 + +# Also relying on these defaults: +# grpc.keepalive_permit_without_calls=0: No keepalive without inflight calls. +# grpc.use_local_subchannel_pool=0: Subchannels are shared. +_GRPC_OPTIONS = [ + *ray_constants.GLOBAL_GRPC_OPTIONS, + ("grpc.max_send_message_length", _MAX_MESSAGE_LENGTH), + ("grpc.max_receive_message_length", _MAX_MESSAGE_LENGTH), + ("grpc.keepalive_time_ms", _GRPC_KEEPALIVE_TIME_MS), + ("grpc.keepalive_timeout_ms", _GRPC_KEEPALIVE_TIMEOUT_MS), +] + + +def create_gcs_channel(address: str, aio=False): + """Returns a GRPC channel to GCS. + + Args: + address: GCS address string, e.g. ip:port + aio: Whether using grpc.aio + Returns: + grpc.Channel or grpc.aio.Channel to GCS + """ + from ray._private.utils import init_grpc_channel + + return init_grpc_channel(address, options=_GRPC_OPTIONS, asynchronous=aio) + + +class GcsChannel: + def __init__(self, gcs_address: Optional[str] = None, aio: bool = False): + self._gcs_address = gcs_address + self._aio = aio + + @property + def address(self): + return self._gcs_address + + def connect(self): + # GCS server uses a cached port, so it should use the same port after + # restarting. This means GCS address should stay the same for the + # lifetime of the Ray cluster. + self._channel = create_gcs_channel(self._gcs_address, self._aio) + + def channel(self): + return self._channel + + +def cleanup_redis_storage( + host: str, + port: int, + password: str, + use_ssl: bool, + storage_namespace: str, + username: Optional[str] = None, +): + """This function is used to cleanup the storage. Before we having + a good design for storage backend, it can be used to delete the old + data. It support redis cluster and non cluster mode. + + Args: + host: The host address of the Redis. + port: The port of the Redis. + username: The username of the Redis. + password: The password of the Redis. + use_ssl: Whether to encrypt the connection. + storage_namespace: The namespace of the storage to be deleted. + """ + + from ray._raylet import del_key_prefix_from_storage # type: ignore + + if not isinstance(host, str): + raise ValueError("Host must be a string") + + if username is None: + username = "" + + if not isinstance(username, str): + raise ValueError("Username must be a string") + + if not isinstance(password, str): + raise ValueError("Password must be a string") + + if port < 0: + raise ValueError(f"Invalid port: {port}") + + if not isinstance(use_ssl, bool): + raise TypeError("use_ssl must be a boolean") + + if not isinstance(storage_namespace, str): + raise ValueError("storage namespace must be a string") + + # Right now, GCS stores all data into multiple hashes with keys prefixed by + # storage_namespace. So we only need to delete the specific key prefix to cleanup + # the cluster. + # Note this deletes all keys with prefix `RAY{key_prefix}@`, not `{key_prefix}`. + return del_key_prefix_from_storage( + host, port, username, password, use_ssl, storage_namespace + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/inspect_util.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/inspect_util.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae603f0160073a547131182556a3afff371390d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/inspect_util.py @@ -0,0 +1,49 @@ +import inspect + + +def is_cython(obj): + """Check if an object is a Cython function or method""" + + # TODO(suo): We could split these into two functions, one for Cython + # functions and another for Cython methods. + # TODO(suo): There doesn't appear to be a Cython function 'type' we can + # check against via isinstance. Please correct me if I'm wrong. + def check_cython(x): + return type(x).__name__ == "cython_function_or_method" + + # Check if function or method, respectively + return check_cython(obj) or ( + hasattr(obj, "__func__") and check_cython(obj.__func__) + ) + + +def is_function_or_method(obj): + """Check if an object is a function or method. + + Args: + obj: The Python object in question. + + Returns: + True if the object is an function or method. + """ + return inspect.isfunction(obj) or inspect.ismethod(obj) or is_cython(obj) + + +def is_class_method(f): + """Returns whether the given method is a class_method.""" + return hasattr(f, "__self__") and f.__self__ is not None + + +def is_static_method(cls, f_name): + """Returns whether the class has a static method with the given name. + + Args: + cls: The Python class (i.e. object of type `type`) to + search for the method in. + f_name: The name of the method to look up in this class + and check whether or not it is static. + """ + for base_cls in inspect.getmro(cls): + if f_name in base_cls.__dict__: + return isinstance(base_cls.__dict__[f_name], staticmethod) + return False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/internal_api.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/internal_api.py new file mode 100644 index 0000000000000000000000000000000000000000..f4efbde4db21d6f3239f9893e6d27981667f0e60 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/internal_api.py @@ -0,0 +1,255 @@ +from typing import List, Tuple + +import ray +import ray._private.profiling as profiling +import ray._private.services as services +import ray._private.utils as utils +import ray._private.worker +from ray._private.state import GlobalState +from ray._raylet import GcsClientOptions +from ray.core.generated import common_pb2 + +__all__ = ["free", "global_gc"] +MAX_MESSAGE_LENGTH = ray._config.max_grpc_message_size() + + +def global_gc(): + """Trigger gc.collect() on all workers in the cluster.""" + + worker = ray._private.worker.global_worker + worker.core_worker.global_gc() + + +def get_state_from_address(address=None): + address = services.canonicalize_bootstrap_address_or_die(address) + + state = GlobalState() + options = GcsClientOptions.create( + address, None, allow_cluster_id_nil=True, fetch_cluster_id_if_nil=False + ) + state._initialize_global_state(options) + return state + + +def memory_summary( + address=None, + group_by="NODE_ADDRESS", + sort_by="OBJECT_SIZE", + units="B", + line_wrap=True, + stats_only=False, + num_entries=None, +): + from ray.dashboard.memory_utils import memory_summary + + state = get_state_from_address(address) + reply = get_memory_info_reply(state) + + if stats_only: + return store_stats_summary(reply) + return memory_summary( + state, group_by, sort_by, line_wrap, units, num_entries + ) + store_stats_summary(reply) + + +def get_memory_info_reply(state, node_manager_address=None, node_manager_port=None): + """Returns global memory info.""" + + from ray.core.generated import node_manager_pb2, node_manager_pb2_grpc + + # We can ask any Raylet for the global memory info, that Raylet internally + # asks all nodes in the cluster for memory stats. + if node_manager_address is None or node_manager_port is None: + # We should ask for a raylet that is alive. + raylet = None + for node in state.node_table(): + if node["Alive"]: + raylet = node + break + assert raylet is not None, "Every raylet is dead" + raylet_address = "{}:{}".format( + raylet["NodeManagerAddress"], raylet["NodeManagerPort"] + ) + else: + raylet_address = "{}:{}".format(node_manager_address, node_manager_port) + + channel = utils.init_grpc_channel( + raylet_address, + options=[ + ("grpc.max_send_message_length", MAX_MESSAGE_LENGTH), + ("grpc.max_receive_message_length", MAX_MESSAGE_LENGTH), + ], + ) + + stub = node_manager_pb2_grpc.NodeManagerServiceStub(channel) + reply = stub.FormatGlobalMemoryInfo( + node_manager_pb2.FormatGlobalMemoryInfoRequest(include_memory_info=False), + timeout=60.0, + ) + return reply + + +def node_stats( + node_manager_address=None, node_manager_port=None, include_memory_info=True +): + """Returns NodeStats object describing memory usage in the cluster.""" + + from ray.core.generated import node_manager_pb2, node_manager_pb2_grpc + + # We can ask any Raylet for the global memory info. + assert node_manager_address is not None and node_manager_port is not None + raylet_address = "{}:{}".format(node_manager_address, node_manager_port) + channel = utils.init_grpc_channel( + raylet_address, + options=[ + ("grpc.max_send_message_length", MAX_MESSAGE_LENGTH), + ("grpc.max_receive_message_length", MAX_MESSAGE_LENGTH), + ], + ) + + stub = node_manager_pb2_grpc.NodeManagerServiceStub(channel) + node_stats = stub.GetNodeStats( + node_manager_pb2.GetNodeStatsRequest(include_memory_info=include_memory_info), + timeout=30.0, + ) + return node_stats + + +def store_stats_summary(reply): + """Returns formatted string describing object store stats in all nodes.""" + store_summary = "--- Aggregate object store stats across all nodes ---\n" + # TODO(ekl) it would be nice if we could provide a full memory usage + # breakdown by type (e.g., pinned by worker, primary, etc.) + store_summary += ( + "Plasma memory usage {} MiB, {} objects, {}% full, {}% " + "needed\n".format( + int(reply.store_stats.object_store_bytes_used / (1024 * 1024)), + reply.store_stats.num_local_objects, + round( + 100 + * reply.store_stats.object_store_bytes_used + / reply.store_stats.object_store_bytes_avail, + 2, + ), + round( + 100 + * reply.store_stats.object_store_bytes_primary_copy + / reply.store_stats.object_store_bytes_avail, + 2, + ), + ) + ) + if reply.store_stats.object_store_bytes_fallback > 0: + store_summary += "Plasma filesystem mmap usage: {} MiB\n".format( + int(reply.store_stats.object_store_bytes_fallback / (1024 * 1024)) + ) + if reply.store_stats.spill_time_total_s > 0: + store_summary += ( + "Spilled {} MiB, {} objects, avg write throughput {} MiB/s\n".format( + int(reply.store_stats.spilled_bytes_total / (1024 * 1024)), + reply.store_stats.spilled_objects_total, + int( + reply.store_stats.spilled_bytes_total + / (1024 * 1024) + / reply.store_stats.spill_time_total_s + ), + ) + ) + if reply.store_stats.restore_time_total_s > 0: + store_summary += ( + "Restored {} MiB, {} objects, avg read throughput {} MiB/s\n".format( + int(reply.store_stats.restored_bytes_total / (1024 * 1024)), + reply.store_stats.restored_objects_total, + int( + reply.store_stats.restored_bytes_total + / (1024 * 1024) + / reply.store_stats.restore_time_total_s + ), + ) + ) + if reply.store_stats.consumed_bytes > 0: + store_summary += "Objects consumed by Ray tasks: {} MiB.\n".format( + int(reply.store_stats.consumed_bytes / (1024 * 1024)) + ) + if reply.store_stats.object_pulls_queued: + store_summary += "Object fetches queued, waiting for available memory." + + return store_summary + + +def free(object_refs: list, local_only: bool = False): + """Free a list of IDs from the in-process and plasma object stores. + + This function is a low-level API which should be used in restricted + scenarios. + + If local_only is false, the request will be send to all object stores. + + This method will not return any value to indicate whether the deletion is + successful or not. This function is an instruction to the object store. If + some of the objects are in use, the object stores will delete them later + when the ref count is down to 0. + + Examples: + + .. testcode:: + + import ray + + @ray.remote + def f(): + return 0 + + obj_ref = f.remote() + ray.get(obj_ref) # wait for object to be created first + free([obj_ref]) # unpin & delete object globally + + Args: + object_refs (List[ObjectRef]): List of object refs to delete. + local_only: Whether only deleting the list of objects in local + object store or all object stores. + """ + worker = ray._private.worker.global_worker + + if isinstance(object_refs, ray.ObjectRef): + object_refs = [object_refs] + + if not isinstance(object_refs, list): + raise TypeError( + "free() expects a list of ObjectRef, got {}".format(type(object_refs)) + ) + + # Make sure that the values are object refs. + for object_ref in object_refs: + if not isinstance(object_ref, ray.ObjectRef): + raise TypeError( + "Attempting to call `free` on the value {}, " + "which is not an ray.ObjectRef.".format(object_ref) + ) + + worker.check_connected() + with profiling.profile("ray.free"): + if len(object_refs) == 0: + return + + worker.core_worker.free_objects(object_refs, local_only) + + +def get_local_ongoing_lineage_reconstruction_tasks() -> List[ + Tuple[common_pb2.LineageReconstructionTask, int] +]: + """Return the locally submitted ongoing retry tasks + triggered by lineage reconstruction. + + NOTE: for the lineage reconstruction task status, + this method only returns the status known to the submitter + (i.e. it returns SUBMITTED_TO_WORKER instead of RUNNING). + + The return type is a list of pairs where pair.first is the + lineage reconstruction task info and pair.second is the number + of ongoing lineage reconstruction tasks of this type. + """ + + worker = ray._private.worker.global_worker + worker.check_connected() + return worker.core_worker.get_local_ongoing_lineage_reconstruction_tasks() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/label_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/label_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6ca9c5ec105223240849e714fa3f74f6390ff685 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/label_utils.py @@ -0,0 +1,191 @@ +import json +import re +from typing import ( + Dict, + Optional, +) + +import yaml + +import ray._private.ray_constants as ray_constants + +# Regex patterns used to validate that labels conform to Kubernetes label syntax rules. +# https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#syntax-and-character-set + +# Regex for mandatory name (DNS label) or value +# Examples: +# Valid matches: "a", "label-name", "a-._b", "123", "this_is_a_valid_label" +# Invalid matches: "-abc", "abc-", "my@label" +LABEL_REGEX = re.compile(r"([a-zA-Z0-9]([a-zA-Z0-9_.-]{0,61}[a-zA-Z0-9])?)") + +# Regex for optional prefix (DNS subdomain) +# Examples: +# Valid matches: "abc", "sub.domain.example", "my-label", "123.456.789" +# Invalid matches: "-abc", "prefix_", "sub..domain", sub.$$.example +LABEL_PREFIX_REGEX = rf"^({LABEL_REGEX.pattern}?(\.{LABEL_REGEX.pattern}?)*)$" + +# Supported operators for label selector conditions. Not (!) conditions are handled separately. +LABEL_OPERATORS = {"in"} +# Create a pattern string dynamically based on the LABEL_OPERATORS +OPERATOR_PATTERN = "|".join([re.escape(operator) for operator in LABEL_OPERATORS]) + +# Regex to match valid label selector operators and values +# Examples: +# Valid matches: "spot", "!GPU", "213521", "in(A123, B456, C789)", "!in(spot, on-demand)", "valid-value" +# Invalid matches: "-spot", "spot_", "in()", "in(spot,", "in(H100, TPU!GPU)", "!!!in(H100, TPU)" +LABEL_SELECTOR_REGEX = re.compile( + rf"^!?(?:{OPERATOR_PATTERN})?\({LABEL_REGEX.pattern}(?:, ?{LABEL_REGEX.pattern})*\)$|^!?{LABEL_REGEX.pattern}$" +) + + +def parse_node_labels_json(labels_json: str) -> Dict[str, str]: + labels = json.loads(labels_json) + if not isinstance(labels, dict): + raise ValueError("The format after deserialization is not a key-value pair map") + for key, value in labels.items(): + if not isinstance(key, str): + raise ValueError("The key is not string type.") + if not isinstance(value, str): + raise ValueError(f'The value of the "{key}" is not string type') + + # Validate parsed custom node labels don't begin with ray.io prefix + validate_node_labels(labels) + + return labels + + +def parse_node_labels_string(labels_str: str) -> Dict[str, str]: + labels = {} + + # Remove surrounding quotes if they exist + if len(labels_str) > 1 and labels_str.startswith('"') and labels_str.endswith('"'): + labels_str = labels_str[1:-1] + + if labels_str == "": + return labels + + # Labels argument should consist of a string of key=value pairs + # separated by commas. Labels follow Kubernetes label syntax. + label_pairs = labels_str.split(",") + for pair in label_pairs: + # Split each pair by `=` + key_value = pair.split("=") + if len(key_value) != 2: + raise ValueError("Label string is not a key-value pair.") + key = key_value[0].strip() + value = key_value[1].strip() + labels[key] = value + + # Validate parsed node labels follow expected Kubernetes label syntax + validate_node_label_syntax(labels) + + return labels + + +def parse_node_labels_from_yaml_file(path: str) -> Dict[str, str]: + if path == "": + return {} + with open(path, "r") as file: + # Expects valid YAML content + labels = yaml.safe_load(file) + if not isinstance(labels, dict): + raise ValueError( + "The format after deserialization is not a key-value pair map." + ) + for key, value in labels.items(): + if not isinstance(key, str): + raise ValueError("The key is not string type.") + if not isinstance(value, str): + raise ValueError(f'The value of "{key}" is not string type.') + + # Validate parsed node labels follow expected Kubernetes label syntax + validate_node_label_syntax(labels) + + return labels + + +# TODO (ryanaoleary@): This function will be removed after the migration to the label +# selector API from NodeLabelSchedulingPolicy is complete. +def validate_node_labels(labels: Dict[str, str]): + if labels is None: + return + for key in labels.keys(): + if key.startswith(ray_constants.RAY_DEFAULT_LABEL_KEYS_PREFIX): + raise ValueError( + f"Custom label keys `{key}` cannot start with the prefix " + f"`{ray_constants.RAY_DEFAULT_LABEL_KEYS_PREFIX}`. " + f"This is reserved for Ray defined labels." + ) + + +def validate_label_key(key: str) -> Optional[str]: + if "/" in key: + prefix, name = key.rsplit("/", 1) + if len(prefix) > 253 or not re.fullmatch(LABEL_PREFIX_REGEX, prefix): + return str( + f"Invalid label key prefix `{prefix}`. Prefix must be a series of DNS labels " + f"separated by dots (.), not longer than 253 characters in total." + ) + else: + name = key + if len(name) > 63 or not re.fullmatch(LABEL_REGEX, name): + return str( + f"Invalid label key name `{name}`. Name must be 63 chars or less beginning and ending " + f"with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_)," + f"dots (.), and alphanumerics between." + ) + return None + + +def validate_label_value(value: str): + if value == "": + return + if len(value) > 63 or not re.fullmatch(LABEL_REGEX, value): + raise ValueError( + f"Invalid label key value `{value}`. Value must be 63 chars or less beginning and ending " + f"with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_)," + f"dots (.), and alphanumerics between." + ) + + +def validate_label_selector(label_selector: Optional[Dict[str, str]]) -> Optional[str]: + if label_selector is None: + return None + + for key, value in label_selector.items(): + possible_error_message = validate_label_key(key) + if possible_error_message: + return possible_error_message + if value is not None: + possible_error_message = validate_label_selector_value(value) + if possible_error_message: + return possible_error_message + + return None + + +def validate_label_selector_value(selector: str) -> Optional[str]: + if selector == "": + return None + if not re.fullmatch(LABEL_SELECTOR_REGEX, selector): + return str( + f"Invalid label selector value `{selector}`. The label selector value should contain optional operators and a label value. Supported operators are: ! and {LABEL_OPERATORS}. " + f"Value must be 63 chars or less beginning and ending " + f"with an alphanumeric character ([a-z0-9A-Z]) with dashes (-), underscores (_)," + f"dots (.), and alphanumerics between." + ) + + return None + + +# TODO (ryanaoleary@): This function will replace `validate_node_labels` after +# the migration from NodeLabelSchedulingPolicy to the Label Selector API is complete. +def validate_node_label_syntax(labels: Dict[str, str]): + if labels is None: + return + for key, value in labels.items(): + possible_error_message = validate_label_key(key) + if possible_error_message: + raise ValueError(possible_error_message) + if value is not None: + validate_label_value(value) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/log.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/log.py new file mode 100644 index 0000000000000000000000000000000000000000..3b4cf2d7eeef818f4c9b1844a2b883ff055088b9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/log.py @@ -0,0 +1,117 @@ +import logging +import threading +import time +from typing import Union + +INTERNAL_TIMESTAMP_LOG_KEY = "_ray_timestamp_ns" + + +def _print_loggers(): + """Print a formatted list of loggers and their handlers for debugging.""" + loggers = {logging.root.name: logging.root} + loggers.update(dict(sorted(logging.root.manager.loggerDict.items()))) + for name, logger in loggers.items(): + if isinstance(logger, logging.Logger): + print(f" {name}: disabled={logger.disabled}, propagate={logger.propagate}") + for handler in logger.handlers: + print(f" {handler}") + + +def clear_logger(logger: Union[str, logging.Logger]): + """Reset a logger, clearing its handlers and enabling propagation. + + Args: + logger: Logger to be cleared + """ + if isinstance(logger, str): + logger = logging.getLogger(logger) + logger.propagate = True + logger.handlers.clear() + + +class PlainRayHandler(logging.StreamHandler): + """A plain log handler. + + This handler writes to whatever sys.stderr points to at emit-time, + not at instantiation time. See docs for logging._StderrHandler. + """ + + def __init__(self): + super().__init__() + self.plain_handler = logging._StderrHandler() + self.plain_handler.level = self.level + self.plain_handler.formatter = logging.Formatter(fmt="%(message)s") + + def emit(self, record: logging.LogRecord): + """Emit the log message. + + If this is a worker, bypass fancy logging and just emit the log record. + If this is the driver, emit the message using the appropriate console handler. + + Args: + record: Log record to be emitted + """ + import ray + + if ( + hasattr(ray, "_private") + and hasattr(ray._private, "worker") + and ray._private.worker.global_worker.mode + == ray._private.worker.WORKER_MODE + ): + self.plain_handler.emit(record) + else: + logging._StderrHandler.emit(self, record) + + +logger_initialized = False +logging_config_lock = threading.Lock() + + +def _setup_log_record_factory(): + """Setup log record factory to add _ray_timestamp_ns to LogRecord.""" + old_factory = logging.getLogRecordFactory() + + def record_factory(*args, **kwargs): + record = old_factory(*args, **kwargs) + # Python logging module starts to use `time.time_ns()` to generate `created` + # from Python 3.13 to avoid the precision loss caused by the float type. + # Here, we generate the `created` for the LogRecord to support older Python + # versions. + ct = time.time_ns() + record.created = ct / 1e9 + + record.__dict__[INTERNAL_TIMESTAMP_LOG_KEY] = ct + + return record + + logging.setLogRecordFactory(record_factory) + + +def generate_logging_config(): + """Generate the default Ray logging configuration.""" + with logging_config_lock: + global logger_initialized + if logger_initialized: + return + logger_initialized = True + + plain_formatter = logging.Formatter( + "%(asctime)s\t%(levelname)s %(filename)s:%(lineno)s -- %(message)s" + ) + + default_handler = PlainRayHandler() + default_handler.setFormatter(plain_formatter) + + ray_logger = logging.getLogger("ray") + ray_logger.setLevel(logging.INFO) + ray_logger.addHandler(default_handler) + ray_logger.propagate = False + + # Special handling for ray.rllib: only warning-level messages passed through + # See https://github.com/ray-project/ray/pull/31858 for related PR + rllib_logger = logging.getLogger("ray.rllib") + rllib_logger.setLevel(logging.WARN) + + # Set up the LogRecord factory. + _setup_log_record_factory() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/log_monitor.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/log_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..6232d675deeeb3b35a3323b68b59070a52c81e33 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/log_monitor.py @@ -0,0 +1,612 @@ +import argparse +import errno +import glob +import logging +import logging.handlers +import os +import platform +import re +import shutil +import sys +import time +import traceback +from typing import Callable, List, Optional, Set + +import ray._private.ray_constants as ray_constants +import ray._private.services as services +import ray._private.utils +from ray._private import logging_utils +from ray._private.ray_logging import setup_component_logger +from ray._raylet import GcsClient + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) + +# The groups are job id, and pid. +WORKER_LOG_PATTERN = re.compile(r".*worker.*-([0-9a-f]+)-(\d+)") +# The groups are job id. +RUNTIME_ENV_SETUP_PATTERN = re.compile(r".*runtime_env_setup-(\d+).log") +# Log name update interval under pressure. +# We need it because log name update is CPU intensive and uses 100% +# of cpu when there are many log files. +LOG_NAME_UPDATE_INTERVAL_S = float(os.getenv("LOG_NAME_UPDATE_INTERVAL_S", 0.5)) +# Once there are more files than this threshold, +# log monitor start giving backpressure to lower cpu usages. +RAY_LOG_MONITOR_MANY_FILES_THRESHOLD = int( + os.getenv("RAY_LOG_MONITOR_MANY_FILES_THRESHOLD", 1000) +) +RAY_RUNTIME_ENV_LOG_TO_DRIVER_ENABLED = int( + os.getenv("RAY_RUNTIME_ENV_LOG_TO_DRIVER_ENABLED", 0) +) + + +class LogFileInfo: + def __init__( + self, + filename=None, + size_when_last_opened=None, + file_position=None, + file_handle=None, + is_err_file=False, + job_id=None, + worker_pid=None, + ): + assert ( + filename is not None + and size_when_last_opened is not None + and file_position is not None + ) + self.filename = filename + self.size_when_last_opened = size_when_last_opened + self.file_position = file_position + self.file_handle = file_handle + self.is_err_file = is_err_file + self.job_id = job_id + self.worker_pid = worker_pid + self.actor_name = None + self.task_name = None + + def reopen_if_necessary(self): + """Check if the file's inode has changed and reopen it if necessary. + There are a variety of reasons what we would logically consider a file + would have different inodes, such as log rotation or file syncing + semantics. + """ + try: + open_inode = None + if self.file_handle and not self.file_handle.closed: + open_inode = os.fstat(self.file_handle.fileno()).st_ino + + new_inode = os.stat(self.filename).st_ino + if open_inode != new_inode: + self.file_handle = open(self.filename, "rb") + self.file_handle.seek(self.file_position) + except Exception: + logger.debug(f"file no longer exists, skip re-opening of {self.filename}") + + def __repr__(self): + return ( + "FileInfo(\n" + f"\tfilename: {self.filename}\n" + f"\tsize_when_last_opened: {self.size_when_last_opened}\n" + f"\tfile_position: {self.file_position}\n" + f"\tfile_handle: {self.file_handle}\n" + f"\tis_err_file: {self.is_err_file}\n" + f"\tjob_id: {self.job_id}\n" + f"\tworker_pid: {self.worker_pid}\n" + f"\tactor_name: {self.actor_name}\n" + f"\ttask_name: {self.task_name}\n" + ")" + ) + + +class LogMonitor: + """A monitor process for monitoring Ray log files. + + This class maintains a list of open files and a list of closed log files. We + can't simply leave all files open because we'll run out of file + descriptors. + + The "run" method of this class will cycle between doing several things: + 1. First, it will check if any new files have appeared in the log + directory. If so, they will be added to the list of closed files. + 2. Then, if we are unable to open any new files, we will close all of the + files. + 3. Then, we will open as many closed files as we can that may have new + lines (judged by an increase in file size since the last time the file + was opened). + 4. Then we will loop through the open files and see if there are any new + lines in the file. If so, we will publish them to Ray pubsub. + + Attributes: + ip: The hostname of this machine, for grouping log messages. + logs_dir: The directory that the log files are in. + log_filenames: This is the set of filenames of all files in + open_file_infos and closed_file_infos. + open_file_infos (list[LogFileInfo]): Info for all of the open files. + closed_file_infos (list[LogFileInfo]): Info for all of the closed + files. + can_open_more_files: True if we can still open more files and + false otherwise. + max_files_open: The maximum number of files that can be open. + """ + + def __init__( + self, + node_ip_address: str, + logs_dir: str, + gcs_client: GcsClient, + is_proc_alive_fn: Callable[[int], bool], + max_files_open: int = ray_constants.LOG_MONITOR_MAX_OPEN_FILES, + gcs_address: Optional[str] = None, + ): + """Initialize the log monitor object.""" + self.ip: str = node_ip_address + self.logs_dir: str = logs_dir + self.gcs_client = gcs_client + self.log_filenames: Set[str] = set() + self.open_file_infos: List[LogFileInfo] = [] + self.closed_file_infos: List[LogFileInfo] = [] + self.can_open_more_files: bool = True + self.max_files_open: int = max_files_open + self.is_proc_alive_fn: Callable[[int], bool] = is_proc_alive_fn + self.is_autoscaler_v2: bool = self.get_is_autoscaler_v2(gcs_address) + + logger.info( + f"Starting log monitor with [max open files={max_files_open}]," + f" [is_autoscaler_v2={self.is_autoscaler_v2}]" + ) + + def get_is_autoscaler_v2(self, gcs_address: Optional[str]) -> bool: + """Check if autoscaler v2 is enabled.""" + if gcs_address is None: + return False + + if not ray.experimental.internal_kv._internal_kv_initialized(): + ray.experimental.internal_kv._initialize_internal_kv(self.gcs_client) + from ray.autoscaler.v2.utils import is_autoscaler_v2 + + return is_autoscaler_v2() + + def _close_all_files(self): + """Close all open files (so that we can open more).""" + while len(self.open_file_infos) > 0: + file_info = self.open_file_infos.pop(0) + file_info.file_handle.close() + file_info.file_handle = None + + proc_alive = True + # Test if the worker process that generated the log file + # is still alive. Only applies to worker processes. + # For all other system components, we always assume they are alive. + if ( + file_info.worker_pid != "raylet" + and file_info.worker_pid != "gcs_server" + and file_info.worker_pid != "autoscaler" + and file_info.worker_pid != "runtime_env" + and file_info.worker_pid is not None + ): + assert not isinstance(file_info.worker_pid, str), ( + "PID should be an int type. " f"Given PID: {file_info.worker_pid}." + ) + proc_alive = self.is_proc_alive_fn(file_info.worker_pid) + if not proc_alive: + # The process is not alive any more, so move the log file + # out of the log directory so glob.glob will not be slowed + # by it. + target = os.path.join( + self.logs_dir, "old", os.path.basename(file_info.filename) + ) + try: + shutil.move(file_info.filename, target) + except (IOError, OSError) as e: + if e.errno == errno.ENOENT: + logger.warning( + f"Warning: The file {file_info.filename} was not found." + ) + else: + raise e + + if proc_alive: + self.closed_file_infos.append(file_info) + + self.can_open_more_files = True + + def update_log_filenames(self): + """Update the list of log files to monitor.""" + monitor_log_paths = [] + # output of user code is written here + monitor_log_paths += glob.glob( + f"{self.logs_dir}/worker*[.out|.err]" + ) + glob.glob(f"{self.logs_dir}/java-worker*.log") + # segfaults and other serious errors are logged here + monitor_log_paths += glob.glob(f"{self.logs_dir}/raylet*.err") + # monitor logs are needed to report autoscaler events + # TODO(rickyx): remove this after migration. + if not self.is_autoscaler_v2: + # We publish monitor logs in autoscaler v1 + monitor_log_paths += glob.glob(f"{self.logs_dir}/monitor.log") + else: + # We publish autoscaler events directly in autoscaler v2 + monitor_log_paths += glob.glob( + f"{self.logs_dir}/events/event_AUTOSCALER.log" + ) + + # If gcs server restarts, there can be multiple log files. + monitor_log_paths += glob.glob(f"{self.logs_dir}/gcs_server*.err") + + # Add libtpu logs if they exist in the Ray container. + tpu_log_dir = f"{self.logs_dir}/tpu_logs" + if os.path.isdir(tpu_log_dir): + monitor_log_paths += glob.glob(f"{self.logs_dir}/tpu_logs/**") + + # runtime_env setup process is logged here + if RAY_RUNTIME_ENV_LOG_TO_DRIVER_ENABLED: + monitor_log_paths += glob.glob(f"{self.logs_dir}/runtime_env*.log") + for file_path in monitor_log_paths: + if os.path.isfile(file_path) and file_path not in self.log_filenames: + worker_match = WORKER_LOG_PATTERN.match(file_path) + if worker_match: + worker_pid = int(worker_match.group(2)) + else: + worker_pid = None + job_id = None + + # Perform existence check first because most file will not be + # including runtime_env. This saves some cpu cycle. + if "runtime_env" in file_path: + runtime_env_job_match = RUNTIME_ENV_SETUP_PATTERN.match(file_path) + if runtime_env_job_match: + job_id = runtime_env_job_match.group(1) + + is_err_file = file_path.endswith("err") + + self.log_filenames.add(file_path) + self.closed_file_infos.append( + LogFileInfo( + filename=file_path, + size_when_last_opened=0, + file_position=0, + file_handle=None, + is_err_file=is_err_file, + job_id=job_id, + worker_pid=worker_pid, + ) + ) + log_filename = os.path.basename(file_path) + logger.info(f"Beginning to track file {log_filename}") + + def open_closed_files(self): + """Open some closed files if they may have new lines. + + Opening more files may require us to close some of the already open + files. + """ + if not self.can_open_more_files: + # If we can't open any more files. Close all of the files. + self._close_all_files() + + files_with_no_updates = [] + while len(self.closed_file_infos) > 0: + if len(self.open_file_infos) >= self.max_files_open: + self.can_open_more_files = False + break + + file_info = self.closed_file_infos.pop(0) + assert file_info.file_handle is None + # Get the file size to see if it has gotten bigger since we last + # opened it. + try: + file_size = os.path.getsize(file_info.filename) + except (IOError, OSError) as e: + # Catch "file not found" errors. + if e.errno == errno.ENOENT: + logger.warning( + f"Warning: The file {file_info.filename} was not found." + ) + self.log_filenames.remove(file_info.filename) + continue + raise e + + # If some new lines have been added to this file, try to reopen the + # file. + if file_size > file_info.size_when_last_opened: + try: + f = open(file_info.filename, "rb") + except (IOError, OSError) as e: + if e.errno == errno.ENOENT: + logger.warning( + f"Warning: The file {file_info.filename} was not found." + ) + self.log_filenames.remove(file_info.filename) + continue + else: + raise e + + f.seek(file_info.file_position) + file_info.size_when_last_opened = file_size + file_info.file_handle = f + self.open_file_infos.append(file_info) + else: + files_with_no_updates.append(file_info) + + if len(self.open_file_infos) >= self.max_files_open: + self.can_open_more_files = False + # Add the files with no changes back to the list of closed files. + self.closed_file_infos += files_with_no_updates + + def check_log_files_and_publish_updates(self): + """Gets updates to the log files and publishes them. + + Returns: + True if anything was published and false otherwise. + """ + anything_published = False + lines_to_publish = [] + + def flush(): + nonlocal lines_to_publish + nonlocal anything_published + if len(lines_to_publish) > 0: + data = { + "ip": self.ip, + "pid": file_info.worker_pid, + "job": file_info.job_id, + "is_err": file_info.is_err_file, + "lines": lines_to_publish, + "actor_name": file_info.actor_name, + "task_name": file_info.task_name, + } + try: + self.gcs_client.publish_logs(data) + except Exception: + logger.exception(f"Failed to publish log messages {data}") + anything_published = True + lines_to_publish = [] + + for file_info in self.open_file_infos: + assert not file_info.file_handle.closed + file_info.reopen_if_necessary() + + max_num_lines_to_read = ray_constants.LOG_MONITOR_NUM_LINES_TO_READ + for _ in range(max_num_lines_to_read): + try: + next_line = file_info.file_handle.readline() + # Replace any characters not in UTF-8 with + # a replacement character, see + # https://stackoverflow.com/a/38565489/10891801 + next_line = next_line.decode("utf-8", "replace") + if next_line == "": + break + next_line = next_line.rstrip("\r\n") + + if next_line.startswith(ray_constants.LOG_PREFIX_ACTOR_NAME): + flush() # Possible change of task/actor name. + file_info.actor_name = next_line.split( + ray_constants.LOG_PREFIX_ACTOR_NAME, 1 + )[1] + file_info.task_name = None + elif next_line.startswith(ray_constants.LOG_PREFIX_TASK_NAME): + flush() # Possible change of task/actor name. + file_info.task_name = next_line.split( + ray_constants.LOG_PREFIX_TASK_NAME, 1 + )[1] + elif next_line.startswith(ray_constants.LOG_PREFIX_JOB_ID): + file_info.job_id = next_line.split( + ray_constants.LOG_PREFIX_JOB_ID, 1 + )[1] + elif next_line.startswith( + "Windows fatal exception: access violation" + ): + # We are suppressing the + # 'Windows fatal exception: access violation' + # message on workers on Windows here. + # As far as we know it is harmless, + # but is frequently popping up if Python + # functions are run inside the core + # worker C extension. See the investigation in + # github.com/ray-project/ray/issues/18944 + # Also skip the following line, which is an + # empty line. + file_info.file_handle.readline() + else: + lines_to_publish.append(next_line) + except Exception: + logger.error( + f"Error: Reading file: {file_info.filename}, " + f"position: {file_info.file_info.file_handle.tell()} " + "failed." + ) + raise + + if file_info.file_position == 0: + # make filename windows-agnostic + filename = file_info.filename.replace("\\", "/") + if "/raylet" in filename: + file_info.worker_pid = "raylet" + elif "/gcs_server" in filename: + file_info.worker_pid = "gcs_server" + elif "/monitor" in filename or "event_AUTOSCALER" in filename: + file_info.worker_pid = "autoscaler" + elif "/runtime_env" in filename: + file_info.worker_pid = "runtime_env" + + # Record the current position in the file. + file_info.file_position = file_info.file_handle.tell() + flush() + + return anything_published + + def should_update_filenames(self, last_file_updated_time: float) -> bool: + """Return true if filenames should be updated. + + This method is used to apply the backpressure on file updates because + that requires heavy glob operations which use lots of CPUs. + + Args: + last_file_updated_time: The last time filenames are updated. + + Returns: + True if filenames should be updated. False otherwise. + """ + elapsed_seconds = float(time.time() - last_file_updated_time) + return ( + len(self.log_filenames) < RAY_LOG_MONITOR_MANY_FILES_THRESHOLD + or elapsed_seconds > LOG_NAME_UPDATE_INTERVAL_S + ) + + def run(self): + """Run the log monitor. + + This will scan the file system once every LOG_NAME_UPDATE_INTERVAL_S to + check if there are new log files to monitor. It will also publish new + log lines. + """ + last_updated = time.time() + while True: + if self.should_update_filenames(last_updated): + self.update_log_filenames() + last_updated = time.time() + + self.open_closed_files() + anything_published = self.check_log_files_and_publish_updates() + # If nothing was published, then wait a little bit before checking + # for logs to avoid using too much CPU. + if not anything_published: + time.sleep(0.1) + + +def is_proc_alive(pid): + # Import locally to make sure the bundled version is used if needed + import psutil + + try: + return psutil.Process(pid).is_running() + except psutil.NoSuchProcess: + # The process does not exist. + return False + + +if __name__ == "__main__": + parser = argparse.ArgumentParser( + description=("Parse GCS server address for the log monitor to connect to.") + ) + parser.add_argument( + "--gcs-address", required=False, type=str, help="The address (ip:port) of GCS." + ) + parser.add_argument( + "--logging-level", + required=False, + type=str, + default=ray_constants.LOGGER_LEVEL, + choices=ray_constants.LOGGER_LEVEL_CHOICES, + help=ray_constants.LOGGER_LEVEL_HELP, + ) + parser.add_argument( + "--logging-format", + required=False, + type=str, + default=ray_constants.LOGGER_FORMAT, + help=ray_constants.LOGGER_FORMAT_HELP, + ) + parser.add_argument( + "--logging-filename", + required=False, + type=str, + default=ray_constants.LOG_MONITOR_LOG_FILE_NAME, + help="Specify the name of log file, " + "log to stderr if set empty, default is " + f'"{ray_constants.LOG_MONITOR_LOG_FILE_NAME}"', + ) + parser.add_argument( + "--session-dir", + required=True, + type=str, + help="Specify the path of the session directory used by Ray processes.", + ) + parser.add_argument( + "--logs-dir", + required=True, + type=str, + help="Specify the path of the log directory used by Ray processes.", + ) + parser.add_argument( + "--logging-rotate-bytes", + required=True, + type=int, + help="Specify the max bytes for rotating log file.", + ) + parser.add_argument( + "--logging-rotate-backup-count", + required=True, + type=int, + help="Specify the backup count of rotated log file.", + ) + parser.add_argument( + "--stdout-filepath", + required=False, + default="", + type=str, + help="The filepath to dump log monitor stdout.", + ) + parser.add_argument( + "--stderr-filepath", + required=False, + default="", + type=str, + help="The filepath to dump log monitor stderr.", + ) + + args = parser.parse_args() + + # Disable log rotation for windows platform. + logging_rotation_bytes = args.logging_rotate_bytes if sys.platform != "win32" else 0 + logging_rotation_backup_count = ( + args.logging_rotate_backup_count if sys.platform != "win32" else 1 + ) + logging_params = dict( + logging_level=args.logging_level, + logging_format=args.logging_format, + log_dir=args.logs_dir, + filename=args.logging_filename, + max_bytes=logging_rotation_bytes, + backup_count=logging_rotation_backup_count, + ) + logger = setup_component_logger(**logging_params) + + # Setup stdout/stderr redirect files if redirection enabled + logging_utils.redirect_stdout_stderr_if_needed( + args.stdout_filepath, + args.stderr_filepath, + logging_rotation_bytes, + logging_rotation_backup_count, + ) + + node_ip = services.get_cached_node_ip_address(args.session_dir) + gcs_client = GcsClient(address=args.gcs_address) + log_monitor = LogMonitor( + node_ip, + args.logs_dir, + gcs_client, + is_proc_alive, + gcs_address=args.gcs_address, + ) + + try: + log_monitor.run() + except Exception as e: + # Something went wrong, so push an error to all drivers. + traceback_str = ray._private.utils.format_error_message(traceback.format_exc()) + message = ( + f"The log monitor on node {platform.node()} " + f"failed with the following error:\n{traceback_str}" + ) + ray._private.utils.publish_error_to_driver( + ray_constants.LOG_MONITOR_DIED_ERROR, + message, + gcs_client=gcs_client, + ) + logger.error(message) + raise e diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/logging_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/logging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..21566f87c5ea1a479b0163fdfbc1b67324b7c50a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/logging_utils.py @@ -0,0 +1,49 @@ +import sys + +from ray._private.utils import open_log +from ray._raylet import StreamRedirector + + +def redirect_stdout_stderr_if_needed( + stdout_filepath: str, + stderr_filepath: str, + rotation_bytes: int, + rotation_backup_count: int, +): + """This function sets up redirection for stdout and stderr if needed, based on the given rotation parameters. + + params: + stdout_filepath: the filepath stdout will be redirected to; if empty, stdout will not be redirected. + stderr_filepath: the filepath stderr will be redirected to; if empty, stderr will not be redirected. + rotation_bytes: number of bytes which triggers file rotation. + rotation_backup_count: the max size of rotation files. + """ + + # Setup redirection for stdout and stderr. + if stdout_filepath: + StreamRedirector.redirect_stdout( + stdout_filepath, + rotation_bytes, + rotation_backup_count, + False, # tee_to_stdout + False, # tee_to_stderr + ) + if stderr_filepath: + StreamRedirector.redirect_stderr( + stderr_filepath, + rotation_bytes, + rotation_backup_count, + False, # tee_to_stdout + False, # tee_to_stderr + ) + + # Setup python system stdout/stderr. + stdout_fileno = sys.stdout.fileno() + stderr_fileno = sys.stderr.fileno() + # We also manually set sys.stdout and sys.stderr because that seems to + # have an effect on the output buffering. Without doing this, stdout + # and stderr are heavily buffered resulting in seemingly lost logging + # statements. We never want to close the stdout file descriptor, dup2 will + # close it when necessary and we don't want python's GC to close it. + sys.stdout = open_log(stdout_fileno, unbuffered=True, closefd=False) + sys.stderr = open_log(stderr_fileno, unbuffered=True, closefd=False) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/memory_monitor.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/memory_monitor.py new file mode 100644 index 0000000000000000000000000000000000000000..fd3880c9d50441e775d2227c33ba723ac8584771 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/memory_monitor.py @@ -0,0 +1,165 @@ +import logging +import os +import platform +import sys +import time + +import ray # noqa F401 + +# Import ray before psutil will make sure we use psutil's bundled version +from ray._common.utils import get_system_memory + +import psutil # noqa E402 + +logger = logging.getLogger(__name__) + + +def get_rss(memory_info): + """Get the estimated non-shared memory usage from psutil memory_info.""" + mem = memory_info.rss + # OSX doesn't have the shared attribute + if hasattr(memory_info, "shared"): + mem -= memory_info.shared + return mem + + +def get_shared(virtual_memory): + """Get the estimated shared memory usage from psutil virtual mem info.""" + # OSX doesn't have the shared attribute + if hasattr(virtual_memory, "shared"): + return virtual_memory.shared + else: + return 0 + + +def get_top_n_memory_usage(n: int = 10): + """Get the top n memory usage of the process + + Params: + n: Number of top n process memory usage to return. + Returns: + (str) The formatted string of top n process memory usage. + """ + proc_stats = [] + for proc in psutil.process_iter(["memory_info", "cmdline"]): + try: + proc_stats.append( + (get_rss(proc.info["memory_info"]), proc.pid, proc.info["cmdline"]) + ) + except psutil.NoSuchProcess: + # We should skip the process that has exited. Refer this + # issue for more detail: + # https://github.com/ray-project/ray/issues/14929 + continue + except psutil.AccessDenied: + # On MacOS, the proc_pidinfo call (used to get per-process + # memory info) fails with a permission denied error when used + # on a process that isn’t owned by the same user. For now, we + # drop the memory info of any such process, assuming that + # processes owned by other users (e.g. root) aren't Ray + # processes and will be of less interest when an OOM happens + # on a Ray node. + # See issue for more detail: + # https://github.com/ray-project/ray/issues/11845#issuecomment-849904019 # noqa: E501 + continue + proc_str = "PID\tMEM\tCOMMAND" + for rss, pid, cmdline in sorted(proc_stats, reverse=True)[:n]: + proc_str += "\n{}\t{}GiB\t{}".format( + pid, round(rss / (1024**3), 2), " ".join(cmdline)[:100].strip() + ) + return proc_str + + +class RayOutOfMemoryError(Exception): + def __init__(self, msg): + Exception.__init__(self, msg) + + @staticmethod + def get_message(used_gb, total_gb, threshold): + proc_str = get_top_n_memory_usage(n=10) + return ( + "More than {}% of the memory on ".format(int(100 * threshold)) + + "node {} is used ({} / {} GB). ".format( + platform.node(), round(used_gb, 2), round(total_gb, 2) + ) + + f"The top 10 memory consumers are:\n\n{proc_str}" + + "\n\nIn addition, up to {} GiB of shared memory is ".format( + round(get_shared(psutil.virtual_memory()) / (1024**3), 2) + ) + + "currently being used by the Ray object store.\n---\n" + "--- Tip: Use the `ray memory` command to list active " + "objects in the cluster.\n" + "--- To disable OOM exceptions, set " + "RAY_DISABLE_MEMORY_MONITOR=1.\n---\n" + ) + + +class MemoryMonitor: + """Helper class for raising errors on low memory. + + This presents a much cleaner error message to users than what would happen + if we actually ran out of memory. + + The monitor tries to use the cgroup memory limit and usage if it is set + and available so that it is more reasonable inside containers. Otherwise, + it uses `psutil` to check the memory usage. + + The environment variable `RAY_MEMORY_MONITOR_ERROR_THRESHOLD` can be used + to overwrite the default error_threshold setting. + + Used by test only. For production code use memory_monitor.cc + """ + + def __init__(self, error_threshold=0.95, check_interval=1): + # Note: it takes ~50us to check the memory usage through psutil, so + # throttle this check at most once a second or so. + self.check_interval = check_interval + self.last_checked = 0 + try: + self.error_threshold = float( + os.getenv("RAY_MEMORY_MONITOR_ERROR_THRESHOLD") + ) + except (ValueError, TypeError): + self.error_threshold = error_threshold + # Try to read the cgroup memory limit if it is available. + try: + with open("/sys/fs/cgroup/memory/memory.limit_in_bytes", "rb") as f: + self.cgroup_memory_limit_gb = int(f.read()) / (1024**3) + except IOError: + self.cgroup_memory_limit_gb = sys.maxsize / (1024**3) + if not psutil: + logger.warning( + "WARNING: Not monitoring node memory since `psutil` " + "is not installed. Install this with " + "`pip install psutil` to enable " + "debugging of memory-related crashes." + ) + self.disabled = ( + "RAY_DEBUG_DISABLE_MEMORY_MONITOR" in os.environ + or "RAY_DISABLE_MEMORY_MONITOR" in os.environ + ) + + def get_memory_usage(self): + from ray._private.utils import get_used_memory + + total_gb = get_system_memory() / (1024**3) + used_gb = get_used_memory() / (1024**3) + + return used_gb, total_gb + + def raise_if_low_memory(self): + if self.disabled: + return + + if time.time() - self.last_checked > self.check_interval: + self.last_checked = time.time() + used_gb, total_gb = self.get_memory_usage() + + if used_gb > total_gb * self.error_threshold: + raise RayOutOfMemoryError( + RayOutOfMemoryError.get_message( + used_gb, total_gb, self.error_threshold + ) + ) + else: + logger.debug(f"Memory usage is {used_gb} / {total_gb}") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/metrics_agent.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/metrics_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..3a43b38a0fc96879398e0832484c778beac3692c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/metrics_agent.py @@ -0,0 +1,860 @@ +import json +import logging +import os +import re +import threading +import time +import traceback +from collections import defaultdict, namedtuple +from enum import Enum +from typing import Any, Dict, List, Set, Tuple, Union + +from opencensus.metrics.export.metric_descriptor import MetricDescriptorType +from opencensus.metrics.export.value import ValueDouble +from opencensus.stats import aggregation, measure as measure_module +from opencensus.stats.aggregation_data import ( + CountAggregationData, + DistributionAggregationData, + LastValueAggregationData, + SumAggregationData, +) +from opencensus.stats.base_exporter import StatsExporter +from opencensus.stats.stats_recorder import StatsRecorder +from opencensus.stats.view import View +from opencensus.stats.view_manager import ViewManager +from opencensus.tags import ( + tag_key as tag_key_module, + tag_map as tag_map_module, + tag_value as tag_value_module, +) +from prometheus_client.core import ( + CounterMetricFamily, + GaugeMetricFamily, + HistogramMetricFamily, + Metric as PrometheusMetric, +) + +import ray +from ray._private.ray_constants import RAY_METRIC_CARDINALITY_LEVEL, env_bool +from ray._raylet import GcsClient +from ray.core.generated.metrics_pb2 import Metric +from ray.util.metrics import _is_invalid_metric_name + +logger = logging.getLogger(__name__) + +# Env var key to decide worker timeout. +# If the worker doesn't report for more than +# this time, we treat workers as dead. +RAY_WORKER_TIMEOUT_S = "RAY_WORKER_TIMEOUT_S" +GLOBAL_COMPONENT_KEY = "CORE" +RE_NON_ALPHANUMS = re.compile(r"[^a-zA-Z0-9]") +# Keep in sync with the WorkerIdKey in src/ray/stats/tag_defs.cc +WORKER_ID_TAG_KEY = "WorkerId" + + +class Gauge(View): + """Gauge representation of opencensus view. + + This class is used to collect process metrics from the reporter agent. + Cpp metrics should be collected in a different way. + """ + + def __init__(self, name, description, unit, tags: List[str]): + if _is_invalid_metric_name(name): + raise ValueError( + f"Invalid metric name: {name}. Metric will be discarded " + "and data will not be collected or published. " + "Metric names can only contain letters, numbers, _, and :. " + "Metric names cannot start with numbers." + ) + self._measure = measure_module.MeasureInt(name, description, unit) + self._description = description + tags = [tag_key_module.TagKey(tag) for tag in tags] + self._view = View( + name, description, tags, self.measure, aggregation.LastValueAggregation() + ) + + @property + def measure(self): + return self._measure + + @property + def view(self): + return self._view + + @property + def name(self): + return self.measure.name + + @property + def description(self): + return self._description + + +Record = namedtuple("Record", ["gauge", "value", "tags"]) + + +def fix_grpc_metric(metric: Metric): + """ + Fix the inbound `opencensus.proto.metrics.v1.Metric` protos to make it acceptable + by opencensus.stats.DistributionAggregationData. + + - metric name: gRPC OpenCensus metrics have names with slashes and dots, e.g. + `grpc.io/client/server_latency`[1]. However Prometheus metric names only take + alphanums,underscores and colons[2]. We santinize the name by replacing non-alphanum + chars to underscore, like the official opencensus prometheus exporter[3]. + - distribution bucket bounds: The Metric proto asks distribution bucket bounds to + be > 0 [4]. However, gRPC OpenCensus metrics have their first bucket bound == 0 [1]. + This makes the `DistributionAggregationData` constructor to raise Exceptions. This + applies to all bytes and milliseconds (latencies). The fix: we update the initial 0 + bounds to be 0.000_000_1. This will not affect the precision of the metrics, since + we don't expect any less-than-1 bytes, or less-than-1-nanosecond times. + + [1] https://github.com/census-instrumentation/opencensus-specs/blob/master/stats/gRPC.md#units # noqa: E501 + [2] https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels + [3] https://github.com/census-instrumentation/opencensus-cpp/blob/50eb5de762e5f87e206c011a4f930adb1a1775b1/opencensus/exporters/stats/prometheus/internal/prometheus_utils.cc#L39 # noqa: E501 + [4] https://github.com/census-instrumentation/opencensus-proto/blob/master/src/opencensus/proto/metrics/v1/metrics.proto#L218 # noqa: E501 + """ + + if not metric.metric_descriptor.name.startswith("grpc.io/"): + return + + metric.metric_descriptor.name = RE_NON_ALPHANUMS.sub( + "_", metric.metric_descriptor.name + ) + + for series in metric.timeseries: + for point in series.points: + if point.HasField("distribution_value"): + dist_value = point.distribution_value + bucket_bounds = dist_value.bucket_options.explicit.bounds + if len(bucket_bounds) > 0 and bucket_bounds[0] == 0: + bucket_bounds[0] = 0.000_000_1 + + +class MetricCardinalityLevel(str, Enum): + """Cardinality level of the metric. + + This is used to determine the cardinality level of the metric. + The cardinality level is used to determine the type of the metric. + """ + + LEGACY = "legacy" + RECOMMENDED = "recommended" + + +class OpencensusProxyMetric: + def __init__(self, name: str, desc: str, unit: str, label_keys: List[str]): + """Represents the OpenCensus metrics that will be proxy exported.""" + self._name = name + self._desc = desc + self._unit = unit + # -- The label keys of the metric -- + self._label_keys = label_keys + # -- The data that needs to be proxy exported -- + # tuple of label values -> data (OpenCesnsus Aggregation data) + self._data = {} + + @property + def name(self): + return self._name + + @property + def desc(self): + return self._desc + + @property + def unit(self): + return self._unit + + @property + def label_keys(self): + return self._label_keys + + @property + def data(self): + return self._data + + def is_distribution_aggregation_data(self): + """Check if the metric is a distribution aggreation metric.""" + return len(self._data) > 0 and isinstance( + next(iter(self._data.values())), DistributionAggregationData + ) + + def add_data(self, label_values: Tuple, data: Any): + """Add the data to the metric. + + Args: + label_values: The label values of the metric. + data: The data to be added. + """ + self._data[label_values] = data + + def record(self, metric: Metric): + """Parse the Opencensus Protobuf and store the data. + + The data can be accessed via `data` API once recorded. + """ + timeseries = metric.timeseries + + if len(timeseries) == 0: + return + + # Create the aggregation and fill it in the our stats + for series in timeseries: + labels = tuple(val.value for val in series.label_values) + + # Aggregate points. + for point in series.points: + if ( + metric.metric_descriptor.type + == MetricDescriptorType.CUMULATIVE_INT64 + ): + data = CountAggregationData(point.int64_value) + elif ( + metric.metric_descriptor.type + == MetricDescriptorType.CUMULATIVE_DOUBLE + ): + data = SumAggregationData(ValueDouble, point.double_value) + elif metric.metric_descriptor.type == MetricDescriptorType.GAUGE_DOUBLE: + data = LastValueAggregationData(ValueDouble, point.double_value) + elif ( + metric.metric_descriptor.type + == MetricDescriptorType.CUMULATIVE_DISTRIBUTION + ): + dist_value = point.distribution_value + counts_per_bucket = [bucket.count for bucket in dist_value.buckets] + bucket_bounds = dist_value.bucket_options.explicit.bounds + data = DistributionAggregationData( + dist_value.sum / dist_value.count, + dist_value.count, + dist_value.sum_of_squared_deviation, + counts_per_bucket, + bucket_bounds, + ) + else: + raise ValueError("Summary is not supported") + self._data[labels] = data + + +class Component: + def __init__(self, id: str): + """Represent a component that requests to proxy export metrics + + Args: + id: Id of this component. + """ + self.id = id + # -- The time this component reported its metrics last time -- + # It is used to figure out if this component is stale. + self._last_reported_time = time.monotonic() + # -- Metrics requested to proxy export from this component -- + # metrics_name (str) -> metric (OpencensusProxyMetric) + self._metrics = {} + + @property + def metrics(self) -> Dict[str, OpencensusProxyMetric]: + """Return the metrics requested to proxy export from this component.""" + return self._metrics + + @property + def last_reported_time(self): + return self._last_reported_time + + def record(self, metrics: List[Metric]): + """Parse the Opencensus protobuf and store metrics. + + Metrics can be accessed via `metrics` API for proxy export. + + Args: + metrics: A list of Opencensus protobuf for proxy export. + """ + self._last_reported_time = time.monotonic() + for metric in metrics: + fix_grpc_metric(metric) + descriptor = metric.metric_descriptor + name = descriptor.name + label_keys = [label_key.key for label_key in descriptor.label_keys] + + if name not in self._metrics: + self._metrics[name] = OpencensusProxyMetric( + name, descriptor.description, descriptor.unit, label_keys + ) + self._metrics[name].record(metric) + + +class OpenCensusProxyCollector: + def __init__(self, namespace: str, component_timeout_s: int = 60): + """Prometheus collector implementation for opencensus proxy export. + + Prometheus collector requires to implement `collect` which is + invoked whenever Prometheus queries the endpoint. + + The class is thread-safe. + + Args: + namespace: Prometheus namespace. + """ + # -- Protect `self._components` -- + self._components_lock = threading.Lock() + # -- Timeout until the component is marked as stale -- + # Once the component is considered as stale, + # the metrics from that worker won't be exported. + self._component_timeout_s = component_timeout_s + # -- Prometheus namespace -- + self._namespace = namespace + # -- Component that requests to proxy export metrics -- + # Component means core worker, raylet, and GCS. + # component_id -> Components + # For workers, they contain worker ids. + # For other components (raylet, GCS), + # they contain the global key `GLOBAL_COMPONENT_KEY`. + self._components = {} + # Whether we want to export counter as gauge. + # This is for bug compatibility. + # See https://github.com/ray-project/ray/pull/43795. + self._export_counter_as_gauge = env_bool("RAY_EXPORT_COUNTER_AS_GAUGE", True) + + def record(self, metrics: List[Metric], worker_id_hex: str = None): + """Record the metrics reported from the component that reports it. + + Args: + metrics: A list of opencensus protobuf to proxy export metrics. + worker_id_hex: A worker id that reports these metrics. + If None, it means they are reported from Raylet or GCS. + """ + key = GLOBAL_COMPONENT_KEY if not worker_id_hex else worker_id_hex + with self._components_lock: + if key not in self._components: + self._components[key] = Component(key) + self._components[key].record(metrics) + + def clean_stale_components(self): + """Clean up stale components. + + Stale means the component is dead or unresponsive. + + Stale components won't be reported to Prometheus anymore. + """ + with self._components_lock: + stale_components = [] + stale_component_ids = [] + for id, component in self._components.items(): + elapsed = time.monotonic() - component.last_reported_time + if elapsed > self._component_timeout_s: + stale_component_ids.append(id) + logger.info( + "Metrics from a worker ({}) is cleaned up due to " + "timeout. Time since last report {}s".format(id, elapsed) + ) + for id in stale_component_ids: + stale_components.append(self._components.pop(id)) + return stale_components + + # TODO(sang): add start and end timestamp + def to_prometheus_metrics( + self, + metric_name: str, + metric_description: str, + label_keys: List[str], + metric_units: str, + label_values: Tuple[tag_value_module.TagValue], + agg_data: Any, + metrics_map: Dict[str, List[PrometheusMetric]], + ) -> None: + """to_metric translate the data that OpenCensus create + to Prometheus format, using Prometheus Metric object. + + This method is from Opencensus Prometheus Exporter. + + Args: + metric_name: Name of the metric. + metric_description: Description of the metric. + label_keys: The fixed label keys of the metric. + metric_units: Units of the metric. + label_values: The values of `label_keys`. + agg_data: `opencensus.stats.aggregation_data.AggregationData` object. + Aggregated data that needs to be converted as Prometheus samples + metrics_map: The converted metric is added to this map. + + """ + assert self._components_lock.locked() + metric_name = f"{self._namespace}_{metric_name}" + assert len(label_values) == len(label_keys), (label_values, label_keys) + # Prometheus requires that all tag values be strings hence + # the need to cast none to the empty string before exporting. See + # https://github.com/census-instrumentation/opencensus-python/issues/480 + label_values = [tv if tv else "" for tv in label_values] + + if isinstance(agg_data, CountAggregationData): + metrics = metrics_map.get(metric_name) + if not metrics: + metric = CounterMetricFamily( + name=metric_name, + documentation=metric_description, + unit=metric_units, + labels=label_keys, + ) + metrics = [metric] + metrics_map[metric_name] = metrics + metrics[0].add_metric(labels=label_values, value=agg_data.count_data) + return + + if isinstance(agg_data, SumAggregationData): + # This should be emitted as prometheus counter + # but we used to emit it as prometheus gauge. + # To keep the backward compatibility + # (changing from counter to gauge changes the metric name + # since prometheus client will add "_total" suffix to counter + # per OpenMetrics specification), + # we now emit both counter and gauge and in the + # next major Ray release (3.0) we can stop emitting gauge. + # This leaves people enough time to migrate their dashboards. + # See https://github.com/ray-project/ray/pull/43795. + metrics = metrics_map.get(metric_name) + if not metrics: + metric = CounterMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + ) + metrics = [metric] + metrics_map[metric_name] = metrics + metrics[0].add_metric(labels=label_values, value=agg_data.sum_data) + + if not self._export_counter_as_gauge: + pass + elif metric_name.endswith("_total"): + # In this case, we only need to emit prometheus counter + # since for metric name already ends with _total suffix + # prometheus client won't change it + # so there is no backward compatibility issue. + # See https://prometheus.github.io/client_python/instrumenting/counter/ + pass + else: + if len(metrics) == 1: + metric = GaugeMetricFamily( + name=metric_name, + documentation=( + f"(DEPRECATED, use {metric_name}_total metric instead) " + f"{metric_description}" + ), + labels=label_keys, + ) + metrics.append(metric) + assert len(metrics) == 2 + metrics[1].add_metric(labels=label_values, value=agg_data.sum_data) + return + + elif isinstance(agg_data, DistributionAggregationData): + + assert agg_data.bounds == sorted(agg_data.bounds) + # buckets are a list of buckets. Each bucket is another list with + # a pair of bucket name and value, or a triple of bucket name, + # value, and exemplar. buckets need to be in order. + buckets = [] + cum_count = 0 # Prometheus buckets expect cumulative count. + for ii, bound in enumerate(agg_data.bounds): + cum_count += agg_data.counts_per_bucket[ii] + bucket = [str(bound), cum_count] + buckets.append(bucket) + # Prometheus requires buckets to be sorted, and +Inf present. + # In OpenCensus we don't have +Inf in the bucket bonds so need to + # append it here. + buckets.append(["+Inf", agg_data.count_data]) + metrics = metrics_map.get(metric_name) + if not metrics: + metric = HistogramMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + ) + metrics = [metric] + metrics_map[metric_name] = metrics + metrics[0].add_metric( + labels=label_values, + buckets=buckets, + sum_value=agg_data.sum, + ) + return + + elif isinstance(agg_data, LastValueAggregationData): + metrics = metrics_map.get(metric_name) + if not metrics: + metric = GaugeMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + ) + metrics = [metric] + metrics_map[metric_name] = metrics + metrics[0].add_metric(labels=label_values, value=agg_data.value) + return + + else: + raise ValueError(f"unsupported aggregation type {type(agg_data)}") + + def _get_metric_cardinality_level_setting(self) -> str: + return RAY_METRIC_CARDINALITY_LEVEL.lower() + + def _get_metric_cardinality_level(self) -> MetricCardinalityLevel: + """Get the cardinality level of the core metric. + + This is used to determine set of metric labels. Some high cardinality labels + such as `WorkerId` and `Name` will be removed on low cardinality level. + """ + try: + return MetricCardinalityLevel(self._get_metric_cardinality_level_setting()) + except ValueError: + return MetricCardinalityLevel.LEGACY + + def _aggregate_metric_data( + self, + datas: List[ + Union[LastValueAggregationData, CountAggregationData, SumAggregationData] + ], + ) -> Union[LastValueAggregationData, CountAggregationData, SumAggregationData]: + assert len(datas) > 0 + sample = datas[0] + if isinstance(sample, LastValueAggregationData): + return LastValueAggregationData( + ValueDouble, sum([data.value for data in datas]) + ) + if isinstance(sample, CountAggregationData): + return CountAggregationData(sum([data.count_data for data in datas])) + if isinstance(sample, SumAggregationData): + return SumAggregationData( + ValueDouble, sum([data.sum_data for data in datas]) + ) + + raise ValueError( + f"Unsupported aggregation type {type(sample)}. " + "Supported types are " + f"{CountAggregationData}, {LastValueAggregationData}, {SumAggregationData}." + f"Got {datas}." + ) + + def _aggregate_with_recommended_cardinality( + self, + per_worker_metrics: List[OpencensusProxyMetric], + ) -> List[OpencensusProxyMetric]: + """Collect per-worker metrics, aggregate them into per-node metrics and convert + them to Prometheus format. + + Args: + per_worker_metrics: A list of per-worker metrics for the same metric name. + Returns: + A list of per-node metrics for the same metric name, with the high + cardinality labels removed and the values aggregated. + """ + metric = next(iter(per_worker_metrics), None) + if not metric or WORKER_ID_TAG_KEY not in metric.label_keys: + # No high cardinality labels, return the original metrics. + return per_worker_metrics + + worker_id_label_index = metric.label_keys.index(WORKER_ID_TAG_KEY) + # map from the tuple of label values without worker_id to the list of per worker + # task metrics + label_value_to_data: Dict[ + Tuple, + List[ + Union[ + LastValueAggregationData, + CountAggregationData, + SumAggregationData, + ] + ], + ] = defaultdict(list) + for metric in per_worker_metrics: + for label_values, data in metric.data.items(): + # remove the worker_id from the label values + label_value_to_data[ + label_values[:worker_id_label_index] + + label_values[worker_id_label_index + 1 :] + ].append(data) + + aggregated_metric = OpencensusProxyMetric( + name=metric.name, + desc=metric.desc, + unit=metric.unit, + # remove the worker_id from the label keys + label_keys=metric.label_keys[:worker_id_label_index] + + metric.label_keys[worker_id_label_index + 1 :], + ) + for label_values, datas in label_value_to_data.items(): + aggregated_metric.add_data( + label_values, + self._aggregate_metric_data(datas), + ) + + return [aggregated_metric] + + def collect(self): # pragma: NO COVER + """Collect fetches the statistics from OpenCensus + and delivers them as Prometheus Metrics. + Collect is invoked every time a prometheus.Gatherer is run + for example when the HTTP endpoint is invoked by Prometheus. + + This method is required as a Prometheus Collector. + """ + with self._components_lock: + # First construct the list of opencensus metrics to be converted to + # prometheus metrics. For LEGACY cardinality level, this comprises all + # metrics from all components. For RECOMMENDED cardinality level, we need + # to remove the high cardinality labels and aggreate the component metrics. + open_cencus_metrics: List[OpencensusProxyMetric] = [] + # The metrics that need to be aggregated with recommended cardinality. Key + # is the metric name and value is the list of per-worker metrics. + to_lower_cardinality: Dict[str, List[OpencensusProxyMetric]] = defaultdict( + list + ) + cardinality_level = self._get_metric_cardinality_level() + for component in self._components.values(): + for metric in component.metrics.values(): + if ( + cardinality_level == MetricCardinalityLevel.RECOMMENDED + and not metric.is_distribution_aggregation_data() + ): + # We reduce the cardinality for all metrics except for histogram + # metrics. The aggregation of histogram metrics from worker + # level to node level is not well defined. In addition, we + # currently have very few histogram metrics in Ray + # (metric_defs.cc) so the impact of them is negligible. + to_lower_cardinality[metric.name].append(metric) + else: + open_cencus_metrics.append(metric) + for per_worker_metrics in to_lower_cardinality.values(): + open_cencus_metrics.extend( + self._aggregate_with_recommended_cardinality( + per_worker_metrics, + ) + ) + + prometheus_metrics_map = {} + for metric in open_cencus_metrics: + for label_values, data in metric.data.items(): + self.to_prometheus_metrics( + metric.name, + metric.desc, + metric.label_keys, + metric.unit, + label_values, + data, + prometheus_metrics_map, + ) + + for metrics in prometheus_metrics_map.values(): + for metric in metrics: + yield metric + + +class MetricsAgent: + def __init__( + self, + view_manager: ViewManager, + stats_recorder: StatsRecorder, + stats_exporter: StatsExporter = None, + ): + """A class to record and export metrics. + + The class exports metrics in 2 different ways. + - Directly record and export metrics using OpenCensus. + - Proxy metrics from other core components + (e.g., raylet, GCS, core workers). + + This class is thread-safe. + """ + # Lock required because gRPC server uses + # multiple threads to process requests. + self._lock = threading.Lock() + + # + # Opencensus components to record metrics. + # + + # Managing views to export metrics + # If the stats_exporter is None, we disable all metrics export. + self.view_manager = view_manager + # A class that's used to record metrics + # emitted from the current process. + self.stats_recorder = stats_recorder + # A class to export metrics. + self.stats_exporter = stats_exporter + # -- A Prometheus custom collector to proxy export metrics -- + # `None` if the prometheus server is not started. + self.proxy_exporter_collector = None + + if self.stats_exporter is None: + # If the exporter is not given, + # we disable metrics collection. + self.view_manager = None + else: + self.view_manager.register_exporter(stats_exporter) + self.proxy_exporter_collector = OpenCensusProxyCollector( + self.stats_exporter.options.namespace, + component_timeout_s=int(os.getenv(RAY_WORKER_TIMEOUT_S, 120)), + ) + + # Registered view names. + self._registered_views: Set[str] = set() + + def record_and_export(self, records: List[Record], global_tags=None): + """Directly record and export stats from the same process.""" + global_tags = global_tags or {} + with self._lock: + if not self.view_manager: + return + + for record in records: + gauge = record.gauge + value = record.value + tags = record.tags + try: + self._record_gauge(gauge, value, {**tags, **global_tags}) + except Exception as e: + logger.error( + f"Failed to record metric {gauge.name} with value {value} with tags {tags!r} and global tags {global_tags!r} due to: {e!r}" + ) + + def _record_gauge(self, gauge: Gauge, value: float, tags: dict): + if gauge.name not in self._registered_views: + self.view_manager.register_view(gauge.view) + self._registered_views.add(gauge.name) + measurement_map = self.stats_recorder.new_measurement_map() + tag_map = tag_map_module.TagMap() + for key, tag_val in tags.items(): + try: + tag_key = tag_key_module.TagKey(key) + except ValueError as e: + logger.error( + f"Failed to create tag key {key} for metric {gauge.name} due to: {e!r}" + ) + raise e + try: + tag_value = tag_value_module.TagValue(tag_val) + except ValueError as e: + logger.error( + f"Failed to create tag value {tag_val} for key {key} for metric {gauge.name} due to: {e!r}" + ) + raise e + tag_map.insert(tag_key, tag_value) + measurement_map.measure_float_put(gauge.measure, value) + # NOTE: When we record this metric, timestamp will be renewed. + measurement_map.record(tag_map) + + def proxy_export_metrics(self, metrics: List[Metric], worker_id_hex: str = None): + """Proxy export metrics specified by a Opencensus Protobuf. + + This API is used to export metrics emitted from + core components. + + Args: + metrics: A list of protobuf Metric defined from OpenCensus. + worker_id_hex: The worker ID it proxies metrics export. None + if the metric is not from a worker (i.e., raylet, GCS). + """ + with self._lock: + if not self.view_manager: + return + + self._proxy_export_metrics(metrics, worker_id_hex) + + def _proxy_export_metrics(self, metrics: List[Metric], worker_id_hex: str = None): + self.proxy_exporter_collector.record(metrics, worker_id_hex) + + def clean_all_dead_worker_metrics(self): + """Clean dead worker's metrics. + + Worker metrics are cleaned up and won't be exported once + it is considered as dead. + + This method has to be periodically called by a caller. + """ + with self._lock: + if not self.view_manager: + return + + self.proxy_exporter_collector.clean_stale_components() + + +class PrometheusServiceDiscoveryWriter(threading.Thread): + """A class to support Prometheus service discovery. + + It supports file-based service discovery. Checkout + https://prometheus.io/docs/guides/file-sd/ for more details. + + Args: + gcs_address: Gcs address for this cluster. + temp_dir: Temporary directory used by + Ray to store logs and metadata. + """ + + def __init__(self, gcs_address, temp_dir): + gcs_client_options = ray._raylet.GcsClientOptions.create( + gcs_address, None, allow_cluster_id_nil=True, fetch_cluster_id_if_nil=False + ) + self.gcs_address = gcs_address + + ray._private.state.state._initialize_global_state(gcs_client_options) + self.temp_dir = temp_dir + self.default_service_discovery_flush_period = 5 + super().__init__() + + def get_file_discovery_content(self): + """Return the content for Prometheus service discovery.""" + nodes = ray.nodes() + metrics_export_addresses = [ + "{}:{}".format(node["NodeManagerAddress"], node["MetricsExportPort"]) + for node in nodes + if node["alive"] is True + ] + gcs_client = GcsClient(address=self.gcs_address) + autoscaler_addr = gcs_client.internal_kv_get(b"AutoscalerMetricsAddress", None) + if autoscaler_addr: + metrics_export_addresses.append(autoscaler_addr.decode("utf-8")) + dashboard_addr = gcs_client.internal_kv_get(b"DashboardMetricsAddress", None) + if dashboard_addr: + metrics_export_addresses.append(dashboard_addr.decode("utf-8")) + return json.dumps( + [{"labels": {"job": "ray"}, "targets": metrics_export_addresses}] + ) + + def write(self): + # Write a file based on https://prometheus.io/docs/guides/file-sd/ + # Write should be atomic. Otherwise, Prometheus raises an error that + # json file format is invalid because it reads a file when + # file is re-written. Note that Prometheus still works although we + # have this error. + temp_file_name = self.get_temp_file_name() + with open(temp_file_name, "w") as json_file: + json_file.write(self.get_file_discovery_content()) + # NOTE: os.replace is atomic on both Linux and Windows, so we won't + # have race condition reading this file. + os.replace(temp_file_name, self.get_target_file_name()) + + def get_target_file_name(self): + return os.path.join( + self.temp_dir, ray._private.ray_constants.PROMETHEUS_SERVICE_DISCOVERY_FILE + ) + + def get_temp_file_name(self): + return os.path.join( + self.temp_dir, + "{}_{}".format( + "tmp", ray._private.ray_constants.PROMETHEUS_SERVICE_DISCOVERY_FILE + ), + ) + + def run(self): + while True: + # This thread won't be broken by exceptions. + try: + self.write() + except Exception as e: + logger.warning( + "Writing a service discovery file, {}," + "failed.".format(self.get_target_file_name()) + ) + logger.warning(traceback.format_exc()) + logger.warning(f"Error message: {e}") + time.sleep(self.default_service_discovery_flush_period) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/node.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f1207fc0471dbd18d374cb1f9d731a93159ad3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/node.py @@ -0,0 +1,1918 @@ +import atexit +import collections +import datetime +import errno +import json +import logging +import os +import random +import signal +import socket +import subprocess +import sys +import tempfile +import threading +import time +import traceback +from collections import defaultdict +from typing import IO, AnyStr, Dict, Optional, Tuple + +from filelock import FileLock + +import ray +import ray._private.ray_constants as ray_constants +import ray._private.services +from ray._common.utils import try_to_create_directory +from ray._private.resource_isolation_config import ResourceIsolationConfig +from ray._private.resource_spec import ResourceSpec +from ray._private.services import get_address, serialize_config +from ray._private.utils import ( + is_in_test, + open_log, + try_to_symlink, + validate_socket_filepath, +) +from ray._raylet import GcsClient, get_session_key_from_storage + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray configures it by default automatically +# using logging.basicConfig in its entry/init points. +logger = logging.getLogger(__name__) + + +class Node: + """An encapsulation of the Ray processes on a single node. + + This class is responsible for starting Ray processes and killing them, + and it also controls the temp file policy. + + Attributes: + all_processes: A mapping from process type (str) to a list of + ProcessInfo objects. All lists have length one except for the Redis + server list, which has multiple. + """ + + def __init__( + self, + ray_params, + head: bool = False, + shutdown_at_exit: bool = True, + spawn_reaper: bool = True, + connect_only: bool = False, + default_worker: bool = False, + ray_init_cluster: bool = False, + ): + """Start a node. + + Args: + ray_params: The RayParams to use to configure the node. + head: True if this is the head node, which means it will + start additional processes like the Redis servers, monitor + processes, and web UI. + shutdown_at_exit: If true, spawned processes will be cleaned + up if this process exits normally. + spawn_reaper: If true, spawns a process that will clean up + other spawned processes if this process dies unexpectedly. + connect_only: If true, connect to the node without starting + new processes. + default_worker: Whether it's running from a ray worker or not + ray_init_cluster: Whether it's a cluster created by ray.init() + """ + if shutdown_at_exit: + if connect_only: + raise ValueError( + "'shutdown_at_exit' and 'connect_only' cannot both be true." + ) + self._register_shutdown_hooks() + self._default_worker = default_worker + self.head = head + self.kernel_fate_share = bool( + spawn_reaper and ray._private.utils.detect_fate_sharing_support() + ) + self.resource_isolation_config: ResourceIsolationConfig = ( + ray_params.resource_isolation_config + ) + self.all_processes: dict = {} + self.removal_lock = threading.Lock() + + self.ray_init_cluster = ray_init_cluster + if ray_init_cluster: + assert head, "ray.init() created cluster only has the head node" + + # Set up external Redis when `RAY_REDIS_ADDRESS` is specified. + redis_address_env = os.environ.get("RAY_REDIS_ADDRESS") + if ray_params.external_addresses is None and redis_address_env is not None: + external_redis = redis_address_env.split(",") + + # Reuse primary Redis as Redis shard when there's only one + # instance provided. + if len(external_redis) == 1: + external_redis.append(external_redis[0]) + [primary_redis_ip, port] = external_redis[0].rsplit(":", 1) + ray_params.external_addresses = external_redis + ray_params.num_redis_shards = len(external_redis) - 1 + + if ( + ray_params._system_config + and len(ray_params._system_config) > 0 + and (not head and not connect_only) + ): + raise ValueError( + "System config parameters can only be set on the head node." + ) + + ray_params.update_if_absent( + include_log_monitor=True, + resources={}, + worker_path=os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "workers", + "default_worker.py", + ), + setup_worker_path=os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "workers", + ray_constants.SETUP_WORKER_FILENAME, + ), + ) + + self._resource_spec = None + self._localhost = socket.gethostbyname("localhost") + self._ray_params = ray_params + self._config = ray_params._system_config or {} + + self._dashboard_agent_listen_port = ray_params.dashboard_agent_listen_port + + # Configure log rotation parameters. + self.max_bytes = int( + os.getenv("RAY_ROTATION_MAX_BYTES", ray_constants.LOGGING_ROTATE_BYTES) + ) + self.backup_count = int( + os.getenv( + "RAY_ROTATION_BACKUP_COUNT", ray_constants.LOGGING_ROTATE_BACKUP_COUNT + ) + ) + + assert self.max_bytes >= 0 + assert self.backup_count >= 0 + + self._redis_address = ray_params.redis_address + if head: + ray_params.update_if_absent(num_redis_shards=1) + self._gcs_address = ray_params.gcs_address + self._gcs_client = None + + if not self.head: + self.validate_ip_port(self.address) + self._init_gcs_client() + + # Register the temp dir. + self._session_name = ray_params.session_name + if self._session_name is None: + if head: + # We expect this the first time we initialize a cluster, but not during + # subsequent restarts of the head node. + maybe_key = self.check_persisted_session_name() + if maybe_key is None: + # date including microsecond + date_str = datetime.datetime.today().strftime( + "%Y-%m-%d_%H-%M-%S_%f" + ) + self._session_name = f"session_{date_str}_{os.getpid()}" + else: + self._session_name = ray._common.utils.decode(maybe_key) + else: + assert not self._default_worker + session_name = ray._private.utils.internal_kv_get_with_retry( + self.get_gcs_client(), + "session_name", + ray_constants.KV_NAMESPACE_SESSION, + num_retries=ray_constants.NUM_REDIS_GET_RETRIES, + ) + self._session_name = ray._common.utils.decode(session_name) + + # Initialize webui url + if head: + self._webui_url = None + else: + if ray_params.webui is None: + assert not self._default_worker + self._webui_url = ray._private.services.get_webui_url_from_internal_kv() + else: + self._webui_url = ( + f"{ray_params.dashboard_host}:{ray_params.dashboard_port}" + ) + + # It creates a session_dir. + self._init_temp() + + node_ip_address = ray_params.node_ip_address + if node_ip_address is None: + if connect_only: + node_ip_address = self._wait_and_get_for_node_address() + else: + node_ip_address = ray.util.get_node_ip_address() + + assert node_ip_address is not None + ray_params.update_if_absent( + node_ip_address=node_ip_address, raylet_ip_address=node_ip_address + ) + self._node_ip_address = node_ip_address + if not connect_only: + ray._private.services.write_node_ip_address( + self.get_session_dir_path(), node_ip_address + ) + + if ray_params.raylet_ip_address: + raylet_ip_address = ray_params.raylet_ip_address + else: + raylet_ip_address = node_ip_address + + if raylet_ip_address != node_ip_address and (not connect_only or head): + raise ValueError( + "The raylet IP address should only be different than the node " + "IP address when connecting to an existing raylet; i.e., when " + "head=False and connect_only=True." + ) + self._raylet_ip_address = raylet_ip_address + + self._object_spilling_config = self._get_object_spilling_config() + logger.debug( + f"Starting node with object spilling config: {self._object_spilling_config}" + ) + + # Obtain the fallback directoy from the object spilling config + # Currently, we set the fallback directory to be the same as the object spilling + # path when the object spills to file system + self._fallback_directory = None + if self._object_spilling_config: + config = json.loads(self._object_spilling_config) + if config.get("type") == "filesystem": + directory_path = config.get("params", {}).get("directory_path") + if isinstance(directory_path, list): + self._fallback_directory = directory_path[0] + elif isinstance(directory_path, str): + self._fallback_directory = directory_path + + # If it is a head node, try validating if external storage is configurable. + if head: + self.validate_external_storage() + + if connect_only: + # Get socket names from the configuration. + self._plasma_store_socket_name = ray_params.plasma_store_socket_name + self._raylet_socket_name = ray_params.raylet_socket_name + self._node_id = ray_params.node_id + + # If user does not provide the socket name, get it from Redis. + if ( + self._plasma_store_socket_name is None + or self._raylet_socket_name is None + or self._ray_params.node_manager_port is None + or self._node_id is None + ): + # Get the address info of the processes to connect to + # from Redis or GCS. + node_info = ray._private.services.get_node_to_connect_for_driver( + self.gcs_address, + self._raylet_ip_address, + ) + self._plasma_store_socket_name = node_info["object_store_socket_name"] + self._raylet_socket_name = node_info["raylet_socket_name"] + self._ray_params.node_manager_port = node_info["node_manager_port"] + self._node_id = node_info["node_id"] + else: + # If the user specified a socket name, use it. + self._plasma_store_socket_name = self._prepare_socket_file( + self._ray_params.plasma_store_socket_name, default_prefix="plasma_store" + ) + self._raylet_socket_name = self._prepare_socket_file( + self._ray_params.raylet_socket_name, default_prefix="raylet" + ) + # Set node labels from RayParams or environment override variables. + self._node_labels = self._get_node_labels() + if ( + self._ray_params.env_vars is not None + and "RAY_OVERRIDE_NODE_ID_FOR_TESTING" in self._ray_params.env_vars + ): + node_id = self._ray_params.env_vars["RAY_OVERRIDE_NODE_ID_FOR_TESTING"] + logger.debug( + f"Setting node ID to {node_id} " + "based on ray_params.env_vars override" + ) + self._node_id = node_id + elif os.environ.get("RAY_OVERRIDE_NODE_ID_FOR_TESTING"): + node_id = os.environ["RAY_OVERRIDE_NODE_ID_FOR_TESTING"] + logger.debug(f"Setting node ID to {node_id} based on env override") + self._node_id = node_id + else: + node_id = ray.NodeID.from_random().hex() + logger.debug(f"Setting node ID to {node_id}") + self._node_id = node_id + + # The dashboard agent port is assigned first to avoid + # other processes accidentally taking its default port + self._dashboard_agent_listen_port = self._get_cached_port( + "dashboard_agent_listen_port", + default_port=ray_params.dashboard_agent_listen_port, + ) + + self.metrics_agent_port = self._get_cached_port( + "metrics_agent_port", default_port=ray_params.metrics_agent_port + ) + self._metrics_export_port = self._get_cached_port( + "metrics_export_port", default_port=ray_params.metrics_export_port + ) + self._runtime_env_agent_port = self._get_cached_port( + "runtime_env_agent_port", + default_port=ray_params.runtime_env_agent_port, + ) + + ray_params.update_if_absent( + metrics_agent_port=self.metrics_agent_port, + metrics_export_port=self._metrics_export_port, + dashboard_agent_listen_port=self._dashboard_agent_listen_port, + runtime_env_agent_port=self._runtime_env_agent_port, + ) + + # Pick a GCS server port. + if head: + gcs_server_port = os.getenv(ray_constants.GCS_PORT_ENVIRONMENT_VARIABLE) + if gcs_server_port: + ray_params.update_if_absent(gcs_server_port=int(gcs_server_port)) + if ray_params.gcs_server_port is None or ray_params.gcs_server_port == 0: + ray_params.gcs_server_port = self._get_cached_port("gcs_server_port") + + if not connect_only and spawn_reaper and not self.kernel_fate_share: + self.start_reaper_process() + if not connect_only: + self._ray_params.update_pre_selected_port() + + # Start processes. + if head: + self.start_head_processes() + + if not connect_only: + self.start_ray_processes() + # we should update the address info after the node has been started + try: + ray._private.services.wait_for_node( + self.gcs_address, + self._plasma_store_socket_name, + ) + except TimeoutError as te: + raise Exception( + "The current node timed out during startup. This " + "could happen because some of the Ray processes " + "failed to startup." + ) from te + + # Fetch node info to update port or get labels. + node_info = ray._private.services.get_node( + self.gcs_address, + self._node_id, + ) + if not connect_only and self._ray_params.node_manager_port == 0: + self._ray_params.node_manager_port = node_info["node_manager_port"] + elif connect_only: + # Set node labels from GCS if provided at node init. + self._node_labels = node_info.get("labels", {}) + + # Makes sure the Node object has valid addresses after setup. + self.validate_ip_port(self.address) + self.validate_ip_port(self.gcs_address) + + if not connect_only: + self._record_stats() + + def check_persisted_session_name(self): + if self._ray_params.external_addresses is None: + return None + self._redis_address = self._ray_params.external_addresses[0] + redis_ip_address, redis_port, enable_redis_ssl = get_address( + self._redis_address, + ) + # Address is ip:port or redis://ip:port + if int(redis_port) < 0: + raise ValueError( + f"Invalid Redis port provided: {redis_port}." + "The port must be a non-negative integer." + ) + + return get_session_key_from_storage( + redis_ip_address, + int(redis_port), + self._ray_params.redis_username, + self._ray_params.redis_password, + enable_redis_ssl, + serialize_config(self._config), + b"session_name", + ) + + @staticmethod + def validate_ip_port(ip_port): + """Validates the address is in the ip:port format""" + _, _, port = ip_port.rpartition(":") + if port == ip_port: + raise ValueError(f"Port is not specified for address {ip_port}") + try: + _ = int(port) + except ValueError: + raise ValueError( + f"Unable to parse port number from {port} (full address = {ip_port})" + ) + + def check_version_info(self): + """Check if the Python and Ray version of this process matches that in GCS. + + This will be used to detect if workers or drivers are started using + different versions of Python, or Ray. + + Raises: + Exception: An exception is raised if there is a version mismatch. + """ + import ray._private.usage.usage_lib as ray_usage_lib + + cluster_metadata = ray_usage_lib.get_cluster_metadata(self.get_gcs_client()) + if cluster_metadata is None: + cluster_metadata = ray_usage_lib.get_cluster_metadata(self.get_gcs_client()) + + if not cluster_metadata: + return + node_ip_address = ray._private.services.get_node_ip_address() + ray._private.utils.check_version_info( + cluster_metadata, f"node {node_ip_address}" + ) + + def _register_shutdown_hooks(self): + # Register the atexit handler. In this case, we shouldn't call sys.exit + # as we're already in the exit procedure. + def atexit_handler(*args): + self.kill_all_processes(check_alive=False, allow_graceful=True) + + atexit.register(atexit_handler) + + # Register the handler to be called if we get a SIGTERM. + # In this case, we want to exit with an error code (1) after + # cleaning up child processes. + def sigterm_handler(signum, frame): + self.kill_all_processes(check_alive=False, allow_graceful=True) + sys.exit(1) + + ray._private.utils.set_sigterm_handler(sigterm_handler) + + def _init_temp(self): + # Create a dictionary to store temp file index. + self._incremental_dict = collections.defaultdict(lambda: 0) + + if self.head: + self._ray_params.update_if_absent( + temp_dir=ray._common.utils.get_ray_temp_dir() + ) + self._temp_dir = self._ray_params.temp_dir + else: + if self._ray_params.temp_dir is None: + assert not self._default_worker + temp_dir = ray._private.utils.internal_kv_get_with_retry( + self.get_gcs_client(), + "temp_dir", + ray_constants.KV_NAMESPACE_SESSION, + num_retries=ray_constants.NUM_REDIS_GET_RETRIES, + ) + self._temp_dir = ray._common.utils.decode(temp_dir) + else: + self._temp_dir = self._ray_params.temp_dir + + try_to_create_directory(self._temp_dir) + + if self.head: + self._session_dir = os.path.join(self._temp_dir, self._session_name) + else: + if self._temp_dir is None or self._session_name is None: + assert not self._default_worker + session_dir = ray._private.utils.internal_kv_get_with_retry( + self.get_gcs_client(), + "session_dir", + ray_constants.KV_NAMESPACE_SESSION, + num_retries=ray_constants.NUM_REDIS_GET_RETRIES, + ) + self._session_dir = ray._common.utils.decode(session_dir) + else: + self._session_dir = os.path.join(self._temp_dir, self._session_name) + session_symlink = os.path.join(self._temp_dir, ray_constants.SESSION_LATEST) + + # Send a warning message if the session exists. + try_to_create_directory(self._session_dir) + try_to_symlink(session_symlink, self._session_dir) + # Create a directory to be used for socket files. + self._sockets_dir = os.path.join(self._session_dir, "sockets") + try_to_create_directory(self._sockets_dir) + # Create a directory to be used for process log files. + self._logs_dir = os.path.join(self._session_dir, "logs") + try_to_create_directory(self._logs_dir) + old_logs_dir = os.path.join(self._logs_dir, "old") + try_to_create_directory(old_logs_dir) + # Create a directory to be used for runtime environment. + self._runtime_env_dir = os.path.join( + self._session_dir, self._ray_params.runtime_env_dir_name + ) + try_to_create_directory(self._runtime_env_dir) + # Create a symlink to the libtpu tpu_logs directory if it exists. + user_temp_dir = ray._common.utils.get_user_temp_dir() + tpu_log_dir = f"{user_temp_dir}/tpu_logs" + if os.path.isdir(tpu_log_dir): + tpu_logs_symlink = os.path.join(self._logs_dir, "tpu_logs") + try_to_symlink(tpu_logs_symlink, tpu_log_dir) + + def _get_node_labels(self): + def merge_labels(env_override_labels, params_labels): + """Merges two dictionaries, picking from the + first in the event of a conflict. Also emit a warning on every + conflict. + """ + + result = params_labels.copy() + result.update(env_override_labels) + + for key in set(env_override_labels.keys()).intersection( + set(params_labels.keys()) + ): + if params_labels[key] != env_override_labels[key]: + logger.warning( + "Autoscaler is overriding your label:" + f"{key}: {params_labels[key]} to " + f"{key}: {env_override_labels[key]}." + ) + return result + + env_override_labels = {} + env_override_labels_string = os.getenv( + ray_constants.LABELS_ENVIRONMENT_VARIABLE + ) + if env_override_labels_string: + try: + env_override_labels = json.loads(env_override_labels_string) + except Exception: + logger.exception(f"Failed to load {env_override_labels_string}") + raise + logger.info(f"Autoscaler overriding labels: {env_override_labels}.") + + return merge_labels(env_override_labels, self._ray_params.labels or {}) + + def get_resource_spec(self): + """Resolve and return the current resource spec for the node.""" + + def merge_resources(env_dict, params_dict): + """Separates special case params and merges two dictionaries, picking from the + first in the event of a conflict. Also emit a warning on every + conflict. + """ + num_cpus = env_dict.pop("CPU", None) + num_gpus = env_dict.pop("GPU", None) + memory = env_dict.pop("memory", None) + object_store_memory = env_dict.pop("object_store_memory", None) + + result = params_dict.copy() + result.update(env_dict) + + for key in set(env_dict.keys()).intersection(set(params_dict.keys())): + if params_dict[key] != env_dict[key]: + logger.warning( + "Autoscaler is overriding your resource:" + f"{key}: {params_dict[key]} with {env_dict[key]}." + ) + return num_cpus, num_gpus, memory, object_store_memory, result + + if not self._resource_spec: + env_resources = {} + env_string = os.getenv(ray_constants.RESOURCES_ENVIRONMENT_VARIABLE) + if env_string: + try: + env_resources = json.loads(env_string) + except Exception: + logger.exception(f"Failed to load {env_string}") + raise + logger.debug(f"Autoscaler overriding resources: {env_resources}.") + ( + num_cpus, + num_gpus, + memory, + object_store_memory, + resources, + ) = merge_resources(env_resources, self._ray_params.resources) + self._resource_spec = ResourceSpec( + self._ray_params.num_cpus if num_cpus is None else num_cpus, + self._ray_params.num_gpus if num_gpus is None else num_gpus, + self._ray_params.memory if memory is None else memory, + ( + self._ray_params.object_store_memory + if object_store_memory is None + else object_store_memory + ), + resources, + ).resolve(is_head=self.head, node_ip_address=self.node_ip_address) + return self._resource_spec + + @property + def node_id(self): + """Get the node ID.""" + return self._node_id + + @property + def session_name(self): + """Get the session name (cluster ID).""" + return self._session_name + + @property + def node_ip_address(self): + """Get the IP address of this node.""" + return self._node_ip_address + + @property + def raylet_ip_address(self): + """Get the IP address of the raylet that this node connects to.""" + return self._raylet_ip_address + + @property + def address(self): + """Get the address for bootstrapping, e.g. the address to pass to + `ray start` or `ray.init()` to start worker nodes, that has been + converted to ip:port format. + """ + return self._gcs_address + + @property + def gcs_address(self): + """Get the gcs address.""" + assert self._gcs_address is not None, "Gcs address is not set" + return self._gcs_address + + @property + def redis_address(self): + """Get the cluster Redis address.""" + return self._redis_address + + @property + def redis_username(self): + """Get the cluster Redis username.""" + return self._ray_params.redis_username + + @property + def redis_password(self): + """Get the cluster Redis password.""" + return self._ray_params.redis_password + + @property + def plasma_store_socket_name(self): + """Get the node's plasma store socket name.""" + return self._plasma_store_socket_name + + @property + def unique_id(self): + """Get a unique identifier for this node.""" + return f"{self.node_ip_address}:{self._plasma_store_socket_name}" + + @property + def webui_url(self): + """Get the cluster's web UI url.""" + return self._webui_url + + @property + def raylet_socket_name(self): + """Get the node's raylet socket name.""" + return self._raylet_socket_name + + @property + def node_manager_port(self): + """Get the node manager's port.""" + return self._ray_params.node_manager_port + + @property + def metrics_export_port(self): + """Get the port that exposes metrics""" + return self._metrics_export_port + + @property + def runtime_env_agent_port(self): + """Get the port that exposes runtime env agent as http""" + return self._runtime_env_agent_port + + @property + def runtime_env_agent_address(self): + """Get the address that exposes runtime env agent as http""" + return f"http://{self._raylet_ip_address}:{self._runtime_env_agent_port}" + + @property + def dashboard_agent_listen_port(self): + """Get the dashboard agent's listen port""" + return self._dashboard_agent_listen_port + + @property + def logging_config(self): + """Get the logging config of the current node.""" + return { + "log_rotation_max_bytes": self.max_bytes, + "log_rotation_backup_count": self.backup_count, + } + + @property + def address_info(self): + """Get a dictionary of addresses.""" + return { + "node_ip_address": self._node_ip_address, + "raylet_ip_address": self._raylet_ip_address, + "redis_address": self.redis_address, + "object_store_address": self._plasma_store_socket_name, + "raylet_socket_name": self._raylet_socket_name, + "webui_url": self._webui_url, + "session_dir": self._session_dir, + "metrics_export_port": self._metrics_export_port, + "gcs_address": self.gcs_address, + "address": self.address, + "dashboard_agent_listen_port": self.dashboard_agent_listen_port, + } + + @property + def node_labels(self): + """Get the node labels.""" + return self._node_labels + + def is_head(self): + return self.head + + def get_gcs_client(self): + if self._gcs_client is None: + self._init_gcs_client() + return self._gcs_client + + def _init_gcs_client(self): + if self.head: + gcs_process = self.all_processes[ray_constants.PROCESS_TYPE_GCS_SERVER][ + 0 + ].process + else: + gcs_process = None + + # TODO(ryw) instead of create a new GcsClient, wrap the one from + # CoreWorkerProcess to save a grpc channel. + for _ in range(ray_constants.NUM_REDIS_GET_RETRIES): + gcs_address = None + last_ex = None + try: + gcs_address = self.gcs_address + client = GcsClient( + address=gcs_address, + cluster_id=self._ray_params.cluster_id, # Hex string + ) + self.cluster_id = client.cluster_id + if self.head: + # Send a simple request to make sure GCS is alive + # if it's a head node. + client.internal_kv_get(b"dummy", None) + self._gcs_client = client + break + except Exception: + if gcs_process is not None and gcs_process.poll() is not None: + # GCS has exited. + break + last_ex = traceback.format_exc() + logger.debug(f"Connecting to GCS: {last_ex}") + time.sleep(1) + + if self._gcs_client is None: + if hasattr(self, "_logs_dir"): + with open(os.path.join(self._logs_dir, "gcs_server.err")) as err: + # Use " C " or " E " to exclude the stacktrace. + # This should work for most cases, especitally + # it's when GCS is starting. Only display last 10 lines of logs. + errors = [e for e in err.readlines() if " C " in e or " E " in e][ + -10: + ] + error_msg = "\n" + "".join(errors) + "\n" + raise RuntimeError( + f"Failed to {'start' if self.head else 'connect to'} GCS. " + f" Last {len(errors)} lines of error files:" + f"{error_msg}." + f"Please check {os.path.join(self._logs_dir, 'gcs_server.out')}" + f" for details. Last connection error: {last_ex}" + ) + else: + raise RuntimeError( + f"Failed to {'start' if self.head else 'connect to'} GCS. Last " + f"connection error: {last_ex}" + ) + + ray.experimental.internal_kv._initialize_internal_kv(self._gcs_client) + + def get_temp_dir_path(self): + """Get the path of the temporary directory.""" + return self._temp_dir + + def get_runtime_env_dir_path(self): + """Get the path of the runtime env.""" + return self._runtime_env_dir + + def get_session_dir_path(self): + """Get the path of the session directory.""" + return self._session_dir + + def get_logs_dir_path(self): + """Get the path of the log files directory.""" + return self._logs_dir + + def get_sockets_dir_path(self): + """Get the path of the sockets directory.""" + return self._sockets_dir + + def _make_inc_temp( + self, suffix: str = "", prefix: str = "", directory_name: Optional[str] = None + ): + """Return an incremental temporary file name. The file is not created. + + Args: + suffix: The suffix of the temp file. + prefix: The prefix of the temp file. + directory_name (str) : The base directory of the temp file. + + Returns: + A string of file name. If there existing a file having + the same name, the returned name will look like + "{directory_name}/{prefix}.{unique_index}{suffix}" + """ + if directory_name is None: + directory_name = ray._common.utils.get_ray_temp_dir() + directory_name = os.path.expanduser(directory_name) + index = self._incremental_dict[suffix, prefix, directory_name] + # `tempfile.TMP_MAX` could be extremely large, + # so using `range` in Python2.x should be avoided. + while index < tempfile.TMP_MAX: + if index == 0: + filename = os.path.join(directory_name, prefix + suffix) + else: + filename = os.path.join( + directory_name, prefix + "." + str(index) + suffix + ) + index += 1 + if not os.path.exists(filename): + # Save the index. + self._incremental_dict[suffix, prefix, directory_name] = index + return filename + + raise FileExistsError(errno.EEXIST, "No usable temporary filename found") + + def should_redirect_logs(self): + redirect_output = self._ray_params.redirect_output + if redirect_output is None: + # Fall back to stderr redirect environment variable. + redirect_output = ( + os.environ.get( + ray_constants.LOGGING_REDIRECT_STDERR_ENVIRONMENT_VARIABLE + ) + != "1" + ) + return redirect_output + + # TODO(hjiang): Re-implement the logic in C++, and expose via cython. + def get_log_file_names( + self, + name: str, + unique: bool = False, + create_out: bool = True, + create_err: bool = True, + ) -> Tuple[Optional[str], Optional[str]]: + """Get filename to dump logs for stdout and stderr, with no files opened. + If output redirection has been disabled, no files will + be opened and `(None, None)` will be returned. + + Args: + name: descriptive string for this log file. + unique: if true, a counter will be attached to `name` to + ensure the returned filename is not already used. + create_out: if True, create a .out file. + create_err: if True, create a .err file. + + Returns: + A tuple of two file handles for redirecting optional (stdout, stderr), + or `(None, None)` if output redirection is disabled. + """ + if not self.should_redirect_logs(): + return None, None + + log_stdout = None + log_stderr = None + + if create_out: + log_stdout = self._get_log_file_name(name, "out", unique=unique) + if create_err: + log_stderr = self._get_log_file_name(name, "err", unique=unique) + return log_stdout, log_stderr + + def get_log_file_handles( + self, + name: str, + unique: bool = False, + create_out: bool = True, + create_err: bool = True, + ) -> Tuple[Optional[IO[AnyStr]], Optional[IO[AnyStr]]]: + """Open log files with partially randomized filenames, returning the + file handles. If output redirection has been disabled, no files will + be opened and `(None, None)` will be returned. + + Args: + name: descriptive string for this log file. + unique: if true, a counter will be attached to `name` to + ensure the returned filename is not already used. + create_out: if True, create a .out file. + create_err: if True, create a .err file. + + Returns: + A tuple of two file handles for redirecting optional (stdout, stderr), + or `(None, None)` if output redirection is disabled. + """ + log_stdout_fname, log_stderr_fname = self.get_log_file_names( + name, unique=unique, create_out=create_out, create_err=create_err + ) + log_stdout = None if log_stdout_fname is None else open_log(log_stdout_fname) + log_stderr = None if log_stderr_fname is None else open_log(log_stderr_fname) + return log_stdout, log_stderr + + def _get_log_file_name( + self, + name: str, + suffix: str, + unique: bool = False, + ) -> str: + """Generate partially randomized filenames for log files. + + Args: + name: descriptive string for this log file. + suffix: suffix of the file. Usually it is .out of .err. + unique: if true, a counter will be attached to `name` to + ensure the returned filename is not already used. + + Returns: + A tuple of two file names for redirecting (stdout, stderr). + """ + # strip if the suffix is something like .out. + suffix = suffix.strip(".") + + if unique: + filename = self._make_inc_temp( + suffix=f".{suffix}", prefix=name, directory_name=self._logs_dir + ) + else: + filename = os.path.join(self._logs_dir, f"{name}.{suffix}") + return filename + + def _get_unused_port(self, allocated_ports=None): + if allocated_ports is None: + allocated_ports = set() + + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.bind(("", 0)) + port = s.getsockname()[1] + + # Try to generate a port that is far above the 'next available' one. + # This solves issue #8254 where GRPC fails because the port assigned + # from this method has been used by a different process. + for _ in range(ray_constants.NUM_PORT_RETRIES): + new_port = random.randint(port, 65535) + if new_port in allocated_ports: + # This port is allocated for other usage already, + # so we shouldn't use it even if it's not in use right now. + continue + new_s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + try: + new_s.bind(("", new_port)) + except OSError: + new_s.close() + continue + s.close() + new_s.close() + return new_port + logger.error("Unable to succeed in selecting a random port.") + s.close() + return port + + def _prepare_socket_file(self, socket_path: str, default_prefix: str): + """Prepare the socket file for raylet and plasma. + + This method helps to prepare a socket file. + 1. Make the directory if the directory does not exist. + 2. If the socket file exists, do nothing (this just means we aren't the + first worker on the node). + + Args: + socket_path: the socket file to prepare. + """ + result = socket_path + if sys.platform == "win32": + if socket_path is None: + result = f"tcp://{self._localhost}:{self._get_unused_port()}" + else: + if socket_path is None: + result = self._make_inc_temp( + prefix=default_prefix, directory_name=self._sockets_dir + ) + else: + try_to_create_directory(os.path.dirname(socket_path)) + + validate_socket_filepath(result.split("://", 1)[-1]) + return result + + def _get_cached_port( + self, port_name: str, default_port: Optional[int] = None + ) -> int: + """Get a port number from a cache on this node. + + Different driver processes on a node should use the same ports for + some purposes, e.g. exporting metrics. This method returns a port + number for the given port name and caches it in a file. If the + port isn't already cached, an unused port is generated and cached. + + Args: + port_name: The name of the port, e.g. metrics_export_port. + default_port: The port to return and cache if no port has already been + cached for the given port_name. If None, an unused port is generated + and cached. + + Returns: + int: The port number. + """ + file_path = os.path.join(self.get_session_dir_path(), "ports_by_node.json") + + # Make sure only the ports in RAY_CACHED_PORTS are cached. + assert port_name in ray_constants.RAY_ALLOWED_CACHED_PORTS + + # Maps a Node.unique_id to a dict that maps port names to port numbers. + ports_by_node: Dict[str, Dict[str, int]] = defaultdict(dict) + + with FileLock(file_path + ".lock"): + if not os.path.exists(file_path): + with open(file_path, "w") as f: + json.dump({}, f) + + with open(file_path, "r") as f: + ports_by_node.update(json.load(f)) + + if ( + self.unique_id in ports_by_node + and port_name in ports_by_node[self.unique_id] + ): + # The port has already been cached at this node, so use it. + port = int(ports_by_node[self.unique_id][port_name]) + else: + # Pick a new port to use and cache it at this node. + allocated_ports = set(ports_by_node[self.unique_id].values()) + + if default_port is not None and default_port in allocated_ports: + # The default port is already in use, so don't use it. + default_port = None + + port = default_port or self._get_unused_port(allocated_ports) + + ports_by_node[self.unique_id][port_name] = port + with open(file_path, "w") as f: + json.dump(ports_by_node, f) + + return port + + def _wait_and_get_for_node_address(self, timeout_s: int = 60) -> str: + """Wait until the RAY_NODE_IP_FILENAME file is avialable. + + RAY_NODE_IP_FILENAME is created when a ray instance is started. + + Args: + timeout_s: If the ip address is not found within this + timeout, it will raise ValueError. + Returns: + The node_ip_address of the current session if it finds it + within timeout_s. + """ + for i in range(timeout_s): + node_ip_address = ray._private.services.get_cached_node_ip_address( + self.get_session_dir_path() + ) + + if node_ip_address is not None: + return node_ip_address + + time.sleep(1) + if i % 10 == 0: + logger.info( + f"Can't find a `{ray_constants.RAY_NODE_IP_FILENAME}` " + f"file from {self.get_session_dir_path()}. " + "Have you started Ray instance using " + "`ray start` or `ray.init`?" + ) + + raise ValueError( + f"Can't find a `{ray_constants.RAY_NODE_IP_FILENAME}` " + f"file from {self.get_session_dir_path()}. " + f"for {timeout_s} seconds. " + "A ray instance hasn't started. " + "Did you do `ray start` or `ray.init` on this host?" + ) + + def start_reaper_process(self): + """ + Start the reaper process. + + This must be the first process spawned and should only be called when + ray processes should be cleaned up if this process dies. + """ + assert ( + not self.kernel_fate_share + ), "a reaper should not be used with kernel fate-sharing" + process_info = ray._private.services.start_reaper(fate_share=False) + assert ray_constants.PROCESS_TYPE_REAPER not in self.all_processes + if process_info is not None: + self.all_processes[ray_constants.PROCESS_TYPE_REAPER] = [ + process_info, + ] + + def start_log_monitor(self): + """Start the log monitor.""" + stdout_log_fname, stderr_log_fname = self.get_log_file_names( + "log_monitor", unique=True, create_out=True, create_err=True + ) + process_info = ray._private.services.start_log_monitor( + self.get_session_dir_path(), + self._logs_dir, + self.gcs_address, + fate_share=self.kernel_fate_share, + max_bytes=self.max_bytes, + backup_count=self.backup_count, + stdout_filepath=stdout_log_fname, + stderr_filepath=stderr_log_fname, + ) + assert ray_constants.PROCESS_TYPE_LOG_MONITOR not in self.all_processes + self.all_processes[ray_constants.PROCESS_TYPE_LOG_MONITOR] = [ + process_info, + ] + + def start_api_server( + self, *, include_dashboard: Optional[bool], raise_on_failure: bool + ): + """Start the dashboard. + + Args: + include_dashboard: If true, this will load all dashboard-related modules + when starting the API server. Otherwise, it will only + start the modules that are not relevant to the dashboard. + raise_on_failure: If true, this will raise an exception + if we fail to start the API server. Otherwise it will print + a warning if we fail to start the API server. + """ + stdout_log_fname, stderr_log_fname = self.get_log_file_names( + "dashboard", unique=True, create_out=True, create_err=True + ) + self._webui_url, process_info = ray._private.services.start_api_server( + include_dashboard, + raise_on_failure, + self._ray_params.dashboard_host, + self.gcs_address, + self.cluster_id.hex(), + self._node_ip_address, + self._temp_dir, + self._logs_dir, + self._session_dir, + port=self._ray_params.dashboard_port, + fate_share=self.kernel_fate_share, + max_bytes=self.max_bytes, + backup_count=self.backup_count, + stdout_filepath=stdout_log_fname, + stderr_filepath=stderr_log_fname, + ) + assert ray_constants.PROCESS_TYPE_DASHBOARD not in self.all_processes + if process_info is not None: + self.all_processes[ray_constants.PROCESS_TYPE_DASHBOARD] = [ + process_info, + ] + self.get_gcs_client().internal_kv_put( + b"webui:url", + self._webui_url.encode(), + True, + ray_constants.KV_NAMESPACE_DASHBOARD, + ) + + def start_gcs_server(self): + """Start the gcs server.""" + gcs_server_port = self._ray_params.gcs_server_port + assert gcs_server_port > 0 + assert self._gcs_address is None, "GCS server is already running." + assert self._gcs_client is None, "GCS client is already connected." + + stdout_log_fname, stderr_log_fname = self.get_log_file_names( + "gcs_server", unique=True, create_out=True, create_err=True + ) + process_info = ray._private.services.start_gcs_server( + self.redis_address, + log_dir=self._logs_dir, + stdout_filepath=stdout_log_fname, + stderr_filepath=stderr_log_fname, + session_name=self.session_name, + redis_username=self._ray_params.redis_username, + redis_password=self._ray_params.redis_password, + config=self._config, + fate_share=self.kernel_fate_share, + gcs_server_port=gcs_server_port, + metrics_agent_port=self._ray_params.metrics_agent_port, + node_ip_address=self._node_ip_address, + ) + assert ray_constants.PROCESS_TYPE_GCS_SERVER not in self.all_processes + self.all_processes[ray_constants.PROCESS_TYPE_GCS_SERVER] = [ + process_info, + ] + # Connecting via non-localhost address may be blocked by firewall rule, + # e.g. https://github.com/ray-project/ray/issues/15780 + # TODO(mwtian): figure out a way to use 127.0.0.1 for local connection + # when possible. + self._gcs_address = f"{self._node_ip_address}:" f"{gcs_server_port}" + + def start_raylet( + self, + plasma_directory: str, + fallback_directory: str, + object_store_memory: int, + use_valgrind: bool = False, + use_profiler: bool = False, + ): + """Start the raylet. + + Args: + use_valgrind: True if we should start the process in + valgrind. + use_profiler: True if we should start the process in the + valgrind profiler. + """ + raylet_stdout_filepath, raylet_stderr_filepath = self.get_log_file_names( + ray_constants.PROCESS_TYPE_RAYLET, + unique=True, + create_out=True, + create_err=True, + ) + ( + dashboard_agent_stdout_filepath, + dashboard_agent_stderr_filepath, + ) = self.get_log_file_names( + ray_constants.PROCESS_TYPE_DASHBOARD_AGENT, + unique=True, + create_out=True, + create_err=True, + ) + ( + runtime_env_agent_stdout_filepath, + runtime_env_agent_stderr_filepath, + ) = self.get_log_file_names( + ray_constants.PROCESS_TYPE_RUNTIME_ENV_AGENT, + unique=True, + create_out=True, + create_err=True, + ) + process_info = ray._private.services.start_raylet( + self.redis_address, + self.gcs_address, + self._node_id, + self._node_ip_address, + self._ray_params.node_manager_port, + self._raylet_socket_name, + self._plasma_store_socket_name, + self.cluster_id.hex(), + self._ray_params.worker_path, + self._ray_params.setup_worker_path, + self._temp_dir, + self._session_dir, + self._runtime_env_dir, + self._logs_dir, + self.get_resource_spec(), + plasma_directory, + fallback_directory, + object_store_memory, + self.session_name, + is_head_node=self.is_head(), + min_worker_port=self._ray_params.min_worker_port, + max_worker_port=self._ray_params.max_worker_port, + worker_port_list=self._ray_params.worker_port_list, + object_manager_port=self._ray_params.object_manager_port, + redis_username=self._ray_params.redis_username, + redis_password=self._ray_params.redis_password, + metrics_agent_port=self._ray_params.metrics_agent_port, + runtime_env_agent_port=self._ray_params.runtime_env_agent_port, + metrics_export_port=self._metrics_export_port, + dashboard_agent_listen_port=self._ray_params.dashboard_agent_listen_port, + use_valgrind=use_valgrind, + use_profiler=use_profiler, + raylet_stdout_filepath=raylet_stdout_filepath, + raylet_stderr_filepath=raylet_stderr_filepath, + dashboard_agent_stdout_filepath=dashboard_agent_stdout_filepath, + dashboard_agent_stderr_filepath=dashboard_agent_stderr_filepath, + runtime_env_agent_stdout_filepath=runtime_env_agent_stdout_filepath, + runtime_env_agent_stderr_filepath=runtime_env_agent_stderr_filepath, + huge_pages=self._ray_params.huge_pages, + fate_share=self.kernel_fate_share, + socket_to_use=None, + max_bytes=self.max_bytes, + backup_count=self.backup_count, + ray_debugger_external=self._ray_params.ray_debugger_external, + env_updates=self._ray_params.env_vars, + node_name=self._ray_params.node_name, + webui=self._webui_url, + labels=self.node_labels, + resource_isolation_config=self.resource_isolation_config, + ) + assert ray_constants.PROCESS_TYPE_RAYLET not in self.all_processes + self.all_processes[ray_constants.PROCESS_TYPE_RAYLET] = [process_info] + + def start_monitor(self): + """Start the monitor. + + Autoscaling output goes to these monitor.err/out files, and + any modification to these files may break existing + cluster launching commands. + """ + from ray.autoscaler.v2.utils import is_autoscaler_v2 + + stdout_log_fname, stderr_log_fname = self.get_log_file_names( + "monitor", unique=True, create_out=True, create_err=True + ) + process_info = ray._private.services.start_monitor( + self.gcs_address, + self._logs_dir, + stdout_filepath=stdout_log_fname, + stderr_filepath=stderr_log_fname, + autoscaling_config=self._ray_params.autoscaling_config, + fate_share=self.kernel_fate_share, + max_bytes=self.max_bytes, + backup_count=self.backup_count, + monitor_ip=self._node_ip_address, + autoscaler_v2=is_autoscaler_v2(fetch_from_server=True), + ) + assert ray_constants.PROCESS_TYPE_MONITOR not in self.all_processes + self.all_processes[ray_constants.PROCESS_TYPE_MONITOR] = [process_info] + + def start_ray_client_server(self): + """Start the ray client server process.""" + stdout_file, stderr_file = self.get_log_file_handles( + "ray_client_server", unique=True + ) + process_info = ray._private.services.start_ray_client_server( + self.address, + self._node_ip_address, + self._ray_params.ray_client_server_port, + stdout_file=stdout_file, + stderr_file=stderr_file, + redis_username=self._ray_params.redis_username, + redis_password=self._ray_params.redis_password, + fate_share=self.kernel_fate_share, + runtime_env_agent_address=self.runtime_env_agent_address, + ) + assert ray_constants.PROCESS_TYPE_RAY_CLIENT_SERVER not in self.all_processes + self.all_processes[ray_constants.PROCESS_TYPE_RAY_CLIENT_SERVER] = [ + process_info + ] + + def _write_cluster_info_to_kv(self): + """Write the cluster metadata to GCS. + Cluster metadata is always recorded, but they are + not reported unless usage report is enabled. + Check `usage_stats_head.py` for more details. + """ + # Make sure the cluster metadata wasn't reported before. + import ray._private.usage.usage_lib as ray_usage_lib + + ray_usage_lib.put_cluster_metadata( + self.get_gcs_client(), ray_init_cluster=self.ray_init_cluster + ) + # Make sure GCS is up. + added = self.get_gcs_client().internal_kv_put( + b"session_name", + self._session_name.encode(), + False, + ray_constants.KV_NAMESPACE_SESSION, + ) + if not added: + curr_val = self.get_gcs_client().internal_kv_get( + b"session_name", ray_constants.KV_NAMESPACE_SESSION + ) + assert curr_val == self._session_name.encode("utf-8"), ( + f"Session name {self._session_name} does not match " + f"persisted value {curr_val}. Perhaps there was an " + f"error connecting to Redis." + ) + + self.get_gcs_client().internal_kv_put( + b"session_dir", + self._session_dir.encode(), + True, + ray_constants.KV_NAMESPACE_SESSION, + ) + self.get_gcs_client().internal_kv_put( + b"temp_dir", + self._temp_dir.encode(), + True, + ray_constants.KV_NAMESPACE_SESSION, + ) + # Add tracing_startup_hook to redis / internal kv manually + # since internal kv is not yet initialized. + if self._ray_params.tracing_startup_hook: + self.get_gcs_client().internal_kv_put( + b"tracing_startup_hook", + self._ray_params.tracing_startup_hook.encode(), + True, + ray_constants.KV_NAMESPACE_TRACING, + ) + + def start_head_processes(self): + """Start head processes on the node.""" + logger.debug( + f"Process STDOUT and STDERR is being " f"redirected to {self._logs_dir}." + ) + assert self._gcs_address is None + assert self._gcs_client is None + + self.start_gcs_server() + assert self.get_gcs_client() is not None + self._write_cluster_info_to_kv() + + if not self._ray_params.no_monitor: + self.start_monitor() + + if self._ray_params.ray_client_server_port: + self.start_ray_client_server() + + if self._ray_params.include_dashboard is None: + # Default + raise_on_api_server_failure = False + else: + raise_on_api_server_failure = self._ray_params.include_dashboard + + self.start_api_server( + include_dashboard=self._ray_params.include_dashboard, + raise_on_failure=raise_on_api_server_failure, + ) + + def start_ray_processes(self): + """Start all of the processes on the node.""" + logger.debug( + f"Process STDOUT and STDERR is being " f"redirected to {self._logs_dir}." + ) + + if not self.head: + # Get the system config from GCS first if this is a non-head node. + gcs_options = ray._raylet.GcsClientOptions.create( + self.gcs_address, + self.cluster_id.hex(), + allow_cluster_id_nil=False, + fetch_cluster_id_if_nil=False, + ) + global_state = ray._private.state.GlobalState() + global_state._initialize_global_state(gcs_options) + new_config = global_state.get_system_config() + assert self._config.items() <= new_config.items(), ( + "The system config from GCS is not a superset of the local" + " system config. There might be a configuration inconsistency" + " issue between the head node and non-head nodes." + f" Local system config: {self._config}," + f" GCS system config: {new_config}" + ) + self._config = new_config + + # Make sure we don't call `determine_plasma_store_config` multiple + # times to avoid printing multiple warnings. + resource_spec = self.get_resource_spec() + + ( + plasma_directory, + fallback_directory, + object_store_memory, + ) = ray._private.services.determine_plasma_store_config( + resource_spec.object_store_memory, + self._temp_dir, + plasma_directory=self._ray_params.plasma_directory, + fallback_directory=self._fallback_directory, + huge_pages=self._ray_params.huge_pages, + ) + + # add plasma store memory to the total system reserved memory + if self.resource_isolation_config.is_enabled(): + self.resource_isolation_config.add_object_store_memory(object_store_memory) + + self.start_raylet(plasma_directory, fallback_directory, object_store_memory) + if self._ray_params.include_log_monitor: + self.start_log_monitor() + + def _kill_process_type( + self, + process_type, + allow_graceful: bool = False, + check_alive: bool = True, + wait: bool = False, + ): + """Kill a process of a given type. + + If the process type is PROCESS_TYPE_REDIS_SERVER, then we will kill all + of the Redis servers. + + If the process was started in valgrind, then we will raise an exception + if the process has a non-zero exit code. + + Args: + process_type: The type of the process to kill. + allow_graceful: Send a SIGTERM first and give the process + time to exit gracefully. If that doesn't work, then use + SIGKILL. We usually want to do this outside of tests. + check_alive: If true, then we expect the process to be alive + and will raise an exception if the process is already dead. + wait: If true, then this method will not return until the + process in question has exited. + + Raises: + This process raises an exception in the following cases: + 1. The process had already died and check_alive is true. + 2. The process had been started in valgrind and had a non-zero + exit code. + """ + + # Ensure thread safety + with self.removal_lock: + self._kill_process_impl( + process_type, + allow_graceful=allow_graceful, + check_alive=check_alive, + wait=wait, + ) + + def _kill_process_impl( + self, process_type, allow_graceful=False, check_alive=True, wait=False + ): + """See `_kill_process_type`.""" + if process_type not in self.all_processes: + return + process_infos = self.all_processes[process_type] + if process_type != ray_constants.PROCESS_TYPE_REDIS_SERVER: + assert len(process_infos) == 1 + for process_info in process_infos: + process = process_info.process + # Handle the case where the process has already exited. + if process.poll() is not None: + if check_alive: + raise RuntimeError( + "Attempting to kill a process of type " + f"'{process_type}', but this process is already dead." + ) + else: + continue + + if process_info.use_valgrind: + process.terminate() + process.wait() + if process.returncode != 0: + message = ( + "Valgrind detected some errors in process of " + f"type {process_type}. Error code {process.returncode}." + ) + if process_info.stdout_file is not None: + with open(process_info.stdout_file, "r") as f: + message += "\nPROCESS STDOUT:\n" + f.read() + if process_info.stderr_file is not None: + with open(process_info.stderr_file, "r") as f: + message += "\nPROCESS STDERR:\n" + f.read() + raise RuntimeError(message) + continue + + if process_info.use_valgrind_profiler: + # Give process signal to write profiler data. + os.kill(process.pid, signal.SIGINT) + # Wait for profiling data to be written. + time.sleep(0.1) + + if allow_graceful: + process.terminate() + # Allow the process one second to exit gracefully. + timeout_seconds = 1 + try: + process.wait(timeout_seconds) + except subprocess.TimeoutExpired: + pass + + # If the process did not exit, force kill it. + if process.poll() is None: + process.kill() + # The reason we usually don't call process.wait() here is that + # there's some chance we'd end up waiting a really long time. + if wait: + process.wait() + + del self.all_processes[process_type] + + def kill_redis(self, check_alive: bool = True): + """Kill the Redis servers. + + Args: + check_alive: Raise an exception if any of the processes + were already dead. + """ + self._kill_process_type( + ray_constants.PROCESS_TYPE_REDIS_SERVER, check_alive=check_alive + ) + + def kill_raylet(self, check_alive: bool = True): + """Kill the raylet. + + Args: + check_alive: Raise an exception if the process was already + dead. + """ + self._kill_process_type( + ray_constants.PROCESS_TYPE_RAYLET, check_alive=check_alive + ) + + def kill_log_monitor(self, check_alive: bool = True): + """Kill the log monitor. + + Args: + check_alive: Raise an exception if the process was already + dead. + """ + self._kill_process_type( + ray_constants.PROCESS_TYPE_LOG_MONITOR, check_alive=check_alive + ) + + def kill_dashboard(self, check_alive: bool = True): + """Kill the dashboard. + + Args: + check_alive: Raise an exception if the process was already + dead. + """ + self._kill_process_type( + ray_constants.PROCESS_TYPE_DASHBOARD, check_alive=check_alive + ) + + def kill_monitor(self, check_alive: bool = True): + """Kill the monitor. + + Args: + check_alive: Raise an exception if the process was already + dead. + """ + self._kill_process_type( + ray_constants.PROCESS_TYPE_MONITOR, check_alive=check_alive + ) + + def kill_gcs_server(self, check_alive: bool = True): + """Kill the gcs server. + + Args: + check_alive: Raise an exception if the process was already + dead. + """ + self._kill_process_type( + ray_constants.PROCESS_TYPE_GCS_SERVER, check_alive=check_alive, wait=True + ) + # Clear GCS client and address to indicate no GCS server is running. + self._gcs_address = None + self._gcs_client = None + + def kill_reaper(self, check_alive: bool = True): + """Kill the reaper process. + + Args: + check_alive: Raise an exception if the process was already + dead. + """ + self._kill_process_type( + ray_constants.PROCESS_TYPE_REAPER, check_alive=check_alive + ) + + def kill_all_processes(self, check_alive=True, allow_graceful=False, wait=False): + """Kill all of the processes. + + Note that This is slower than necessary because it calls kill, wait, + kill, wait, ... instead of kill, kill, ..., wait, wait, ... + + Args: + check_alive: Raise an exception if any of the processes were + already dead. + wait: If true, then this method will not return until the + process in question has exited. + """ + # Kill the raylet first. This is important for suppressing errors at + # shutdown because we give the raylet a chance to exit gracefully and + # clean up its child worker processes. If we were to kill the plasma + # store (or Redis) first, that could cause the raylet to exit + # ungracefully, leading to more verbose output from the workers. + if ray_constants.PROCESS_TYPE_RAYLET in self.all_processes: + self._kill_process_type( + ray_constants.PROCESS_TYPE_RAYLET, + check_alive=check_alive, + allow_graceful=allow_graceful, + wait=wait, + ) + + if ray_constants.PROCESS_TYPE_GCS_SERVER in self.all_processes: + self._kill_process_type( + ray_constants.PROCESS_TYPE_GCS_SERVER, + check_alive=check_alive, + allow_graceful=allow_graceful, + wait=wait, + ) + + # We call "list" to copy the keys because we are modifying the + # dictionary while iterating over it. + for process_type in list(self.all_processes.keys()): + # Need to kill the reaper process last in case we die unexpectedly + # while cleaning up. + if process_type != ray_constants.PROCESS_TYPE_REAPER: + self._kill_process_type( + process_type, + check_alive=check_alive, + allow_graceful=allow_graceful, + wait=wait, + ) + + if ray_constants.PROCESS_TYPE_REAPER in self.all_processes: + self._kill_process_type( + ray_constants.PROCESS_TYPE_REAPER, + check_alive=check_alive, + allow_graceful=allow_graceful, + wait=wait, + ) + + def live_processes(self): + """Return a list of the live processes. + + Returns: + A list of the live processes. + """ + result = [] + for process_type, process_infos in self.all_processes.items(): + for process_info in process_infos: + if process_info.process.poll() is None: + result.append((process_type, process_info.process)) + return result + + def dead_processes(self): + """Return a list of the dead processes. + + Note that this ignores processes that have been explicitly killed, + e.g., via a command like node.kill_raylet(). + + Returns: + A list of the dead processes ignoring the ones that have been + explicitly killed. + """ + result = [] + for process_type, process_infos in self.all_processes.items(): + for process_info in process_infos: + if process_info.process.poll() is not None: + result.append((process_type, process_info.process)) + return result + + def any_processes_alive(self): + """Return true if any processes are still alive. + + Returns: + True if any process is still alive. + """ + return any(self.live_processes()) + + def remaining_processes_alive(self): + """Return true if all remaining processes are still alive. + + Note that this ignores processes that have been explicitly killed, + e.g., via a command like node.kill_raylet(). + + Returns: + True if any process that wasn't explicitly killed is still alive. + """ + return not any(self.dead_processes()) + + def destroy_external_storage(self): + object_spilling_config = self._config.get("object_spilling_config", {}) + if object_spilling_config: + object_spilling_config = json.loads(object_spilling_config) + from ray._private import external_storage + + storage = external_storage.setup_external_storage( + object_spilling_config, self._node_id, self._session_name + ) + storage.destroy_external_storage() + + def validate_external_storage(self): + """Make sure we can setup the object spilling external storage.""" + + automatic_spilling_enabled = self._config.get( + "automatic_object_spilling_enabled", True + ) + if not automatic_spilling_enabled: + return + + object_spilling_config = self._object_spilling_config + # Try setting up the storage. + # Configure the proper system config. + # We need to set both ray param's system config and self._config + # because they could've been diverged at this point. + deserialized_config = json.loads(object_spilling_config) + self._ray_params._system_config[ + "object_spilling_config" + ] = object_spilling_config + self._config["object_spilling_config"] = object_spilling_config + + is_external_storage_type_fs = deserialized_config["type"] == "filesystem" + self._ray_params._system_config[ + "is_external_storage_type_fs" + ] = is_external_storage_type_fs + self._config["is_external_storage_type_fs"] = is_external_storage_type_fs + + # Validate external storage usage. + from ray._private import external_storage + + # Node ID is available only after GCS is connected. However, + # validate_external_storage() needs to be called before it to + # be able to validate the configs early. Therefore, we use a + # dummy node ID here and make sure external storage can be set + # up based on the provided config. This storage is destroyed + # right after the validation. + dummy_node_id = ray.NodeID.from_random().hex() + storage = external_storage.setup_external_storage( + deserialized_config, dummy_node_id, self._session_name + ) + storage.destroy_external_storage() + external_storage.reset_external_storage() + + def _get_object_spilling_config(self): + """Consolidate the object spilling config from the ray params, environment + variable, and system config. The object spilling directory specified through + ray params will override the one specified through environment variable and + system config.""" + + object_spilling_directory = self._ray_params.object_spilling_directory + if not object_spilling_directory: + object_spilling_directory = self._config.get( + "object_spilling_directory", "" + ) + + if not object_spilling_directory: + object_spilling_directory = os.environ.get( + "RAY_object_spilling_directory", "" + ) + + if object_spilling_directory: + return json.dumps( + { + "type": "filesystem", + "params": {"directory_path": object_spilling_directory}, + } + ) + + object_spilling_config = self._config.get("object_spilling_config", {}) + if not object_spilling_config: + object_spilling_config = os.environ.get("RAY_object_spilling_config", "") + + # If the config is not specified in ray params, system config or environment + # variable, we fill up the default. + if not object_spilling_config: + object_spilling_config = json.dumps( + {"type": "filesystem", "params": {"directory_path": self._session_dir}} + ) + else: + if not is_in_test(): + logger.warning( + "The object spilling config is specified from an unstable " + "API - system config or environment variable. This is " + "subject to change in the future. You can use the stable " + "API - --object-spilling-directory in ray start or " + "object_spilling_directory in ray.init() to specify the " + "object spilling directory instead. If you need more " + "advanced settings, please open a github issue with the " + "Ray team." + ) + + return object_spilling_config + + def _record_stats(self): + # This is only called when a new node is started. + # Initialize the internal kv so that the metrics can be put + from ray._private.usage.usage_lib import ( + TagKey, + record_extra_usage_tag, + record_hardware_usage, + ) + + if not ray.experimental.internal_kv._internal_kv_initialized(): + ray.experimental.internal_kv._initialize_internal_kv(self.get_gcs_client()) + assert ray.experimental.internal_kv._internal_kv_initialized() + if self.head: + # record head node stats + gcs_storage_type = ( + "redis" if os.environ.get("RAY_REDIS_ADDRESS") is not None else "memory" + ) + record_extra_usage_tag(TagKey.GCS_STORAGE, gcs_storage_type) + cpu_model_name = ray._private.utils.get_current_node_cpu_model_name() + if cpu_model_name: + # CPU model name can be an arbitrary long string + # so we truncate it to the first 50 characters + # to avoid any issues. + record_hardware_usage(cpu_model_name[:50]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/object_ref_generator.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/object_ref_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..735115ce0748c4a5884b737ace62717175e354af --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/object_ref_generator.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import collections +from typing import TYPE_CHECKING, Deque, Iterator + +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + import ray + + +@DeveloperAPI +class DynamicObjectRefGenerator: + def __init__(self, refs: Deque["ray.ObjectRef"]): + # TODO(swang): As an optimization, can also store the generator + # ObjectID so that we don't need to keep individual ref counts for the + # inner ObjectRefs. + self._refs: Deque["ray.ObjectRef"] = collections.deque(refs) + + def __iter__(self) -> Iterator("ray.ObjectRef"): + while self._refs: + yield self._refs.popleft() + + def __len__(self) -> int: + return len(self._refs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/parameter.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/parameter.py new file mode 100644 index 0000000000000000000000000000000000000000..0534ea2e34ff4dc9d5733cf8376729c488309a43 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/parameter.py @@ -0,0 +1,461 @@ +import logging +import os +from typing import Dict, List, Optional + +import ray._private.ray_constants as ray_constants +from ray._private.resource_isolation_config import ResourceIsolationConfig +from ray._private.utils import check_ray_client_dependencies_installed + +logger = logging.getLogger(__name__) + + +class RayParams: + """A class used to store the parameters used by Ray. + + Attributes: + redis_address: The address of the Redis server to connect to. If + this address is not provided, then this command will start Redis, a + raylet, a plasma store, a plasma manager, and some workers. + It will also kill these processes when Python exits. + redis_port: The port that the primary Redis shard should listen + to. If None, then it will fall back to + ray._private.ray_constants.DEFAULT_PORT, or a random port if the default is + not available. + redis_shard_ports: A list of the ports to use for the non-primary Redis + shards. If None, then it will fall back to the ports right after + redis_port, or random ports if those are not available. + num_cpus: Number of CPUs to configure the raylet with. + num_gpus: Number of GPUs to configure the raylet with. + resources: A dictionary mapping the name of a resource to the quantity + of that resource available. + labels: The key-value labels of the node. + memory: Total available memory for workers requesting memory. + object_store_memory: The amount of memory (in bytes) to start the + object store with. + object_manager_port int: The port to use for the object manager. + node_manager_port: The port to use for the node manager. + gcs_server_port: The port to use for the GCS server. + node_ip_address: The IP address of the node that we are on. + raylet_ip_address: The IP address of the raylet that this node + connects to. + min_worker_port: The lowest port number that workers will bind + on. If not set or set to 0, random ports will be chosen. + max_worker_port: The highest port number that workers will bind + on. If set, min_worker_port must also be set. + worker_port_list: An explicit list of ports to be used for + workers (comma-separated). Overrides min_worker_port and + max_worker_port. + ray_client_server_port: The port number the ray client server + will bind on. If not set, the ray client server will not + be started. + redirect_output: True if stdout and stderr for non-worker + processes should be redirected to files and false otherwise. + external_addresses: The address of external Redis server to + connect to, in format of "ip1:port1,ip2:port2,...". If this + address is provided, then ray won't start Redis instances in the + head node but use external Redis server(s) instead. + num_redis_shards: The number of Redis shards to start in addition to + the primary Redis shard. + redis_max_clients: If provided, attempt to configure Redis with this + maxclients number. + redis_username: Prevents external clients without the username + from connecting to Redis if provided. + redis_password: Prevents external clients without the password + from connecting to Redis if provided. + plasma_directory: A directory where the Plasma memory mapped files will + be created. + object_spilling_directory: The path to spill objects to. The same path will + be used as the object store fallback directory as well. + worker_path: The path of the source code that will be run by the + worker. + setup_worker_path: The path of the Python file that will set up + the environment for the worker process. + huge_pages: Boolean flag indicating whether to start the Object + Store with hugetlbfs support. Requires plasma_directory. + include_dashboard: Boolean flag indicating whether to start the web + UI, which displays the status of the Ray cluster. If this value is + None, then the UI will be started if the relevant dependencies are + present. + dashboard_host: The host to bind the web UI server to. Can either be + localhost (127.0.0.1) or 0.0.0.0 (available from all interfaces). + By default, this is set to localhost to prevent access from + external machines. + dashboard_port: The port to bind the dashboard server to. + Defaults to 8265. + dashboard_agent_listen_port: The port for dashboard agents to listen on + for HTTP requests. + Defaults to 52365. + runtime_env_agent_port: The port at which the runtime env agent + listens to for HTTP. + Defaults to random available port. + plasma_store_socket_name: If provided, it specifies the socket + name used by the plasma store. + raylet_socket_name: If provided, it specifies the socket path + used by the raylet process. + temp_dir: If provided, it will specify the root temporary + directory for the Ray process. Must be an absolute path. + runtime_env_dir_name: If provided, specifies the directory that + will be created in the session dir to hold runtime_env files. + include_log_monitor: If True, then start a log monitor to + monitor the log files for all processes on this node and push their + contents to Redis. + autoscaling_config: path to autoscaling config file. + metrics_agent_port: The port to bind metrics agent. + metrics_export_port: The port at which metrics are exposed + through a Prometheus endpoint. + no_monitor: If True, the ray autoscaler monitor for this cluster + will not be started. + _system_config: Configuration for overriding RayConfig + defaults. Used to set system configuration and for experimental Ray + core feature flags. + enable_object_reconstruction: Enable plasma reconstruction on + failure. + ray_debugger_external: If true, make the Ray debugger for a + worker available externally to the node it is running on. This will + bind on 0.0.0.0 instead of localhost. + env_vars: Override environment variables for the raylet. + session_name: The name of the session of the ray cluster. + webui: The url of the UI. + cluster_id: The cluster ID in hex string. + resource_isolation_config: settings for cgroupv2 based isolation of ray + system processes (defaults to no isolation if config not provided) + """ + + def __init__( + self, + redis_address: Optional[str] = None, + gcs_address: Optional[str] = None, + num_cpus: Optional[int] = None, + num_gpus: Optional[int] = None, + resources: Optional[Dict[str, float]] = None, + labels: Optional[Dict[str, str]] = None, + memory: Optional[float] = None, + object_store_memory: Optional[float] = None, + redis_port: Optional[int] = None, + redis_shard_ports: Optional[List[int]] = None, + object_manager_port: Optional[int] = None, + node_manager_port: int = 0, + gcs_server_port: Optional[int] = None, + node_ip_address: Optional[str] = None, + node_name: Optional[str] = None, + raylet_ip_address: Optional[str] = None, + min_worker_port: Optional[int] = None, + max_worker_port: Optional[int] = None, + worker_port_list: Optional[List[int]] = None, + ray_client_server_port: Optional[int] = None, + driver_mode=None, + redirect_output: Optional[bool] = None, + external_addresses: Optional[List[str]] = None, + num_redis_shards: Optional[int] = None, + redis_max_clients: Optional[int] = None, + redis_username: Optional[str] = ray_constants.REDIS_DEFAULT_USERNAME, + redis_password: Optional[str] = ray_constants.REDIS_DEFAULT_PASSWORD, + plasma_directory: Optional[str] = None, + object_spilling_directory: Optional[str] = None, + worker_path: Optional[str] = None, + setup_worker_path: Optional[str] = None, + huge_pages: Optional[bool] = False, + include_dashboard: Optional[bool] = None, + dashboard_host: Optional[str] = ray_constants.DEFAULT_DASHBOARD_IP, + dashboard_port: Optional[bool] = ray_constants.DEFAULT_DASHBOARD_PORT, + dashboard_agent_listen_port: Optional[ + int + ] = ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT, + runtime_env_agent_port: Optional[int] = None, + plasma_store_socket_name: Optional[str] = None, + raylet_socket_name: Optional[str] = None, + temp_dir: Optional[str] = None, + runtime_env_dir_name: Optional[str] = None, + include_log_monitor: Optional[str] = None, + autoscaling_config: Optional[str] = None, + ray_debugger_external: bool = False, + _system_config: Optional[Dict[str, str]] = None, + enable_object_reconstruction: Optional[bool] = False, + metrics_agent_port: Optional[int] = None, + metrics_export_port: Optional[int] = None, + tracing_startup_hook=None, + no_monitor: Optional[bool] = False, + env_vars: Optional[Dict[str, str]] = None, + session_name: Optional[str] = None, + webui: Optional[str] = None, + cluster_id: Optional[str] = None, + node_id: Optional[str] = None, + resource_isolation_config: Optional[ResourceIsolationConfig] = None, + ): + self.redis_address = redis_address + self.gcs_address = gcs_address + self.num_cpus = num_cpus + self.num_gpus = num_gpus + self.memory = memory + self.object_store_memory = object_store_memory + self.resources = resources + self.redis_port = redis_port + self.redis_shard_ports = redis_shard_ports + self.object_manager_port = object_manager_port + self.node_manager_port = node_manager_port + self.gcs_server_port = gcs_server_port + self.node_ip_address = node_ip_address + self.node_name = node_name + self.raylet_ip_address = raylet_ip_address + self.min_worker_port = min_worker_port + self.max_worker_port = max_worker_port + self.worker_port_list = worker_port_list + self.ray_client_server_port = ray_client_server_port + self.driver_mode = driver_mode + self.redirect_output = redirect_output + self.external_addresses = external_addresses + self.num_redis_shards = num_redis_shards + self.redis_max_clients = redis_max_clients + self.redis_username = redis_username + self.redis_password = redis_password + self.plasma_directory = plasma_directory + self.object_spilling_directory = object_spilling_directory + self.worker_path = worker_path + self.setup_worker_path = setup_worker_path + self.huge_pages = huge_pages + self.include_dashboard = include_dashboard + self.dashboard_host = dashboard_host + self.dashboard_port = dashboard_port + self.dashboard_agent_listen_port = dashboard_agent_listen_port + self.runtime_env_agent_port = runtime_env_agent_port + self.plasma_store_socket_name = plasma_store_socket_name + self.raylet_socket_name = raylet_socket_name + self.temp_dir = temp_dir + self.runtime_env_dir_name = ( + runtime_env_dir_name or ray_constants.DEFAULT_RUNTIME_ENV_DIR_NAME + ) + self.include_log_monitor = include_log_monitor + self.autoscaling_config = autoscaling_config + self.metrics_agent_port = metrics_agent_port + self.metrics_export_port = metrics_export_port + self.tracing_startup_hook = tracing_startup_hook + self.no_monitor = no_monitor + self.ray_debugger_external = ray_debugger_external + self.env_vars = env_vars + self.session_name = session_name + self.webui = webui + self._system_config = _system_config or {} + self._enable_object_reconstruction = enable_object_reconstruction + self.labels = labels + self._check_usage() + self.cluster_id = cluster_id + self.node_id = node_id + + self.resource_isolation_config = resource_isolation_config + if not self.resource_isolation_config: + self.resource_isolation_config = ResourceIsolationConfig( + enable_resource_isolation=False + ) + + # Set the internal config options for object reconstruction. + if enable_object_reconstruction: + # Turn off object pinning. + if self._system_config is None: + self._system_config = dict() + print(self._system_config) + self._system_config["lineage_pinning_enabled"] = True + + def update(self, **kwargs): + """Update the settings according to the keyword arguments. + + Args: + kwargs: The keyword arguments to set corresponding fields. + """ + for arg in kwargs: + if hasattr(self, arg): + setattr(self, arg, kwargs[arg]) + else: + raise ValueError(f"Invalid RayParams parameter in update: {arg}") + + self._check_usage() + + def update_if_absent(self, **kwargs): + """Update the settings when the target fields are None. + + Args: + kwargs: The keyword arguments to set corresponding fields. + """ + for arg in kwargs: + if hasattr(self, arg): + if getattr(self, arg) is None: + setattr(self, arg, kwargs[arg]) + else: + raise ValueError( + f"Invalid RayParams parameter in update_if_absent: {arg}" + ) + + self._check_usage() + + def update_pre_selected_port(self): + """Update the pre-selected port information + + Returns: + The dictionary mapping of component -> ports. + """ + + def wrap_port(port): + # 0 port means select a random port for the grpc server. + if port is None or port == 0: + return [] + else: + return [port] + + # Create a dictionary of the component -> port mapping. + pre_selected_ports = { + "gcs": wrap_port(self.redis_port), + "object_manager": wrap_port(self.object_manager_port), + "node_manager": wrap_port(self.node_manager_port), + "gcs_server": wrap_port(self.gcs_server_port), + "client_server": wrap_port(self.ray_client_server_port), + "dashboard": wrap_port(self.dashboard_port), + "dashboard_agent_grpc": wrap_port(self.metrics_agent_port), + "dashboard_agent_http": wrap_port(self.dashboard_agent_listen_port), + "runtime_env_agent": wrap_port(self.runtime_env_agent_port), + "metrics_export": wrap_port(self.metrics_export_port), + } + redis_shard_ports = self.redis_shard_ports + if redis_shard_ports is None: + redis_shard_ports = [] + pre_selected_ports["redis_shards"] = redis_shard_ports + if self.worker_port_list is None: + if self.min_worker_port is not None and self.max_worker_port is not None: + pre_selected_ports["worker_ports"] = list( + range(self.min_worker_port, self.max_worker_port + 1) + ) + else: + # The dict is not updated when it requires random ports. + pre_selected_ports["worker_ports"] = [] + else: + pre_selected_ports["worker_ports"] = [ + int(port) for port in self.worker_port_list.split(",") + ] + + # Update the pre selected port set. + self.reserved_ports = set() + for comp, port_list in pre_selected_ports.items(): + for port in port_list: + if port in self.reserved_ports: + raise ValueError( + f"Ray component {comp} is trying to use " + f"a port number {port} that is used by other components.\n" + f"Port information: {self._format_ports(pre_selected_ports)}\n" + "If you allocate ports, please make sure the same port " + "is not used by multiple components." + ) + self.reserved_ports.add(port) + + def _check_usage(self): + if self.worker_port_list is not None: + for port_str in self.worker_port_list.split(","): + try: + port = int(port_str) + except ValueError as e: + raise ValueError( + "worker_port_list must be a comma-separated " + f"list of integers: {e}" + ) from None + + if port < 1024 or port > 65535: + raise ValueError( + "Ports in worker_port_list must be " + f"between 1024 and 65535. Got: {port}" + ) + + # Used primarily for testing. + if os.environ.get("RAY_USE_RANDOM_PORTS", False): + if self.min_worker_port is None and self.max_worker_port is None: + self.min_worker_port = 0 + self.max_worker_port = 0 + + if self.min_worker_port is not None: + if self.min_worker_port != 0 and ( + self.min_worker_port < 1024 or self.min_worker_port > 65535 + ): + raise ValueError( + "min_worker_port must be 0 or an integer between 1024 and 65535." + ) + + if self.max_worker_port is not None: + if self.min_worker_port is None: + raise ValueError( + "If max_worker_port is set, min_worker_port must also be set." + ) + elif self.max_worker_port != 0: + if self.max_worker_port < 1024 or self.max_worker_port > 65535: + raise ValueError( + "max_worker_port must be 0 or an integer between " + "1024 and 65535." + ) + elif self.max_worker_port <= self.min_worker_port: + raise ValueError( + "max_worker_port must be higher than min_worker_port." + ) + if self.ray_client_server_port is not None: + if not check_ray_client_dependencies_installed(): + raise ValueError( + "Ray Client requires pip package `ray[client]`. " + "If you installed the minimal Ray (e.g. `pip install ray`), " + "please reinstall by executing `pip install ray[client]`." + ) + if ( + self.ray_client_server_port < 1024 + or self.ray_client_server_port > 65535 + ): + raise ValueError( + "ray_client_server_port must be an integer " + "between 1024 and 65535." + ) + if self.runtime_env_agent_port is not None: + if ( + self.runtime_env_agent_port < 1024 + or self.runtime_env_agent_port > 65535 + ): + raise ValueError( + "runtime_env_agent_port must be an integer " + "between 1024 and 65535." + ) + + if self.resources is not None: + + def build_error(resource, alternative): + return ( + f"{self.resources} -> `{resource}` cannot be a " + "custom resource because it is one of the default resources " + f"({ray_constants.DEFAULT_RESOURCES}). " + f"Use `{alternative}` instead. For example, use `ray start " + f"--{alternative.replace('_', '-')}=1` instead of " + f"`ray start --resources={{'{resource}': 1}}`" + ) + + assert "CPU" not in self.resources, build_error("CPU", "num_cpus") + assert "GPU" not in self.resources, build_error("GPU", "num_gpus") + assert "memory" not in self.resources, build_error("memory", "memory") + assert "object_store_memory" not in self.resources, build_error( + "object_store_memory", "object_store_memory" + ) + + if self.redirect_output is not None: + raise DeprecationWarning("The redirect_output argument is deprecated.") + + if self.temp_dir is not None and not os.path.isabs(self.temp_dir): + raise ValueError("temp_dir must be absolute path or None.") + + def _format_ports(self, pre_selected_ports): + """Format the pre-selected ports information to be more human-readable.""" + ports = pre_selected_ports.copy() + + for comp, port_list in ports.items(): + if len(port_list) == 1: + ports[comp] = port_list[0] + elif len(port_list) == 0: + # Nothing is selected, meaning it will be randomly selected. + ports[comp] = "random" + elif comp == "worker_ports": + min_port = port_list[0] + max_port = port_list[len(port_list) - 1] + if len(port_list) < 50: + port_range_str = str(port_list) + else: + port_range_str = f"from {min_port} to {max_port}" + ports[comp] = f"{len(port_list)} ports {port_range_str}" + return ports diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/path_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/path_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0e432a3b67af4554d70add15ff21b474b72f6080 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/path_utils.py @@ -0,0 +1,32 @@ +import pathlib +import urllib + +"""Cross-platform utilities for manipulating paths and URIs. + +NOTE: All functions in this file must support POSIX and Windows. +""" + + +def is_path(path_or_uri: str) -> bool: + """Returns True if uri_or_path is a path and False otherwise. + + Windows paths start with a drive name which can be interpreted as + a URI scheme by urlparse and thus needs to be treated differently + form POSIX paths. + + E.g. Creating a directory returns the path 'C:\\Users\\mp5n6ul72w\\working_dir' + will have the scheme 'C:'. + """ + if not isinstance(path_or_uri, str): + raise TypeError(f" path_or_uri must be a string, got {type(path_or_uri)}.") + + parsed_path = pathlib.Path(path_or_uri) + parsed_uri = urllib.parse.urlparse(path_or_uri) + + if isinstance(parsed_path, pathlib.PurePosixPath): + return not parsed_uri.scheme + elif isinstance(parsed_path, pathlib.PureWindowsPath): + return parsed_uri.scheme == parsed_path.drive.strip(":").lower() + else: + # this should never happen. + raise TypeError(f"Unsupported path type: {type(parsed_path).__name__}") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/process_watcher.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/process_watcher.py new file mode 100644 index 0000000000000000000000000000000000000000..6dd5c7df36bcf33b1c95681d0132d7d21e2fe486 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/process_watcher.py @@ -0,0 +1,197 @@ +import asyncio +import io +import logging +import os +import sys +from concurrent.futures import ThreadPoolExecutor + +import ray +import ray._private.ray_constants as ray_constants +import ray.dashboard.consts as dashboard_consts +from ray._common.utils import run_background_task +from ray._raylet import GcsClient +from ray.dashboard.consts import _PARENT_DEATH_THREASHOLD + +# Import psutil after ray so the packaged version is used. +import psutil + +logger = logging.getLogger(__name__) + +# TODO: move all consts from dashboard_consts to ray_constants and rename to remove +# DASHBOARD_ prefixes. + +# Publishes at most this number of lines of Raylet logs, when the Raylet dies +# unexpectedly. +_RAYLET_LOG_MAX_PUBLISH_LINES = 20 + +# Reads at most this amount of Raylet logs from the tail, for publishing and +# checking if the Raylet was terminated gracefully. +_RAYLET_LOG_MAX_TAIL_SIZE = 1 * 1024**2 + +try: + create_task = asyncio.create_task +except AttributeError: + create_task = asyncio.ensure_future + + +def get_raylet_pid(): + # TODO(edoakes): RAY_RAYLET_PID isn't properly set on Windows. This is + # only used for fate-sharing with the raylet and we need a different + # fate-sharing mechanism for Windows anyways. + if sys.platform in ["win32", "cygwin"]: + return None + raylet_pid = int(os.environ["RAY_RAYLET_PID"]) + assert raylet_pid > 0 + logger.info("raylet pid is %s", raylet_pid) + return raylet_pid + + +def create_check_raylet_task(log_dir, gcs_client, parent_dead_callback, loop): + """ + Creates an asyncio task to periodically check if the raylet process is still + running. If raylet is dead for _PARENT_DEATH_THREASHOLD (5) times, prepare to exit + as follows: + + - Write logs about whether the raylet exit is graceful, by looking into the raylet + log and search for term "SIGTERM", + - Flush the logs via GcsClient, + - Exit. + """ + if sys.platform in ["win32", "cygwin"]: + raise RuntimeError("can't check raylet process in Windows.") + raylet_pid = get_raylet_pid() + + if dashboard_consts.PARENT_HEALTH_CHECK_BY_PIPE: + logger.info("check_parent_via_pipe") + check_parent_task = _check_parent_via_pipe( + log_dir, gcs_client, loop, parent_dead_callback + ) + else: + logger.info("_check_parent") + check_parent_task = _check_parent( + raylet_pid, log_dir, gcs_client, parent_dead_callback + ) + + return run_background_task(check_parent_task) + + +def report_raylet_error_logs(log_dir: str, gcs_client: GcsClient): + log_path = os.path.join(log_dir, "raylet.out") + error = False + msg = "Raylet is terminated. " + try: + with open(log_path, "r", encoding="utf-8") as f: + # Seek to _RAYLET_LOG_MAX_TAIL_SIZE from the end if the + # file is larger than that. + f.seek(0, io.SEEK_END) + pos = max(0, f.tell() - _RAYLET_LOG_MAX_TAIL_SIZE) + f.seek(pos, io.SEEK_SET) + # Read remaining logs by lines. + raylet_logs = f.readlines() + # Assume the SIGTERM message must exist within the last + # _RAYLET_LOG_MAX_TAIL_SIZE of the log file. + if any("Raylet received SIGTERM" in line for line in raylet_logs): + msg += "Termination is graceful." + logger.info(msg) + else: + msg += ( + "Termination is unexpected. Possible reasons " + "include: (1) SIGKILL by the user or system " + "OOM killer, (2) Invalid memory access from " + "Raylet causing SIGSEGV or SIGBUS, " + "(3) Other termination signals. " + f"Last {_RAYLET_LOG_MAX_PUBLISH_LINES} lines " + "of the Raylet logs:\n" + ) + msg += " " + " ".join( + raylet_logs[-_RAYLET_LOG_MAX_PUBLISH_LINES:] + ) + error = True + except Exception as e: + msg += f"Failed to read Raylet logs at {log_path}: {e}!" + logger.exception(msg) + error = True + if error: + logger.error(msg) + # TODO: switch to async if necessary. + ray._private.utils.publish_error_to_driver( + ray_constants.RAYLET_DIED_ERROR, + msg, + gcs_client=gcs_client, + ) + else: + logger.info(msg) + + +async def _check_parent_via_pipe( + log_dir: str, gcs_client: GcsClient, loop, parent_dead_callback +): + while True: + try: + # Read input asynchronously. + # The parent (raylet) should have redirected its pipe + # to stdin. If we read 0 bytes from stdin, it means + # the process is dead. + with ThreadPoolExecutor(max_workers=1) as executor: + input_data = await loop.run_in_executor( + executor, lambda: sys.stdin.readline() + ) + if len(input_data) == 0: + # cannot read bytes from parent == parent is dead. + parent_dead_callback("_check_parent_via_pipe: The parent is dead.") + report_raylet_error_logs(log_dir, gcs_client) + sys.exit(0) + except Exception as e: + logger.exception( + "raylet health checking is failed. " + f"The agent process may leak. Exception: {e}" + ) + + +async def _check_parent(raylet_pid, log_dir, gcs_client, parent_dead_callback): + """Check if raylet is dead and fate-share if it is.""" + try: + curr_proc = psutil.Process() + parent_death_cnt = 0 + while True: + parent = curr_proc.parent() + # If the parent is dead, it is None. + parent_gone = parent is None + init_assigned_for_parent = False + parent_changed = False + + if parent: + # Sometimes, the parent is changed to the `init` process. + # In this case, the parent.pid is 1. + init_assigned_for_parent = parent.pid == 1 + # Sometimes, the parent is dead, and the pid is reused + # by other processes. In this case, this condition is triggered. + parent_changed = raylet_pid != parent.pid + + if parent_gone or init_assigned_for_parent or parent_changed: + parent_death_cnt += 1 + logger.warning( + f"Raylet is considered dead {parent_death_cnt} X. " + f"If it reaches to {_PARENT_DEATH_THREASHOLD}, the agent " + f"will kill itself. Parent: {parent}, " + f"parent_gone: {parent_gone}, " + f"init_assigned_for_parent: {init_assigned_for_parent}, " + f"parent_changed: {parent_changed}." + ) + if parent_death_cnt < _PARENT_DEATH_THREASHOLD: + await asyncio.sleep( + dashboard_consts.DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S + ) + continue + + parent_dead_callback("_check_parent: The parent is dead.") + report_raylet_error_logs(log_dir, gcs_client) + sys.exit(0) + else: + parent_death_cnt = 0 + await asyncio.sleep( + dashboard_consts.DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S + ) + except Exception: + logger.exception("Failed to check parent PID, exiting.") + sys.exit(1) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/profiling.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/profiling.py new file mode 100644 index 0000000000000000000000000000000000000000..ca55aad62ed5f2d5a30727b837769942dc5dba0e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/profiling.py @@ -0,0 +1,240 @@ +import json +import os +from collections import defaultdict +from dataclasses import asdict, dataclass +from typing import Dict, List, Union + +import ray + + +class _NullLogSpan: + """A log span context manager that does nothing""" + + def __enter__(self): + pass + + def __exit__(self, type, value, tb): + pass + + +PROFILING_ENABLED = "RAY_PROFILING" in os.environ +NULL_LOG_SPAN = _NullLogSpan() + +# Colors are specified at +# https://github.com/catapult-project/catapult/blob/master/tracing/tracing/base/color_scheme.html. # noqa: E501 +_default_color_mapping = defaultdict( + lambda: "generic_work", + { + "worker_idle": "cq_build_abandoned", + "task": "rail_response", + "task:deserialize_arguments": "rail_load", + "task:execute": "rail_animation", + "task:store_outputs": "rail_idle", + "wait_for_function": "detailed_memory_dump", + "ray.get": "good", + "ray.put": "terrible", + "ray.wait": "vsync_highlight_color", + "submit_task": "background_memory_dump", + "fetch_and_run_function": "detailed_memory_dump", + "register_remote_function": "detailed_memory_dump", + }, +) + + +@dataclass(init=True) +class ChromeTracingCompleteEvent: + # https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.lpfof2aylapb # noqa + # The event categories. This is a comma separated list of categories + # for the event. The categories can be used to hide events in + # the Trace Viewer UI. + cat: str + # The string displayed on the event. + name: str + # The identifier for the group of rows that the event + # appears in. + pid: int + # The identifier for the row that the event appears in. + tid: int + # The start time in microseconds. + ts: int + # The duration in microseconds. + dur: int + # This is the name of the color to display the box in. + cname: str + # The extra user-defined data. + args: Dict[str, Union[str, int]] + # The event type (X means the complete event). + ph: str = "X" + + +@dataclass(init=True) +class ChromeTracingMetadataEvent: + # https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#bookmark=id.iycbnb4z7i9g # noqa + name: str + # Metadata arguments. E.g., name: + args: Dict[str, str] + # The process id of this event. In Ray, pid indicates the node. + pid: int + # The thread id of this event. In Ray, tid indicates each worker. + tid: int = None + # M means the metadata event. + ph: str = "M" + + +def profile(event_type, extra_data=None): + """Profile a span of time so that it appears in the timeline visualization. + + Note that this only works in the raylet code path. + + This function can be used as follows (both on the driver or within a task). + + .. testcode:: + import ray._private.profiling as profiling + + with profiling.profile("custom event", extra_data={'key': 'val'}): + # Do some computation here. + x = 1 * 2 + + Optionally, a dictionary can be passed as the "extra_data" argument, and + it can have keys "name" and "cname" if you want to override the default + timeline display text and box color. Other values will appear at the bottom + of the chrome tracing GUI when you click on the box corresponding to this + profile span. + + Args: + event_type: A string describing the type of the event. + extra_data: This must be a dictionary mapping strings to strings. This + data will be added to the json objects that are used to populate + the timeline, so if you want to set a particular color, you can + simply set the "cname" attribute to an appropriate color. + Similarly, if you set the "name" attribute, then that will set the + text displayed on the box in the timeline. + + Returns: + An object that can profile a span of time via a "with" statement. + """ + if not PROFILING_ENABLED: + return NULL_LOG_SPAN + worker = ray._private.worker.global_worker + if worker.mode == ray._private.worker.LOCAL_MODE: + return NULL_LOG_SPAN + return worker.core_worker.profile_event(event_type.encode("ascii"), extra_data) + + +def chrome_tracing_dump( + tasks: List[dict], +) -> str: + """Generate a chrome/perfetto tracing dump using task events. + + Args: + tasks: List of tasks generated by a state API list_tasks(detail=True). + + Returns: + Json serialized dump to create a chrome/perfetto tracing. + """ + # All events from given tasks. + all_events = [] + + # Chrome tracing doesn't have a concept of "node". Instead, we use + # chrome tracing's pid == ray's node. + # chrome tracing's tid == ray's process. + # Note that pid or tid is usually integer, but ray's node/process has + # ids in string. + # Unfortunately, perfetto doesn't allow to have string as a value of pid/tid. + # To workaround it, we use Metadata event from chrome tracing schema + # (https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.xqopa5m0e28f) # noqa + # which allows pid/tid -> name mapping. In order to use this schema + # we build node_ip/(node_ip, worker_id) -> arbitrary index mapping. + + # node ip address -> node idx. + node_to_index = {} + # Arbitrary index mapped to the ip address. + node_idx = 0 + # (node index, worker id) -> worker idx + worker_to_index = {} + # Arbitrary index mapped to the (node index, worker id). + worker_idx = 0 + + for task in tasks: + profiling_data = task.get("profiling_data", []) + if profiling_data: + node_ip_address = profiling_data["node_ip_address"] + component_events = profiling_data["events"] + component_type = profiling_data["component_type"] + component_id = component_type + ":" + profiling_data["component_id"] + + if component_type not in ["worker", "driver"]: + continue + + for event in component_events: + extra_data = event["extra_data"] + # Propagate extra data. + extra_data["task_id"] = task["task_id"] + extra_data["job_id"] = task["job_id"] + extra_data["attempt_number"] = task["attempt_number"] + extra_data["func_or_class_name"] = task["func_or_class_name"] + extra_data["actor_id"] = task["actor_id"] + event_name = event["event_name"] + + # build a id -> arbitrary index mapping + if node_ip_address not in node_to_index: + node_to_index[node_ip_address] = node_idx + # Whenever new node ip is introduced, we increment the index. + node_idx += 1 + + if ( + node_to_index[node_ip_address], + component_id, + ) not in worker_to_index: # noqa + worker_to_index[ + (node_to_index[node_ip_address], component_id) + ] = worker_idx # noqa + worker_idx += 1 + + # Modify the name with the additional user-defined extra data. + cname = _default_color_mapping[event["event_name"]] + name = event_name + + if "cname" in extra_data: + cname = _default_color_mapping[event["extra_data"]["cname"]] + if "name" in extra_data: + name = extra_data["name"] + + new_event = ChromeTracingCompleteEvent( + cat=event_name, + name=name, + pid=node_to_index[node_ip_address], + tid=worker_to_index[(node_to_index[node_ip_address], component_id)], + ts=event["start_time"] * 1e3, + dur=(event["end_time"] * 1e3) - (event["start_time"] * 1e3), + cname=cname, + args=extra_data, + ) + all_events.append(asdict(new_event)) + + for node, i in node_to_index.items(): + all_events.append( + asdict( + ChromeTracingMetadataEvent( + name="process_name", + pid=i, + args={"name": f"Node {node}"}, + ) + ) + ) + + for worker, i in worker_to_index.items(): + all_events.append( + asdict( + ChromeTracingMetadataEvent( + name="thread_name", + ph="M", + tid=i, + pid=worker[0], + args={"name": worker[1]}, + ) + ) + ) + + # Handle task event disabled. + return json.dumps(all_events) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/prometheus_exporter.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/prometheus_exporter.py new file mode 100644 index 0000000000000000000000000000000000000000..c60b764a95b1e2803868a372ff855f3490d2ba1a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/prometheus_exporter.py @@ -0,0 +1,363 @@ +# NOTE: This file has been copied from OpenCensus Python exporter. +# It is because OpenCensus Prometheus exporter hasn't released for a while +# and the latest version has a compatibility issue with the latest OpenCensus +# library. + +import logging +import re + +from opencensus.common.transports import sync +from opencensus.stats import aggregation_data as aggregation_data_module, base_exporter +from prometheus_client import start_http_server +from prometheus_client.core import ( + REGISTRY, + CounterMetricFamily, + GaugeMetricFamily, + HistogramMetricFamily, + UnknownMetricFamily, +) + +logger = logging.getLogger(__name__) + + +class Options(object): + """Options contains options for configuring the exporter. + The address can be empty as the prometheus client will + assume it's localhost + :type namespace: str + :param namespace: The prometheus namespace to be used. Defaults to ''. + :type port: int + :param port: The Prometheus port to be used. Defaults to 8000. + :type address: str + :param address: The Prometheus address to be used. Defaults to ''. + :type registry: registry + :param registry: The Prometheus address to be used. Defaults to ''. + :type registry: :class:`~prometheus_client.core.CollectorRegistry` + :param registry: A Prometheus collector registry instance. + """ + + def __init__(self, namespace="", port=8000, address="", registry=REGISTRY): + self._namespace = namespace + self._registry = registry + self._port = int(port) + self._address = address + + @property + def registry(self): + """Prometheus Collector Registry instance""" + return self._registry + + @property + def namespace(self): + """Prefix to be used with view name""" + return self._namespace + + @property + def port(self): + """Port number to listen""" + return self._port + + @property + def address(self): + """Endpoint address (default is localhost)""" + return self._address + + +class Collector(object): + """Collector represents the Prometheus Collector object""" + + def __init__(self, options=Options(), view_name_to_data_map=None): + if view_name_to_data_map is None: + view_name_to_data_map = {} + self._options = options + self._registry = options.registry + self._view_name_to_data_map = view_name_to_data_map + self._registered_views = {} + + @property + def options(self): + """Options to be used to configure the exporter""" + return self._options + + @property + def registry(self): + """Prometheus Collector Registry instance""" + return self._registry + + @property + def view_name_to_data_map(self): + """Map with all view data objects + that will be sent to Prometheus + """ + return self._view_name_to_data_map + + @property + def registered_views(self): + """Map with all registered views""" + return self._registered_views + + def register_view(self, view): + """register_view will create the needed structure + in order to be able to sent all data to Prometheus + """ + v_name = get_view_name(self.options.namespace, view) + + if v_name not in self.registered_views: + desc = { + "name": v_name, + "documentation": view.description, + "labels": list(map(sanitize, view.columns)), + "units": view.measure.unit, + } + self.registered_views[v_name] = desc + + def add_view_data(self, view_data): + """Add view data object to be sent to server""" + self.register_view(view_data.view) + v_name = get_view_name(self.options.namespace, view_data.view) + self.view_name_to_data_map[v_name] = view_data + + # TODO: add start and end timestamp + def to_metric(self, desc, tag_values, agg_data, metrics_map): + """to_metric translate the data that OpenCensus create + to Prometheus format, using Prometheus Metric object + :type desc: dict + :param desc: The map that describes view definition + :type tag_values: tuple of :class: + `~opencensus.tags.tag_value.TagValue` + :param object of opencensus.tags.tag_value.TagValue: + TagValue object used as label values + :type agg_data: object of :class: + `~opencensus.stats.aggregation_data.AggregationData` + :param object of opencensus.stats.aggregation_data.AggregationData: + Aggregated data that needs to be converted as Prometheus samples + :rtype: :class:`~prometheus_client.core.CounterMetricFamily` or + :class:`~prometheus_client.core.HistogramMetricFamily` or + :class:`~prometheus_client.core.UnknownMetricFamily` or + :class:`~prometheus_client.core.GaugeMetricFamily` + """ + metric_name = desc["name"] + metric_description = desc["documentation"] + label_keys = desc["labels"] + metric_units = desc["units"] + assert len(tag_values) == len(label_keys), (tag_values, label_keys) + # Prometheus requires that all tag values be strings hence + # the need to cast none to the empty string before exporting. See + # https://github.com/census-instrumentation/opencensus-python/issues/480 + tag_values = [tv if tv else "" for tv in tag_values] + + if isinstance(agg_data, aggregation_data_module.CountAggregationData): + metric = metrics_map.get(metric_name) + if not metric: + metric = CounterMetricFamily( + name=metric_name, + documentation=metric_description, + unit=metric_units, + labels=label_keys, + ) + metrics_map[metric_name] = metric + metric.add_metric(labels=tag_values, value=agg_data.count_data) + return + + elif isinstance(agg_data, aggregation_data_module.DistributionAggregationData): + + assert agg_data.bounds == sorted(agg_data.bounds) + # buckets are a list of buckets. Each bucket is another list with + # a pair of bucket name and value, or a triple of bucket name, + # value, and exemplar. buckets need to be in order. + buckets = [] + cum_count = 0 # Prometheus buckets expect cumulative count. + for ii, bound in enumerate(agg_data.bounds): + cum_count += agg_data.counts_per_bucket[ii] + bucket = [str(bound), cum_count] + buckets.append(bucket) + # Prometheus requires buckets to be sorted, and +Inf present. + # In OpenCensus we don't have +Inf in the bucket bonds so need to + # append it here. + buckets.append(["+Inf", agg_data.count_data]) + metric = metrics_map.get(metric_name) + if not metric: + metric = HistogramMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + ) + metrics_map[metric_name] = metric + metric.add_metric( + labels=tag_values, + buckets=buckets, + sum_value=agg_data.sum, + ) + return + + elif isinstance(agg_data, aggregation_data_module.SumAggregationData): + metric = metrics_map.get(metric_name) + if not metric: + metric = UnknownMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + ) + metrics_map[metric_name] = metric + metric.add_metric(labels=tag_values, value=agg_data.sum_data) + return + + elif isinstance(agg_data, aggregation_data_module.LastValueAggregationData): + metric = metrics_map.get(metric_name) + if not metric: + metric = GaugeMetricFamily( + name=metric_name, + documentation=metric_description, + labels=label_keys, + ) + metrics_map[metric_name] = metric + metric.add_metric(labels=tag_values, value=agg_data.value) + return + + else: + raise ValueError(f"unsupported aggregation type {type(agg_data)}") + + def collect(self): # pragma: NO COVER + """Collect fetches the statistics from OpenCensus + and delivers them as Prometheus Metrics. + Collect is invoked every time a prometheus.Gatherer is run + for example when the HTTP endpoint is invoked by Prometheus. + """ + # Make a shallow copy of self._view_name_to_data_map, to avoid seeing + # concurrent modifications when iterating through the dictionary. + metrics_map = {} + for v_name, view_data in self._view_name_to_data_map.copy().items(): + if v_name not in self.registered_views: + continue + desc = self.registered_views[v_name] + for tag_values in view_data.tag_value_aggregation_data_map: + agg_data = view_data.tag_value_aggregation_data_map[tag_values] + self.to_metric(desc, tag_values, agg_data, metrics_map) + + for metric in metrics_map.values(): + yield metric + + +class PrometheusStatsExporter(base_exporter.StatsExporter): + """Exporter exports stats to Prometheus, users need + to register the exporter as an HTTP Handler to be + able to export. + :type options: + :class:`~opencensus.ext.prometheus.stats_exporter.Options` + :param options: An options object with the parameters to instantiate the + prometheus exporter. + :type gatherer: :class:`~prometheus_client.core.CollectorRegistry` + :param gatherer: A Prometheus collector registry instance. + :type transport: + :class:`opencensus.common.transports.sync.SyncTransport` or + :class:`opencensus.common.transports.async_.AsyncTransport` + :param transport: An instance of a Transpor to send data with. + :type collector: + :class:`~opencensus.ext.prometheus.stats_exporter.Collector` + :param collector: An instance of the Prometheus Collector object. + """ + + def __init__( + self, options, gatherer, transport=sync.SyncTransport, collector=Collector() + ): + self._options = options + self._gatherer = gatherer + self._collector = collector + self._transport = transport(self) + self.serve_http() + REGISTRY.register(self._collector) + + @property + def transport(self): + """The transport way to be sent data to server + (default is sync). + """ + return self._transport + + @property + def collector(self): + """Collector class instance to be used + to communicate with Prometheus + """ + return self._collector + + @property + def gatherer(self): + """Prometheus Collector Registry instance""" + return self._gatherer + + @property + def options(self): + """Options to be used to configure the exporter""" + return self._options + + def export(self, view_data): + """export send the data to the transport class + in order to be sent to Prometheus in a sync or async way. + """ + if view_data is not None: # pragma: NO COVER + self.transport.export(view_data) + + def on_register_view(self, view): + return NotImplementedError("Not supported by Prometheus") + + def emit(self, view_data): # pragma: NO COVER + """Emit exports to the Prometheus if view data has one or more rows. + Each OpenCensus AggregationData will be converted to + corresponding Prometheus Metric: SumData will be converted + to Untyped Metric, CountData will be a Counter Metric + DistributionData will be a Histogram Metric. + """ + + for v_data in view_data: + if v_data.tag_value_aggregation_data_map is None: + v_data.tag_value_aggregation_data_map = {} + + self.collector.add_view_data(v_data) + + def serve_http(self): + """serve_http serves the Prometheus endpoint.""" + address = str(self.options.address) + kwargs = {"addr": address} if address else {} + start_http_server(port=self.options.port, **kwargs) + + +def new_stats_exporter(option): + """new_stats_exporter returns an exporter + that exports stats to Prometheus. + """ + if option.namespace == "": + raise ValueError("Namespace can not be empty string.") + + collector = new_collector(option) + + exporter = PrometheusStatsExporter( + options=option, gatherer=option.registry, collector=collector + ) + return exporter + + +def new_collector(options): + """new_collector should be used + to create instance of Collector class in order to + prevent the usage of constructor directly + """ + return Collector(options=options) + + +def get_view_name(namespace, view): + """create the name for the view""" + name = "" + if namespace != "": + name = namespace + "_" + return sanitize(name + view.name) + + +_NON_LETTERS_NOR_DIGITS_RE = re.compile(r"[^\w]", re.UNICODE | re.IGNORECASE) + + +def sanitize(key): + """sanitize the given metric name or label according to Prometheus rule. + Replace all characters other than [A-Za-z0-9_] with '_'. + """ + return _NON_LETTERS_NOR_DIGITS_RE.sub("_", key) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/protobuf_compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/protobuf_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..66971d8812d98fa1d9b8d74f12ca9b0abbc8260e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/protobuf_compat.py @@ -0,0 +1,47 @@ +import inspect + +from google.protobuf.json_format import MessageToDict + +""" +This module provides a compatibility layer for different versions of the protobuf +library. +""" + +_protobuf_has_old_arg_name_cached = None + + +def _protobuf_has_old_arg_name(): + """Cache the inspect result to avoid doing it for every single message.""" + global _protobuf_has_old_arg_name_cached + if _protobuf_has_old_arg_name_cached is None: + params = inspect.signature(MessageToDict).parameters + _protobuf_has_old_arg_name_cached = "including_default_value_fields" in params + return _protobuf_has_old_arg_name_cached + + +def rename_always_print_fields_with_no_presence(kwargs): + """ + Protobuf version 5.26.0rc2 renamed argument for `MessageToDict`: + `including_default_value_fields` -> `always_print_fields_with_no_presence`. + See https://github.com/protocolbuffers/protobuf/commit/06e7caba58ede0220b110b89d08f329e5f8a7537#diff-8de817c14d6a087981503c9aea38730b1b3e98f4e306db5ff9d525c7c304f234L129 # noqa: E501 + + We choose to always use the new argument name. If user used the old arg, we raise an + error. + + If protobuf does not have the new arg name but have the old arg name, we rename our + arg to the old one. + """ + old_arg_name = "including_default_value_fields" + new_arg_name = "always_print_fields_with_no_presence" + if old_arg_name in kwargs: + raise ValueError(f"{old_arg_name} is deprecated, please use {new_arg_name}") + + if new_arg_name in kwargs and _protobuf_has_old_arg_name(): + kwargs[old_arg_name] = kwargs.pop(new_arg_name) + + return kwargs + + +def message_to_dict(*args, **kwargs): + kwargs = rename_always_print_fields_with_no_presence(kwargs) + return MessageToDict(*args, **kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_client_microbenchmark.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_client_microbenchmark.py new file mode 100644 index 0000000000000000000000000000000000000000..c3cfec3a8645bd935aaa01e8ddb27af7d6205ec0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_client_microbenchmark.py @@ -0,0 +1,117 @@ +import inspect +import logging +import sys + +import numpy as np + +from ray._private.ray_microbenchmark_helpers import timeit +from ray.util.client.ray_client_helpers import ray_start_client_server + + +def benchmark_get_calls(ray, results): + value = ray.put(0) + + def get_small(): + ray.get(value) + + results += timeit("client: get calls", get_small) + + +def benchmark_tasks_and_get_batch(ray, results): + @ray.remote + def small_value(): + return b"ok" + + def small_value_batch(): + submitted = [small_value.remote() for _ in range(1000)] + ray.get(submitted) + return 0 + + results += timeit("client: tasks and get batch", small_value_batch) + + +def benchmark_put_calls(ray, results): + def put_small(): + ray.put(0) + + results += timeit("client: put calls", put_small) + + +def benchmark_remote_put_calls(ray, results): + @ray.remote + def do_put_small(): + for _ in range(100): + ray.put(0) + + def put_multi_small(): + ray.get([do_put_small.remote() for _ in range(10)]) + + results += timeit("client: tasks and put batch", put_multi_small, 1000) + + +def benchmark_put_large(ray, results): + arr = np.zeros(100 * 1024 * 1024, dtype=np.int64) + + def put_large(): + ray.put(arr) + + results += timeit("client: put gigabytes", put_large, 8 * 0.1) + + +def benchmark_simple_actor(ray, results): + @ray.remote(num_cpus=0) + class Actor: + def small_value(self): + return b"ok" + + def small_value_arg(self, x): + return b"ok" + + def small_value_batch(self, n): + ray.get([self.small_value.remote() for _ in range(n)]) + + a = Actor.remote() + + def actor_sync(): + ray.get(a.small_value.remote()) + + results += timeit("client: 1:1 actor calls sync", actor_sync) + + def actor_async(): + ray.get([a.small_value.remote() for _ in range(1000)]) + + results += timeit("client: 1:1 actor calls async", actor_async, 1000) + + a = Actor.options(max_concurrency=16).remote() + + def actor_concurrent(): + ray.get([a.small_value.remote() for _ in range(1000)]) + + results += timeit("client: 1:1 actor calls concurrent", actor_concurrent, 1000) + + +def main(results=None): + results = results or [] + + ray_config = {"logging_level": logging.WARNING} + + def ray_connect_handler(job_config=None, **ray_init_kwargs): + from ray._private.client_mode_hook import disable_client_hook + + with disable_client_hook(): + import ray as real_ray + + if not real_ray.is_initialized(): + real_ray.init(**ray_config) + + for name, obj in inspect.getmembers(sys.modules[__name__]): + if not name.startswith("benchmark_"): + continue + with ray_start_client_server(ray_connect_handler=ray_connect_handler) as ray: + obj(ray, results) + + return results + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_cluster_perf.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_cluster_perf.py new file mode 100644 index 0000000000000000000000000000000000000000..11d23fc85350eaf67d0162df23d229fc42525b68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_cluster_perf.py @@ -0,0 +1,51 @@ +"""This is the script for `ray clusterbenchmark`.""" + +import time + +import numpy as np + +import ray +from ray.cluster_utils import Cluster + + +def main(): + cluster = Cluster( + initialize_head=True, + connect=True, + head_node_args={"object_store_memory": 20 * 1024 * 1024 * 1024, "num_cpus": 16}, + ) + cluster.add_node( + object_store_memory=20 * 1024 * 1024 * 1024, num_gpus=1, num_cpus=16 + ) + + object_ref_list = [] + for i in range(0, 10): + object_ref = ray.put(np.random.rand(1024 * 128, 1024)) + object_ref_list.append(object_ref) + + @ray.remote(num_gpus=1) + def f(object_ref_list): + diffs = [] + for object_ref in object_ref_list: + before = time.time() + ray.get(object_ref) + after = time.time() + diffs.append(after - before) + time.sleep(1) + return np.mean(diffs), np.std(diffs) + + time_diff, time_diff_std = ray.get(f.remote(object_ref_list)) + + print( + "latency to get an 1G object over network", + round(time_diff, 2), + "+-", + round(time_diff_std, 2), + ) + + ray.shutdown() + cluster.shutdown() + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf4f4952ce6c26ffe9e77e8176b360465da458f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_constants.py @@ -0,0 +1,594 @@ +"""Ray constants used in the Python code.""" + +import json +import logging +import os +import sys + +logger = logging.getLogger(__name__) + + +def env_integer(key, default): + if key in os.environ: + value = os.environ[key] + if value.isdigit(): + return int(os.environ[key]) + + logger.debug( + f"Found {key} in environment, but value must " + f"be an integer. Got: {value}. Returning " + f"provided default {default}." + ) + return default + return default + + +def env_float(key, default): + if key in os.environ: + value = os.environ[key] + try: + return float(value) + except ValueError: + logger.debug( + f"Found {key} in environment, but value must " + f"be a float. Got: {value}. Returning " + f"provided default {default}." + ) + return default + return default + + +def env_bool(key, default): + if key in os.environ: + return ( + True + if os.environ[key].lower() == "true" or os.environ[key] == "1" + else False + ) + return default + + +def env_set_by_user(key): + return key in os.environ + + +# Whether event logging to driver is enabled. Set to 0 to disable. +AUTOSCALER_EVENTS = env_integer("RAY_SCHEDULER_EVENTS", 1) + +RAY_LOG_TO_DRIVER = env_bool("RAY_LOG_TO_DRIVER", True) + +# Filter level under which events will be filtered out, i.e. not printing to driver +RAY_LOG_TO_DRIVER_EVENT_LEVEL = os.environ.get("RAY_LOG_TO_DRIVER_EVENT_LEVEL", "INFO") + +# Internal kv keys for storing monitor debug status. +DEBUG_AUTOSCALING_ERROR = "__autoscaling_error" +DEBUG_AUTOSCALING_STATUS = "__autoscaling_status" +DEBUG_AUTOSCALING_STATUS_LEGACY = "__autoscaling_status_legacy" + +ID_SIZE = 28 + +# The default maximum number of bytes to allocate to the object store unless +# overridden by the user. +DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES = env_integer( + "RAY_DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES", (200) * (10**9) # 200 GB +) +# The default proportion of available memory allocated to the object store +DEFAULT_OBJECT_STORE_MEMORY_PROPORTION = env_float( + "RAY_DEFAULT_OBJECT_STORE_MEMORY_PROPORTION", + 0.3, +) + +# The following values are only used when resource isolation is enabled +# ===== The default number of bytes to reserve for ray system processes +DEFAULT_SYSTEM_RESERVED_MEMORY_BYTES = env_integer( + "RAY_DEFAULT_DEFAULT_SYSTEM_RESERVED_MEMORY_BYTES", (25) * (10**9) +) +# The default proportion available memory to reserve for ray system processes +DEFAULT_SYSTEM_RESERVED_MEMORY_PROPORTION = env_integer( + "RAY_DEFAULT_SYSTEM_RESERVED_MEMORY_PROPORTION", 0.10 +) +# The default number of cpu cores to reserve for ray system processes +DEFAULT_SYSTEM_RESERVED_CPU_CORES = env_float( + "RAY_DEFAULT_SYSTEM_RESERVED_CPU_CORES", 1.0 +) +# The default proportion of cpu cores to reserve for ray system processes +DEFAULT_SYSTEM_RESERVED_CPU_PROPORTION = env_float( + "RAY_DEFAULT_SYSTEM_RESERVED_CPU_PROPORTION", 0.05 +) +# The smallest number of cores that ray system processes can be guaranteed +MINIMUM_SYSTEM_RESERVED_CPU_CORES = 0.5 +# The smallest number of bytes that ray system processes can be guaranteed +MINIMUM_SYSTEM_RESERVED_MEMORY_BYTES = (100) * (10**6) +# The default path for cgroupv2 +DEFAULT_CGROUP_PATH = "/sys/fs/cgroup" + +# The smallest cap on the memory used by the object store that we allow. +# This must be greater than MEMORY_RESOURCE_UNIT_BYTES +OBJECT_STORE_MINIMUM_MEMORY_BYTES = 75 * 1024 * 1024 +# Each ObjectRef currently uses about 3KB of caller memory. +CALLER_MEMORY_USAGE_PER_OBJECT_REF = 3000 +# Match max_direct_call_object_size in +# src/ray/common/ray_config_def.h. +# TODO(swang): Ideally this should be pulled directly from the +# config in case the user overrides it. +DEFAULT_MAX_DIRECT_CALL_OBJECT_SIZE = 100 * 1024 +# Above this number of bytes, raise an error by default unless the user sets +# RAY_ALLOW_SLOW_STORAGE=1. This avoids swapping with large object stores. +REQUIRE_SHM_SIZE_THRESHOLD = 10**10 +# Mac with 16GB memory has degraded performance when the object store size is +# greater than 2GB. +# (see https://github.com/ray-project/ray/issues/20388 for details) +# The workaround here is to limit capacity to 2GB for Mac by default, +# and raise error if the capacity is overwritten by user. +MAC_DEGRADED_PERF_MMAP_SIZE_LIMIT = (2) * (2**30) +# If a user does not specify a port for the primary Ray service, +# we attempt to start the service running at this port. +DEFAULT_PORT = 6379 + +RAY_ADDRESS_ENVIRONMENT_VARIABLE = "RAY_ADDRESS" +RAY_NAMESPACE_ENVIRONMENT_VARIABLE = "RAY_NAMESPACE" +RAY_RUNTIME_ENV_ENVIRONMENT_VARIABLE = "RAY_RUNTIME_ENV" +RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_ENV_VAR = ( + "RAY_RUNTIME_ENV_TEMPORARY_REFERENCE_EXPIRATION_S" +) +# Ray populates this env var to the working dir in the creation of a runtime env. +# For example, `pip` and `conda` users can use this environment variable to locate the +# `requirements.txt` file. +RAY_RUNTIME_ENV_CREATE_WORKING_DIR_ENV_VAR = "RAY_RUNTIME_ENV_CREATE_WORKING_DIR" +# Defaults to 10 minutes. This should be longer than the total time it takes for +# the local working_dir and py_modules to be uploaded, or these files might get +# garbage collected before the job starts. +RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_DEFAULT = 10 * 60 +# If set to 1, then `.gitignore` files will not be parsed and loaded into "excludes" +# when using a local working_dir or py_modules. +RAY_RUNTIME_ENV_IGNORE_GITIGNORE = "RAY_RUNTIME_ENV_IGNORE_GITIGNORE" +# Hook for running a user-specified runtime-env hook. This hook will be called +# unconditionally given the runtime_env dict passed for ray.init. It must return +# a rewritten runtime_env dict. Example: "your.module.runtime_env_hook". +RAY_RUNTIME_ENV_HOOK = "RAY_RUNTIME_ENV_HOOK" +# Hook that is invoked on `ray start`. It will be given the cluster parameters and +# whether we are the head node as arguments. The function can modify the params class, +# but otherwise returns void. Example: "your.module.ray_start_hook". +RAY_START_HOOK = "RAY_START_HOOK" +# Hook that is invoked on `ray job submit`. It will be given all the same args as the +# job.cli.submit() function gets, passed as kwargs to this function. +RAY_JOB_SUBMIT_HOOK = "RAY_JOB_SUBMIT_HOOK" +# Headers to pass when using the Job CLI. It will be given to +# instantiate a Job SubmissionClient. +RAY_JOB_HEADERS = "RAY_JOB_HEADERS" + +DEFAULT_DASHBOARD_IP = "127.0.0.1" +DEFAULT_DASHBOARD_PORT = 8265 +DASHBOARD_ADDRESS = "dashboard" +DASHBOARD_CLIENT_MAX_SIZE = 100 * 1024**2 +PROMETHEUS_SERVICE_DISCOVERY_FILE = "prom_metrics_service_discovery.json" +DEFAULT_DASHBOARD_AGENT_LISTEN_PORT = 52365 +# Default resource requirements for actors when no resource requirements are +# specified. +DEFAULT_ACTOR_METHOD_CPU_SIMPLE = 1 +DEFAULT_ACTOR_CREATION_CPU_SIMPLE = 0 +# Default resource requirements for actors when some resource requirements are +# specified in . +DEFAULT_ACTOR_METHOD_CPU_SPECIFIED = 0 +DEFAULT_ACTOR_CREATION_CPU_SPECIFIED = 1 +# Default number of return values for each actor method. +DEFAULT_ACTOR_METHOD_NUM_RETURN_VALS = 1 + +# Wait 30 seconds for client to reconnect after unexpected disconnection +DEFAULT_CLIENT_RECONNECT_GRACE_PERIOD = 30 + +# If a remote function or actor (or some other export) has serialized size +# greater than this quantity, print an warning. +FUNCTION_SIZE_WARN_THRESHOLD = 10**7 +FUNCTION_SIZE_ERROR_THRESHOLD = env_integer("FUNCTION_SIZE_ERROR_THRESHOLD", (10**8)) + +# If remote functions with the same source are imported this many times, then +# print a warning. +DUPLICATE_REMOTE_FUNCTION_THRESHOLD = 100 + +# The maximum resource quantity that is allowed. TODO(rkn): This could be +# relaxed, but the current implementation of the node manager will be slower +# for large resource quantities due to bookkeeping of specific resource IDs. +MAX_RESOURCE_QUANTITY = 100e12 + +# Number of units 1 resource can be subdivided into. +MIN_RESOURCE_GRANULARITY = 0.0001 + +# Set this environment variable to populate the dashboard URL with +# an external hosted Ray dashboard URL (e.g. because the +# dashboard is behind a proxy or load balancer). This only overrides +# the dashboard URL when returning or printing to a user through a public +# API, but not in the internal KV store. +RAY_OVERRIDE_DASHBOARD_URL = "RAY_OVERRIDE_DASHBOARD_URL" + + +# Different types of Ray errors that can be pushed to the driver. +# TODO(rkn): These should be defined in flatbuffers and must be synced with +# the existing C++ definitions. +PICKLING_LARGE_OBJECT_PUSH_ERROR = "pickling_large_object" +WAIT_FOR_FUNCTION_PUSH_ERROR = "wait_for_function" +VERSION_MISMATCH_PUSH_ERROR = "version_mismatch" +WORKER_CRASH_PUSH_ERROR = "worker_crash" +WORKER_DIED_PUSH_ERROR = "worker_died" +WORKER_POOL_LARGE_ERROR = "worker_pool_large" +PUT_RECONSTRUCTION_PUSH_ERROR = "put_reconstruction" +RESOURCE_DEADLOCK_ERROR = "resource_deadlock" +REMOVED_NODE_ERROR = "node_removed" +MONITOR_DIED_ERROR = "monitor_died" +LOG_MONITOR_DIED_ERROR = "log_monitor_died" +DASHBOARD_AGENT_DIED_ERROR = "dashboard_agent_died" +DASHBOARD_DIED_ERROR = "dashboard_died" +RAYLET_DIED_ERROR = "raylet_died" +DETACHED_ACTOR_ANONYMOUS_NAMESPACE_ERROR = "detached_actor_anonymous_namespace" +EXCESS_QUEUEING_WARNING = "excess_queueing_warning" + +# Used by autoscaler to set the node custom resources and labels +# from cluster.yaml. +RESOURCES_ENVIRONMENT_VARIABLE = "RAY_OVERRIDE_RESOURCES" +LABELS_ENVIRONMENT_VARIABLE = "RAY_OVERRIDE_LABELS" + +# Temporary flag to disable log processing in the dashboard. This is useful +# if the dashboard is overloaded by logs and failing to process other +# dashboard API requests (e.g. Job Submission). +DISABLE_DASHBOARD_LOG_INFO = env_integer("RAY_DISABLE_DASHBOARD_LOG_INFO", 0) + +LOGGER_FORMAT = "%(asctime)s\t%(levelname)s %(filename)s:%(lineno)s -- %(message)s" +LOGGER_FORMAT_ESCAPE = json.dumps(LOGGER_FORMAT.replace("%", "%%")) +LOGGER_FORMAT_HELP = f"The logging format. default={LOGGER_FORMAT_ESCAPE}" +# Configure the default logging levels for various Ray components. +# TODO (kevin85421): Currently, I don't encourage Ray users to configure +# `RAY_LOGGER_LEVEL` until its scope and expected behavior are clear and +# easy to understand. Now, only Ray developers should use it. +LOGGER_LEVEL = os.environ.get("RAY_LOGGER_LEVEL", "info") +LOGGER_LEVEL_CHOICES = ["debug", "info", "warning", "error", "critical"] +LOGGER_LEVEL_HELP = ( + "The logging level threshold, choices=['debug', 'info'," + " 'warning', 'error', 'critical'], default='info'" +) + +LOGGING_ROTATE_BYTES = 512 * 1024 * 1024 # 512MB. +LOGGING_ROTATE_BACKUP_COUNT = 5 # 5 Backup files at max. + +LOGGING_REDIRECT_STDERR_ENVIRONMENT_VARIABLE = "RAY_LOG_TO_STDERR" +# Logging format when logging stderr. This should be formatted with the +# component before setting the formatter, e.g. via +# format = LOGGER_FORMAT_STDERR.format(component="dashboard") +# handler.setFormatter(logging.Formatter(format)) +LOGGER_FORMAT_STDERR = ( + "%(asctime)s\t%(levelname)s ({component}) %(filename)s:%(lineno)s -- %(message)s" +) + +# Constants used to define the different process types. +PROCESS_TYPE_REAPER = "reaper" +PROCESS_TYPE_MONITOR = "monitor" +PROCESS_TYPE_RAY_CLIENT_SERVER = "ray_client_server" +PROCESS_TYPE_LOG_MONITOR = "log_monitor" +PROCESS_TYPE_DASHBOARD = "dashboard" +PROCESS_TYPE_DASHBOARD_AGENT = "dashboard_agent" +PROCESS_TYPE_RUNTIME_ENV_AGENT = "runtime_env_agent" +PROCESS_TYPE_WORKER = "worker" +PROCESS_TYPE_RAYLET = "raylet" +PROCESS_TYPE_REDIS_SERVER = "redis_server" +PROCESS_TYPE_GCS_SERVER = "gcs_server" +PROCESS_TYPE_PYTHON_CORE_WORKER_DRIVER = "python-core-driver" +PROCESS_TYPE_PYTHON_CORE_WORKER = "python-core-worker" + +# Log file names +MONITOR_LOG_FILE_NAME = f"{PROCESS_TYPE_MONITOR}.log" +LOG_MONITOR_LOG_FILE_NAME = f"{PROCESS_TYPE_LOG_MONITOR}.log" + +# Enable log deduplication. +RAY_DEDUP_LOGS = env_bool("RAY_DEDUP_LOGS", True) + +# How many seconds of messages to buffer for log deduplication. +RAY_DEDUP_LOGS_AGG_WINDOW_S = env_integer("RAY_DEDUP_LOGS_AGG_WINDOW_S", 5) + +# Regex for log messages to never deduplicate, or None. This takes precedence over +# the skip regex below. A default pattern is set for testing. +TESTING_NEVER_DEDUP_TOKEN = "__ray_testing_never_deduplicate__" +RAY_DEDUP_LOGS_ALLOW_REGEX = os.environ.get( + "RAY_DEDUP_LOGS_ALLOW_REGEX", TESTING_NEVER_DEDUP_TOKEN +) + +# Regex for log messages to always skip / suppress, or None. +RAY_DEDUP_LOGS_SKIP_REGEX = os.environ.get("RAY_DEDUP_LOGS_SKIP_REGEX") + +WORKER_PROCESS_TYPE_IDLE_WORKER = "ray::IDLE" +WORKER_PROCESS_TYPE_SPILL_WORKER_NAME = "SpillWorker" +WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME = "RestoreWorker" +WORKER_PROCESS_TYPE_SPILL_WORKER_IDLE = ( + f"ray::IDLE_{WORKER_PROCESS_TYPE_SPILL_WORKER_NAME}" +) +WORKER_PROCESS_TYPE_RESTORE_WORKER_IDLE = ( + f"ray::IDLE_{WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME}" +) +WORKER_PROCESS_TYPE_SPILL_WORKER = f"ray::SPILL_{WORKER_PROCESS_TYPE_SPILL_WORKER_NAME}" +WORKER_PROCESS_TYPE_RESTORE_WORKER = ( + f"ray::RESTORE_{WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME}" +) +WORKER_PROCESS_TYPE_SPILL_WORKER_DELETE = ( + f"ray::DELETE_{WORKER_PROCESS_TYPE_SPILL_WORKER_NAME}" +) +WORKER_PROCESS_TYPE_RESTORE_WORKER_DELETE = ( + f"ray::DELETE_{WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME}" +) + +# The number of files the log monitor will open. If more files exist, they will +# be ignored. +LOG_MONITOR_MAX_OPEN_FILES = int( + os.environ.get("RAY_LOG_MONITOR_MAX_OPEN_FILES", "200") +) + +# The maximum batch of lines to be read in a single iteration. We _always_ try +# to read this number of lines even if there aren't any new lines. +LOG_MONITOR_NUM_LINES_TO_READ = int( + os.environ.get("RAY_LOG_MONITOR_NUM_LINES_TO_READ", "1000") +) + +# Autoscaler events are denoted by the ":event_summary:" magic token. +LOG_PREFIX_EVENT_SUMMARY = ":event_summary:" +# Cluster-level info events are denoted by the ":info_message:" magic token. These may +# be emitted in the stderr of Ray components. +LOG_PREFIX_INFO_MESSAGE = ":info_message:" +# Actor names are recorded in the logs with this magic token as a prefix. +LOG_PREFIX_ACTOR_NAME = ":actor_name:" +# Task names are recorded in the logs with this magic token as a prefix. +LOG_PREFIX_TASK_NAME = ":task_name:" +# Job ids are recorded in the logs with this magic token as a prefix. +LOG_PREFIX_JOB_ID = ":job_id:" + +# The object metadata field uses the following format: It is a comma +# separated list of fields. The first field is mandatory and is the +# type of the object (see types below) or an integer, which is interpreted +# as an error value. The second part is optional and if present has the +# form DEBUG:, it is used for implementing the debugger. + +# A constant used as object metadata to indicate the object is cross language. +OBJECT_METADATA_TYPE_CROSS_LANGUAGE = b"XLANG" +# A constant used as object metadata to indicate the object is python specific. +OBJECT_METADATA_TYPE_PYTHON = b"PYTHON" +# A constant used as object metadata to indicate the object is raw bytes. +OBJECT_METADATA_TYPE_RAW = b"RAW" + +# A constant used as object metadata to indicate the object is an actor handle. +# This value should be synchronized with the Java definition in +# ObjectSerializer.java +# TODO(fyrestone): Serialize the ActorHandle via the custom type feature +# of XLANG. +OBJECT_METADATA_TYPE_ACTOR_HANDLE = b"ACTOR_HANDLE" + +# A constant indicating the debugging part of the metadata (see above). +OBJECT_METADATA_DEBUG_PREFIX = b"DEBUG:" + +AUTOSCALER_RESOURCE_REQUEST_CHANNEL = b"autoscaler_resource_request" + +REDIS_DEFAULT_USERNAME = "" + +REDIS_DEFAULT_PASSWORD = "" + +# The default ip address to bind to. +NODE_DEFAULT_IP = "127.0.0.1" + +# The Mach kernel page size in bytes. +MACH_PAGE_SIZE_BYTES = 4096 + +# The max number of bytes for task execution error message. +MAX_APPLICATION_ERROR_LEN = 500 + +# Max 64 bit integer value, which is needed to ensure against overflow +# in C++ when passing integer values cross-language. +MAX_INT64_VALUE = 9223372036854775807 + +# Object Spilling related constants +DEFAULT_OBJECT_PREFIX = "ray_spilled_objects" + +GCS_PORT_ENVIRONMENT_VARIABLE = "RAY_GCS_SERVER_PORT" + +HEALTHCHECK_EXPIRATION_S = os.environ.get("RAY_HEALTHCHECK_EXPIRATION_S", 10) + +# Filename of "shim process" that sets up Python worker environment. +# Should be kept in sync with kSetupWorkerFilename in +# src/ray/common/constants.h. +SETUP_WORKER_FILENAME = "setup_worker.py" + +# Directory name where runtime_env resources will be created & cached. +DEFAULT_RUNTIME_ENV_DIR_NAME = "runtime_resources" + +# The timeout seconds for the creation of runtime env, +# dafault timeout is 10 minutes +DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS = 600 + +# Used to separate lines when formatting the call stack where an ObjectRef was +# created. +CALL_STACK_LINE_DELIMITER = " | " + +# The default gRPC max message size is 4 MiB, we use a larger number of 512 MiB +# NOTE: This is equal to the C++ limit of (RAY_CONFIG::max_grpc_message_size) +GRPC_CPP_MAX_MESSAGE_SIZE = 512 * 1024 * 1024 + +# The gRPC send & receive max length for "dashboard agent" server. +# NOTE: This is equal to the C++ limit of RayConfig::max_grpc_message_size +# and HAVE TO STAY IN SYNC with it (ie, meaning that both of these values +# have to be set at the same time) +AGENT_GRPC_MAX_MESSAGE_LENGTH = env_integer( + "AGENT_GRPC_MAX_MESSAGE_LENGTH", 20 * 1024 * 1024 # 20MB +) + + +# GRPC options +GRPC_ENABLE_HTTP_PROXY = ( + 1 + if os.environ.get("RAY_grpc_enable_http_proxy", "0").lower() in ("1", "true") + else 0 +) +GLOBAL_GRPC_OPTIONS = (("grpc.enable_http_proxy", GRPC_ENABLE_HTTP_PROXY),) + +# Internal kv namespaces +KV_NAMESPACE_DASHBOARD = b"dashboard" +KV_NAMESPACE_SESSION = b"session" +KV_NAMESPACE_TRACING = b"tracing" +KV_NAMESPACE_PDB = b"ray_pdb" +KV_NAMESPACE_HEALTHCHECK = b"healthcheck" +KV_NAMESPACE_JOB = b"job" +KV_NAMESPACE_CLUSTER = b"cluster" +KV_HEAD_NODE_ID_KEY = b"head_node_id" +# TODO: Set package for runtime env +# We need to update ray client for this since runtime env use ray client +# This might introduce some compatibility issues so leave it here for now. +KV_NAMESPACE_PACKAGE = None +KV_NAMESPACE_FUNCTION_TABLE = b"fun" + +LANGUAGE_WORKER_TYPES = ["python", "java", "cpp"] + +NEURON_CORES = "neuron_cores" +GPU = "GPU" +TPU = "TPU" +NPU = "NPU" +HPU = "HPU" + + +RAY_WORKER_NICENESS = "RAY_worker_niceness" + +# Default max_retries option in @ray.remote for non-actor +# tasks. +DEFAULT_TASK_MAX_RETRIES = 3 + +# Default max_concurrency option in @ray.remote for threaded actors. +DEFAULT_MAX_CONCURRENCY_THREADED = 1 + +# Default max_concurrency option in @ray.remote for async actors. +DEFAULT_MAX_CONCURRENCY_ASYNC = 1000 + +# Prefix for namespaces which are used internally by ray. +# Jobs within these namespaces should be hidden from users +# and should not be considered user activity. +# Please keep this in sync with the definition kRayInternalNamespacePrefix +# in /src/ray/gcs/gcs_server/gcs_job_manager.h. +RAY_INTERNAL_NAMESPACE_PREFIX = "_ray_internal_" +RAY_INTERNAL_DASHBOARD_NAMESPACE = f"{RAY_INTERNAL_NAMESPACE_PREFIX}dashboard" + +# Ray internal flags. These flags should not be set by users, and we strip them on job +# submission. +# This should be consistent with src/ray/common/ray_internal_flag_def.h +RAY_INTERNAL_FLAGS = [ + "RAY_JOB_ID", + "RAY_RAYLET_PID", + "RAY_OVERRIDE_NODE_ID_FOR_TESTING", +] + + +def gcs_actor_scheduling_enabled(): + return os.environ.get("RAY_gcs_actor_scheduling_enabled") == "true" + + +DEFAULT_RESOURCES = {"CPU", "GPU", "memory", "object_store_memory"} + +# Supported Python versions for runtime env's "conda" field. Ray downloads +# Ray wheels into the conda environment, so the Ray wheels for these Python +# versions must be available online. +RUNTIME_ENV_CONDA_PY_VERSIONS = [(3, 9), (3, 10), (3, 11), (3, 12)] + +# Whether to enable Ray clusters (in addition to local Ray). +# Ray clusters are not explicitly supported for Windows and OSX. +IS_WINDOWS_OR_OSX = sys.platform == "darwin" or sys.platform == "win32" +ENABLE_RAY_CLUSTERS_ENV_VAR = "RAY_ENABLE_WINDOWS_OR_OSX_CLUSTER" +ENABLE_RAY_CLUSTER = env_bool( + ENABLE_RAY_CLUSTERS_ENV_VAR, + not IS_WINDOWS_OR_OSX, +) + +SESSION_LATEST = "session_latest" +NUM_PORT_RETRIES = 40 +NUM_REDIS_GET_RETRIES = int(os.environ.get("RAY_NUM_REDIS_GET_RETRIES", "20")) + +# The allowed cached ports in Ray. Refer to Port configuration for more details: +# https://docs.ray.io/en/latest/ray-core/configure.html#ports-configurations +RAY_ALLOWED_CACHED_PORTS = { + "metrics_agent_port", + "metrics_export_port", + "dashboard_agent_listen_port", + "runtime_env_agent_port", + "gcs_server_port", # the `port` option for gcs port. +} + +# Turn this on if actor task log's offsets are expected to be recorded. +# With this enabled, actor tasks' log could be queried with task id. +RAY_ENABLE_RECORD_ACTOR_TASK_LOGGING = env_bool( + "RAY_ENABLE_RECORD_ACTOR_TASK_LOGGING", False +) + +# RuntimeEnv env var to indicate it exports a function +WORKER_PROCESS_SETUP_HOOK_ENV_VAR = "__RAY_WORKER_PROCESS_SETUP_HOOK_ENV_VAR" +RAY_WORKER_PROCESS_SETUP_HOOK_LOAD_TIMEOUT_ENV_VAR = ( + "RAY_WORKER_PROCESS_SETUP_HOOK_LOAD_TIMEOUT" # noqa +) + +RAY_DEFAULT_LABEL_KEYS_PREFIX = "ray.io/" + +RAY_TPU_MAX_CONCURRENT_CONNECTIONS_ENV_VAR = "RAY_TPU_MAX_CONCURRENT_ACTIVE_CONNECTIONS" + +RAY_NODE_IP_FILENAME = "node_ip_address.json" + +RAY_LOGGING_CONFIG_ENCODING = os.environ.get("RAY_LOGGING_CONFIG_ENCODING") + +RAY_BACKEND_LOG_JSON_ENV_VAR = "RAY_BACKEND_LOG_JSON" + +# Write export API event of all resource types to file if enabled. +# RAY_enable_export_api_write_config will not be considered if +# this is enabled. +RAY_ENABLE_EXPORT_API_WRITE = env_bool("RAY_enable_export_api_write", False) + +# Comma separated string containing individual resource +# to write export API events for. This configuration is only used if +# RAY_enable_export_api_write is not enabled. Full list of valid +# resource types in ExportEvent.SourceType enum in +# src/ray/protobuf/export_api/export_event.proto +# Example config: +# `export RAY_enable_export_api_write_config='EXPORT_SUBMISSION_JOB,EXPORT_ACTOR'` +RAY_ENABLE_EXPORT_API_WRITE_CONFIG_STR = os.environ.get( + "RAY_enable_export_api_write_config", "" +) +RAY_ENABLE_EXPORT_API_WRITE_CONFIG = RAY_ENABLE_EXPORT_API_WRITE_CONFIG_STR.split(",") + +RAY_EXPORT_EVENT_MAX_FILE_SIZE_BYTES = env_bool( + "RAY_EXPORT_EVENT_MAX_FILE_SIZE_BYTES", 100 * 1e6 +) + +RAY_EXPORT_EVENT_MAX_BACKUP_COUNT = env_bool("RAY_EXPORT_EVENT_MAX_BACKUP_COUNT", 20) + +# If this flag is set and you run the driver with `uv run`, Ray propagates the `uv run` +# environment to all workers. Ray does this by setting the `py_executable` to the +# `uv run`` command line and by propagating the working directory +# via the `working_dir` plugin so uv finds the pyproject.toml. +# If you enable RAY_ENABLE_UV_RUN_RUNTIME_ENV AND you run the driver +# with `uv run`, Ray deactivates the regular RAY_RUNTIME_ENV_HOOK +# because in most cases the hooks wouldn't work unless you specifically make the code +# for the runtime env hook available in your uv environment and make sure your hook +# is compatible with your uv runtime environment. If you want to combine a custom +# RAY_RUNTIME_ENV_HOOK with `uv run`, you should flag off RAY_ENABLE_UV_RUN_RUNTIME_ENV +# and call ray._private.runtime_env.uv_runtime_env_hook.hook manually in your hook or +# manually set the py_executable in your runtime environment hook. +RAY_ENABLE_UV_RUN_RUNTIME_ENV = env_bool("RAY_ENABLE_UV_RUN_RUNTIME_ENV", True) + +# Prometheus metric cardinality level setting, either "legacy" or "recommended". +# +# Legacy: report all metrics to prometheus with the set of labels that are reported by +# the component, including WorkerId, (task or actor) Name, etc. This is the default. +# Recommended: report only the node level metrics to prometheus. This means that the +# WorkerId will be removed from all metrics. +RAY_METRIC_CARDINALITY_LEVEL = os.environ.get("RAY_metric_cardinality_level", "legacy") + +# Whether enable OpenTelemetry as the metrics collection backend on the driver +# component. This flag is only used during the migration of the metric collection +# backend from OpenCensus to OpenTelemetry. It will be removed in the future. +RAY_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY_ON_AGENT = env_bool( + "RAY_experimental_enable_open_telemetry_on_agent", False +) + +# Whether enable OpenTelemetry as the metrics collection backend on the core +# components (core workers, gcs server, raylet, etc.). This flag is only used during +# the migration of the metric collection backend from OpenCensus to OpenTelemetry. +# It will be removed in the future. +RAY_EXPERIMENTAL_ENABLE_OPEN_TELEMETRY_ON_CORE = env_bool( + "RAY_experimental_enable_open_telemetry_on_core", False +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_experimental_perf.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_experimental_perf.py new file mode 100644 index 0000000000000000000000000000000000000000..f3364fef69f3e1897978b5d40b0073faff4f1633 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_experimental_perf.py @@ -0,0 +1,337 @@ +"""This is the script for `ray microbenchmark`.""" + +import asyncio +import logging +import multiprocessing + +import ray +import ray.experimental.channel as ray_channel +from ray._common.utils import ( + get_or_create_event_loop, +) +from ray._private.ray_microbenchmark_helpers import asyncio_timeit, timeit +from ray._private.test_utils import get_actor_node_id +from ray.dag import InputNode, MultiOutputNode +from ray.dag.compiled_dag_node import CompiledDAG +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +logger = logging.getLogger(__name__) + + +@ray.remote +class DAGActor: + def echo(self, x): + return x + + def echo_multiple(self, *x): + return x + + +def check_optimized_build(): + if not ray._raylet.OPTIMIZED: + msg = ( + "WARNING: Unoptimized build! " + "To benchmark an optimized build, try:\n" + "\tbazel build -c opt //:ray_pkg\n" + "You can also make this permanent by adding\n" + "\tbuild --compilation_mode=opt\n" + "to your user-wide ~/.bazelrc file. " + "(Do not add this to the project-level .bazelrc file.)" + ) + logger.warning(msg) + + +def create_driver_actor(): + return CompiledDAG.DAGDriverProxyActor.options( + scheduling_strategy=NodeAffinitySchedulingStrategy( + ray.get_runtime_context().get_node_id(), soft=False + ) + ).remote() + + +def main(results=None): + results = results or [] + loop = get_or_create_event_loop() + + check_optimized_build() + + print("Tip: set TESTS_TO_RUN='pattern' to run a subset of benchmarks") + + ################################################# + # Perf tests for channels, used in compiled DAGs. + ################################################# + ray.init() + + def put_channel_small(chans, do_get=False): + for chan in chans: + chan.write(b"0") + if do_get: + chan.read() + + @ray.remote + class ChannelReader: + def ready(self): + return + + def read(self, chans): + while True: + for chan in chans: + chan.read() + + driver_actor = create_driver_actor() + driver_node = get_actor_node_id(driver_actor) + chans = [ray_channel.Channel(None, [(driver_actor, driver_node)], 1000)] + results += timeit( + "[unstable] local put:local get, single channel calls", + lambda: put_channel_small(chans, do_get=True), + ) + + reader = ChannelReader.remote() + reader_node = get_actor_node_id(reader) + chans = [ray_channel.Channel(None, [(reader, reader_node)], 1000)] + ray.get(reader.ready.remote()) + reader.read.remote(chans) + results += timeit( + "[unstable] local put:1 remote get, single channel calls", + lambda: put_channel_small(chans), + ) + ray.kill(reader) + + n_cpu = multiprocessing.cpu_count() // 2 + print(f"Testing multiple readers/channels, n={n_cpu}") + + reader_and_node_list = [] + for _ in range(n_cpu): + reader = ChannelReader.remote() + reader_node = get_actor_node_id(reader) + reader_and_node_list.append((reader, reader_node)) + chans = [ray_channel.Channel(None, reader_and_node_list, 1000)] + ray.get([reader.ready.remote() for reader, _ in reader_and_node_list]) + for reader, _ in reader_and_node_list: + reader.read.remote(chans) + results += timeit( + "[unstable] local put:n remote get, single channel calls", + lambda: put_channel_small(chans), + ) + for reader, _ in reader_and_node_list: + ray.kill(reader) + + reader = ChannelReader.remote() + reader_node = get_actor_node_id(reader) + chans = [ + ray_channel.Channel(None, [(reader, reader_node)], 1000) for _ in range(n_cpu) + ] + ray.get(reader.ready.remote()) + reader.read.remote(chans) + results += timeit( + "[unstable] local put:1 remote get, n channels calls", + lambda: put_channel_small(chans), + ) + ray.kill(reader) + + reader_and_node_list = [] + for _ in range(n_cpu): + reader = ChannelReader.remote() + reader_node = get_actor_node_id(reader) + reader_and_node_list.append((reader, reader_node)) + chans = [ + ray_channel.Channel(None, [reader_and_node_list[i]], 1000) for i in range(n_cpu) + ] + ray.get([reader.ready.remote() for reader, _ in reader_and_node_list]) + for chan, reader_node_tuple in zip(chans, reader_and_node_list): + reader = reader_node_tuple[0] + reader.read.remote([chan]) + results += timeit( + "[unstable] local put:n remote get, n channels calls", + lambda: put_channel_small(chans), + ) + for reader, _ in reader_and_node_list: + ray.kill(reader) + + # Tests for compiled DAGs. + + def _exec(dag, num_args=1, payload_size=1): + output_ref = dag.execute(*[b"x" * payload_size for _ in range(num_args)]) + ray.get(output_ref) + + async def exec_async(tag): + async def _exec_async(): + fut = await compiled_dag.execute_async(b"x") + if not isinstance(fut, list): + await fut + else: + await asyncio.gather(*fut) + + return await asyncio_timeit( + tag, + _exec_async, + ) + + # Single-actor DAG calls + + a = DAGActor.remote() + with InputNode() as inp: + dag = a.echo.bind(inp) + + results += timeit( + "[unstable] single-actor DAG calls", lambda: ray.get(dag.execute(b"x")) + ) + compiled_dag = dag.experimental_compile() + results += timeit( + "[unstable] compiled single-actor DAG calls", lambda: _exec(compiled_dag) + ) + del a + + # Single-actor asyncio DAG calls + + a = DAGActor.remote() + with InputNode() as inp: + dag = a.echo.bind(inp) + compiled_dag = dag.experimental_compile(enable_asyncio=True) + results += loop.run_until_complete( + exec_async( + "[unstable] compiled single-actor asyncio DAG calls", + ) + ) + del a + + # Scatter-gather DAG calls + + n_cpu = multiprocessing.cpu_count() // 2 + actors = [DAGActor.remote() for _ in range(n_cpu)] + with InputNode() as inp: + dag = MultiOutputNode([a.echo.bind(inp) for a in actors]) + results += timeit( + f"[unstable] scatter-gather DAG calls, n={n_cpu} actors", + lambda: ray.get(dag.execute(b"x")), + ) + compiled_dag = dag.experimental_compile() + results += timeit( + f"[unstable] compiled scatter-gather DAG calls, n={n_cpu} actors", + lambda: _exec(compiled_dag), + ) + + # Scatter-gather asyncio DAG calls + + actors = [DAGActor.remote() for _ in range(n_cpu)] + with InputNode() as inp: + dag = MultiOutputNode([a.echo.bind(inp) for a in actors]) + compiled_dag = dag.experimental_compile(enable_asyncio=True) + results += loop.run_until_complete( + exec_async( + f"[unstable] compiled scatter-gather asyncio DAG calls, n={n_cpu} actors", + ) + ) + + # Chain DAG calls + + actors = [DAGActor.remote() for _ in range(n_cpu)] + with InputNode() as inp: + dag = inp + for a in actors: + dag = a.echo.bind(dag) + results += timeit( + f"[unstable] chain DAG calls, n={n_cpu} actors", + lambda: ray.get(dag.execute(b"x")), + ) + compiled_dag = dag.experimental_compile() + results += timeit( + f"[unstable] compiled chain DAG calls, n={n_cpu} actors", + lambda: _exec(compiled_dag), + ) + + # Chain asyncio DAG calls + + actors = [DAGActor.remote() for _ in range(n_cpu)] + with InputNode() as inp: + dag = inp + for a in actors: + dag = a.echo.bind(dag) + compiled_dag = dag.experimental_compile(enable_asyncio=True) + results += loop.run_until_complete( + exec_async(f"[unstable] compiled chain asyncio DAG calls, n={n_cpu} actors") + ) + + # Multiple args with small payloads + + n_actors = 8 + assert ( + n_cpu > n_actors + ), f"n_cpu ({n_cpu}) must be greater than n_actors ({n_actors})" + + actors = [DAGActor.remote() for _ in range(n_actors)] + with InputNode() as inp: + dag = MultiOutputNode([actors[i].echo.bind(inp[i]) for i in range(n_actors)]) + payload_size = 1 + results += timeit( + f"[unstable] multiple args with small payloads DAG calls, n={n_actors} actors", + lambda: ray.get(dag.execute(*[b"x" * payload_size for _ in range(n_actors)])), + ) + compiled_dag = dag.experimental_compile() + results += timeit( + f"[unstable] compiled multiple args with small payloads DAG calls, " + f"n={n_actors} actors", + lambda: _exec(compiled_dag, num_args=n_actors, payload_size=payload_size), + ) + + # Multiple args with medium payloads + + actors = [DAGActor.remote() for _ in range(n_actors)] + with InputNode() as inp: + dag = MultiOutputNode([actors[i].echo.bind(inp[i]) for i in range(n_actors)]) + payload_size = 1024 * 1024 + results += timeit( + f"[unstable] multiple args with medium payloads DAG calls, n={n_actors} actors", + lambda: ray.get(dag.execute(*[b"x" * payload_size for _ in range(n_actors)])), + ) + compiled_dag = dag.experimental_compile() + results += timeit( + "[unstable] compiled multiple args with medium payloads DAG calls, " + f"n={n_actors} actors", + lambda: _exec(compiled_dag, num_args=n_actors, payload_size=payload_size), + ) + + # Multiple args with large payloads + + actors = [DAGActor.remote() for _ in range(n_actors)] + with InputNode() as inp: + dag = MultiOutputNode([actors[i].echo.bind(inp[i]) for i in range(n_actors)]) + payload_size = 10 * 1024 * 1024 + results += timeit( + f"[unstable] multiple args with large payloads DAG calls, n={n_actors} actors", + lambda: ray.get(dag.execute(*[b"x" * payload_size for _ in range(n_actors)])), + ) + compiled_dag = dag.experimental_compile() + results += timeit( + "[unstable] compiled multiple args with large payloads DAG calls, " + f"n={n_actors} actors", + lambda: _exec(compiled_dag, num_args=n_actors, payload_size=payload_size), + ) + + # Worst case for multiple arguments: a single actor takes all the arguments + # with small payloads. + + actor = DAGActor.remote() + n_args = 8 + with InputNode() as inp: + dag = actor.echo_multiple.bind(*[inp[i] for i in range(n_args)]) + payload_size = 1 + results += timeit( + "[unstable] single-actor with all args with small payloads DAG calls, " + "n=1 actors", + lambda: ray.get(dag.execute(*[b"x" * payload_size for _ in range(n_args)])), + ) + compiled_dag = dag.experimental_compile() + results += timeit( + "[unstable] single-actor with all args with small payloads DAG calls, " + "n=1 actors", + lambda: _exec(compiled_dag, num_args=n_args, payload_size=payload_size), + ) + + ray.shutdown() + + return results + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b24e1754ff8a7222373bf6b588a8f248bf45c1e1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__init__.py @@ -0,0 +1,379 @@ +import logging +import logging.handlers +import os +import re +import sys +import threading +import time +from dataclasses import dataclass +from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union + +import colorama + +import ray +from ray._private.ray_constants import ( + RAY_DEDUP_LOGS, + RAY_DEDUP_LOGS_AGG_WINDOW_S, + RAY_DEDUP_LOGS_ALLOW_REGEX, + RAY_DEDUP_LOGS_SKIP_REGEX, +) +from ray.experimental.tqdm_ray import RAY_TQDM_MAGIC +from ray.util.debug import log_once + + +def setup_logger( + logging_level: int, + logging_format: str, +): + """Setup default logging for ray.""" + logger = logging.getLogger("ray") + if logging_format: + # Overwrite the formatters for all default handlers. + formatter = logging.Formatter(logging_format) + for handler in logger.handlers: + handler.setFormatter(formatter) + if type(logging_level) is str: + logging_level = logging.getLevelName(logging_level.upper()) + logger.setLevel(logging_level) + + +def setup_component_logger( + *, + logging_level, + logging_format, + log_dir, + filename: Union[str, Iterable[str]], + max_bytes, + backup_count, + logger_name=None, + propagate=True, +): + """Configure the logger that is used for Ray's python components. + + For example, it should be used for monitor, dashboard, and log monitor. + The only exception is workers. They use the different logging config. + + Ray's python components generally should not write to stdout/stderr, because + messages written there will be redirected to the head node. For deployments where + there may be thousands of workers, this would create unacceptable levels of log + spam. For this reason, we disable the "ray" logger's handlers, and enable + propagation so that log messages that actually do need to be sent to the head node + can reach it. + + Args: + logging_level: Logging level in string or logging enum. + logging_format: Logging format string. + log_dir: Log directory path. If empty, logs will go to + stderr. + filename: A single filename or an iterable of filenames to write logs to. + If empty, logs will go to stderr. + max_bytes: Same argument as RotatingFileHandler's maxBytes. + backup_count: Same argument as RotatingFileHandler's backupCount. + logger_name: Used to create or get the correspoding + logger in getLogger call. It will get the root logger by default. + propagate: Whether to propagate the log to the parent logger. + Returns: + the created or modified logger. + """ + ray._private.log.clear_logger("ray") + + logger = logging.getLogger(logger_name) + if isinstance(logging_level, str): + logging_level = logging.getLevelName(logging_level.upper()) + logger.setLevel(logging_level) + + filenames = [filename] if isinstance(filename, str) else filename + + for filename in filenames: + if not filename or not log_dir: + handler = logging.StreamHandler() + else: + handler = logging.handlers.RotatingFileHandler( + os.path.join(log_dir, filename), + maxBytes=max_bytes, + backupCount=backup_count, + ) + handler.setLevel(logging_level) + handler.setFormatter(logging.Formatter(logging_format)) + logger.addHandler(handler) + + logger.propagate = propagate + return logger + + +def run_callback_on_events_in_ipython(event: str, cb: Callable): + """ + Register a callback to be run after each cell completes in IPython. + E.g.: + This is used to flush the logs after each cell completes. + + If IPython is not installed, this function does nothing. + + Args: + cb: The callback to run. + """ + if "IPython" in sys.modules: + from IPython import get_ipython + + ipython = get_ipython() + # Register a callback on cell completion. + if ipython is not None: + ipython.events.register(event, cb) + + +""" +All components underneath here is used specifically for the default_worker.py. +""" + +# It's worth noticing that filepath format should be kept in sync with function +# `GetWorkerOutputFilepath` under file "src/ray/core_worker/core_worker_process.cc". +def get_worker_log_file_name(worker_type, job_id=None): + if job_id is None: + job_id = os.environ.get("RAY_JOB_ID") + if worker_type == "WORKER": + if job_id is None: + job_id = "" + worker_name = "worker" + else: + job_id = "" + worker_name = "io_worker" + + # Make sure these values are set already. + assert ray._private.worker._global_node is not None + assert ray._private.worker.global_worker is not None + filename = f"{worker_name}-{ray.get_runtime_context().get_worker_id()}-" + if job_id: + filename += f"{job_id}-" + filename += f"{os.getpid()}" + return filename + + +def configure_log_file(out_file, err_file): + # If either of the file handles are None, there are no log files to + # configure since we're redirecting all output to stdout and stderr. + if out_file is None or err_file is None: + return + stdout_fileno = sys.stdout.fileno() + stderr_fileno = sys.stderr.fileno() + # C++ logging requires redirecting the stdout file descriptor. Note that + # dup2 will automatically close the old file descriptor before overriding + # it. + os.dup2(out_file.fileno(), stdout_fileno) + os.dup2(err_file.fileno(), stderr_fileno) + # We also manually set sys.stdout and sys.stderr because that seems to + # have an effect on the output buffering. Without doing this, stdout + # and stderr are heavily buffered resulting in seemingly lost logging + # statements. We never want to close the stdout file descriptor, dup2 will + # close it when necessary and we don't want python's GC to close it. + sys.stdout = ray._private.utils.open_log( + stdout_fileno, unbuffered=True, closefd=False + ) + sys.stderr = ray._private.utils.open_log( + stderr_fileno, unbuffered=True, closefd=False + ) + + +class WorkerStandardStreamDispatcher: + def __init__(self): + self.handlers = [] + self._lock = threading.Lock() + + def add_handler(self, name: str, handler: Callable) -> None: + with self._lock: + self.handlers.append((name, handler)) + + def remove_handler(self, name: str) -> None: + with self._lock: + new_handlers = [pair for pair in self.handlers if pair[0] != name] + self.handlers = new_handlers + + def emit(self, data): + with self._lock: + for pair in self.handlers: + _, handle = pair + handle(data) + + +global_worker_stdstream_dispatcher = WorkerStandardStreamDispatcher() + + +# Regex for canonicalizing log lines. +NUMBERS = re.compile(r"(\d+|0x[0-9a-fA-F]+)") + +# Batch of log lines including ip, pid, lines, etc. +LogBatch = Dict[str, Any] + + +def _canonicalise_log_line(line): + # Remove words containing numbers or hex, since those tend to differ between + # workers. + return " ".join(x for x in line.split() if not NUMBERS.search(x)) + + +@dataclass +class DedupState: + # Timestamp of the earliest log message seen of this pattern. + timestamp: int + + # The number of un-printed occurrances for this pattern. + count: int + + # Latest instance of this log pattern. + line: int + + # Latest metadata dict for this log pattern, not including the lines field. + metadata: LogBatch + + # Set of (ip, pid) sources which have emitted this pattern. + sources: Set[Tuple[str, int]] + + # The string that should be printed to stdout. + def formatted(self) -> str: + return self.line + _color( + f" [repeated {self.count}x across cluster]" + _warn_once() + ) + + +class LogDeduplicator: + def __init__( + self, + agg_window_s: int, + allow_re: Optional[str], + skip_re: Optional[str], + *, + _timesource=None, + ): + self.agg_window_s = agg_window_s + if allow_re: + self.allow_re = re.compile(allow_re) + else: + self.allow_re = None + if skip_re: + self.skip_re = re.compile(skip_re) + else: + self.skip_re = None + # Buffer of up to RAY_DEDUP_LOGS_AGG_WINDOW_S recent log patterns. + # This buffer is cleared if the pattern isn't seen within the window. + self.recent: Dict[str, DedupState] = {} + self.timesource = _timesource or (lambda: time.time()) + + run_callback_on_events_in_ipython("post_execute", self.flush) + + def deduplicate(self, batch: LogBatch) -> List[LogBatch]: + """Rewrite a batch of lines to reduce duplicate log messages. + + Args: + batch: The batch of lines from a single source. + + Returns: + List of batches from this and possibly other previous sources to print. + """ + if not RAY_DEDUP_LOGS: + return [batch] + + now = self.timesource() + metadata = batch.copy() + del metadata["lines"] + source = (metadata.get("ip"), metadata.get("pid")) + output: List[LogBatch] = [dict(**metadata, lines=[])] + + # Decide which lines to emit from the input batch. Put the outputs in the + # first output log batch (output[0]). + for line in batch["lines"]: + if RAY_TQDM_MAGIC in line or (self.allow_re and self.allow_re.search(line)): + output[0]["lines"].append(line) + continue + elif self.skip_re and self.skip_re.search(line): + continue + dedup_key = _canonicalise_log_line(line) + + if dedup_key == "": + # Don't dedup messages that are empty after canonicalization. + # Because that's all the information users want to see. + output[0]["lines"].append(line) + continue + + if dedup_key in self.recent: + sources = self.recent[dedup_key].sources + sources.add(source) + # We deduplicate the warnings/error messages from raylet by default. + if len(sources) > 1 or batch["pid"] == "raylet": + state = self.recent[dedup_key] + self.recent[dedup_key] = DedupState( + state.timestamp, + state.count + 1, + line, + metadata, + sources, + ) + else: + # Don't dedup messages from the same source, just print. + output[0]["lines"].append(line) + else: + self.recent[dedup_key] = DedupState(now, 0, line, metadata, {source}) + output[0]["lines"].append(line) + + # Flush patterns from the buffer that are older than the aggregation window. + while self.recent: + if now - next(iter(self.recent.values())).timestamp < self.agg_window_s: + break + dedup_key = next(iter(self.recent)) + state = self.recent.pop(dedup_key) + # we already logged an instance of this line immediately when received, + # so don't log for count == 0 + if state.count > 1: + # (Actor pid=xxxx) [repeated 2x across cluster] ... + output.append(dict(**state.metadata, lines=[state.formatted()])) + # Continue aggregating for this key but reset timestamp and count. + state.timestamp = now + state.count = 0 + self.recent[dedup_key] = state + elif state.count > 0: + # Aggregation wasn't fruitful, print the line and stop aggregating. + output.append(dict(state.metadata, lines=[state.line])) + + return output + + def flush(self) -> List[dict]: + """Return all buffered log messages and clear the buffer. + + Returns: + List of log batches to print. + """ + output = [] + for state in self.recent.values(): + if state.count > 1: + output.append( + dict( + state.metadata, + lines=[state.formatted()], + ) + ) + elif state.count > 0: + output.append(dict(state.metadata, **{"lines": [state.line]})) + self.recent.clear() + return output + + +def _warn_once() -> str: + if log_once("log_dedup_warning"): + return ( + " (Ray deduplicates logs by default. Set RAY_DEDUP_LOGS=0 to " + "disable log deduplication, or see https://docs.ray.io/en/master/" + "ray-observability/user-guides/configure-logging.html#log-deduplication " + "for more options.)" + ) + else: + return "" + + +def _color(msg: str) -> str: + return "{}{}{}".format(colorama.Fore.GREEN, msg, colorama.Style.RESET_ALL) + + +stdout_deduplicator = LogDeduplicator( + RAY_DEDUP_LOGS_AGG_WINDOW_S, RAY_DEDUP_LOGS_ALLOW_REGEX, RAY_DEDUP_LOGS_SKIP_REGEX +) +stderr_deduplicator = LogDeduplicator( + RAY_DEDUP_LOGS_AGG_WINDOW_S, RAY_DEDUP_LOGS_ALLOW_REGEX, RAY_DEDUP_LOGS_SKIP_REGEX +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef55d7fee8eb4d0f86bc8c8730ae499e91e0dc83 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/constants.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dbbb652ecb2f821f69e3c33dfb5186c1c3aefb1 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/constants.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/default_impl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/default_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c5b9274206d4f0fd81e391381b230ea396be34b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/default_impl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/filters.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/filters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2d0317d42322ba550ec33060478e0a09e651a403 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/filters.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/formatters.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/formatters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db05d1ceb1f0adb2e8b1b2e2bce1bd38038fa0a7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/formatters.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/logging_config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/logging_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9da42ea5eedc063e5ad343d72c7e46c6d0270c49 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/__pycache__/logging_config.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..6accad120006413f52022320f271ad3f6969c0d8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/constants.py @@ -0,0 +1,58 @@ +from enum import Enum + +# A set containing the standard attributes of a LogRecord. This is used to +# help us determine which attributes constitute Ray or user-provided context. It is +# also be used to determine whether a attribute is a standard python logging attribute. +# http://docs.python.org/library/logging.html#logrecord-attributes +LOGRECORD_STANDARD_ATTRS = { + "args", + "asctime", + "created", + "exc_info", + "exc_text", + "filename", + "funcName", + "levelname", + "levelno", + "lineno", + "message", + "module", + "msecs", + "msg", + "name", + "pathname", + "process", + "processName", + "relativeCreated", + "stack_info", + "thread", + "threadName", + "taskName", +} + +LOGGER_FLATTEN_KEYS = { + "ray_serve_extra_fields", +} + + +class LogKey(str, Enum): + # Core context + JOB_ID = "job_id" + WORKER_ID = "worker_id" + NODE_ID = "node_id" + ACTOR_ID = "actor_id" + TASK_ID = "task_id" + ACTOR_NAME = "actor_name" + TASK_NAME = "task_name" + TASK_FUNCTION_NAME = "task_func_name" + + # Logger built-in context + ASCTIME = "asctime" + LEVELNAME = "levelname" + MESSAGE = "message" + FILENAME = "filename" + LINENO = "lineno" + EXC_TEXT = "exc_text" + + # Ray logging context + TIMESTAMP_NS = "timestamp_ns" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/default_impl.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/default_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..3901baaa956f3fd35cdfd8a3fa89ee5878137893 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/default_impl.py @@ -0,0 +1,4 @@ +def get_logging_configurator(): + from ray._private.ray_logging.logging_config import DefaultLoggingConfigurator + + return DefaultLoggingConfigurator() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/filters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..d2c5841d34ce0acbda893c498ec75cde629d2edb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/filters.py @@ -0,0 +1,33 @@ +import logging + +import ray +from ray._private.ray_logging.constants import LogKey + + +class CoreContextFilter(logging.Filter): + def filter(self, record): + if not ray.is_initialized(): + # There is no additional context if ray is not initialized + return True + + runtime_context = ray.get_runtime_context() + setattr(record, LogKey.JOB_ID.value, runtime_context.get_job_id()) + setattr(record, LogKey.WORKER_ID.value, runtime_context.get_worker_id()) + setattr(record, LogKey.NODE_ID.value, runtime_context.get_node_id()) + if runtime_context.worker.mode == ray.WORKER_MODE: + actor_id = runtime_context.get_actor_id() + if actor_id is not None: + setattr(record, LogKey.ACTOR_ID.value, actor_id) + task_id = runtime_context.get_task_id() + if task_id is not None: + setattr(record, LogKey.TASK_ID.value, task_id) + task_name = runtime_context.get_task_name() + if task_name is not None: + setattr(record, LogKey.TASK_NAME.value, task_name) + task_function_name = runtime_context.get_task_function_name() + if task_function_name is not None: + setattr(record, LogKey.TASK_FUNCTION_NAME.value, task_function_name) + actor_name = runtime_context.get_actor_name() + if actor_name is not None: + setattr(record, LogKey.ACTOR_NAME.value, actor_name) + return True diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/formatters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/formatters.py new file mode 100644 index 0000000000000000000000000000000000000000..9c1cc8a51e40e4d202936bf7bb1f6df6df18bf58 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/formatters.py @@ -0,0 +1,119 @@ +import json +import logging +from abc import ABC, abstractmethod +from typing import Any, Dict, List + +from ray._private.log import INTERNAL_TIMESTAMP_LOG_KEY +from ray._private.ray_constants import LOGGER_FORMAT +from ray._private.ray_logging.constants import ( + LOGGER_FLATTEN_KEYS, + LOGRECORD_STANDARD_ATTRS, + LogKey, +) + + +def _append_flatten_attributes(formatted_attrs: Dict[str, Any], key: str, value: Any): + """Flatten the dictionary values for special keys and append the values in place. + + If the key is in `LOGGER_FLATTEN_KEYS`, the value will be flattened and appended + to the `formatted_attrs` dictionary. Otherwise, the key-value pair will be appended + directly. + """ + if key in LOGGER_FLATTEN_KEYS: + if not isinstance(value, dict): + raise ValueError( + f"Expected a dictionary passing into {key}, but got {type(value)}" + ) + for k, v in value.items(): + if k in formatted_attrs: + raise KeyError(f"Found duplicated key in the log record: {k}") + formatted_attrs[k] = v + else: + formatted_attrs[key] = value + + +class AbstractFormatter(logging.Formatter, ABC): + def __init__(self, fmt=None, datefmt=None, style="%", validate=True) -> None: + super().__init__(fmt, datefmt, style, validate) + self._additional_log_standard_attrs = [] + + def set_additional_log_standard_attrs( + self, additional_log_standard_attrs: List[str] + ) -> None: + self._additional_log_standard_attrs = additional_log_standard_attrs + + @property + def additional_log_standard_attrs(self) -> List[str]: + return self._additional_log_standard_attrs + + def generate_record_format_attrs( + self, + record: logging.LogRecord, + exclude_default_standard_attrs, + ) -> dict: + record_format_attrs = {} + + # If `exclude_default_standard_attrs` is False, include the standard attributes. + # Otherwise, include only Ray and user-provided context. + if not exclude_default_standard_attrs: + record_format_attrs.update( + { + LogKey.ASCTIME.value: self.formatTime(record), + LogKey.LEVELNAME.value: record.levelname, + LogKey.MESSAGE.value: record.getMessage(), + LogKey.FILENAME.value: record.filename, + LogKey.LINENO.value: record.lineno, + } + ) + if record.exc_info: + if not record.exc_text: + record.exc_text = self.formatException(record.exc_info) + record_format_attrs[LogKey.EXC_TEXT.value] = record.exc_text + + # Add the user specified additional standard attributes. + for key in self._additional_log_standard_attrs: + _append_flatten_attributes( + record_format_attrs, key, getattr(record, key, None) + ) + + for key, value in record.__dict__.items(): + # Both Ray and user-provided context are stored in `record_format`. + if key not in LOGRECORD_STANDARD_ATTRS: + _append_flatten_attributes(record_format_attrs, key, value) + + # Format the internal timestamp to the standardized `timestamp_ns` key. + if INTERNAL_TIMESTAMP_LOG_KEY in record_format_attrs: + record_format_attrs[LogKey.TIMESTAMP_NS.value] = record_format_attrs.pop( + INTERNAL_TIMESTAMP_LOG_KEY + ) + + return record_format_attrs + + @abstractmethod + def format(self, record: logging.LogRecord) -> str: + pass + + +class JSONFormatter(AbstractFormatter): + def format(self, record: logging.LogRecord) -> str: + record_format_attrs = self.generate_record_format_attrs( + record, exclude_default_standard_attrs=False + ) + return json.dumps(record_format_attrs) + + +class TextFormatter(AbstractFormatter): + def __init__(self, fmt=None, datefmt=None, style="%", validate=True) -> None: + super().__init__(fmt, datefmt, style, validate) + self._inner_formatter = logging.Formatter(LOGGER_FORMAT) + + def format(self, record: logging.LogRecord) -> str: + s = self._inner_formatter.format(record) + record_format_attrs = self.generate_record_format_attrs( + record, exclude_default_standard_attrs=True + ) + + additional_attrs = " ".join( + [f"{key}={value}" for key, value in record_format_attrs.items()] + ) + return f"{s} {additional_attrs}" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/logging_config.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/logging_config.py new file mode 100644 index 0000000000000000000000000000000000000000..843935d6b415d510e2ddf09d187d172e288eefba --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_logging/logging_config.py @@ -0,0 +1,161 @@ +import logging +from abc import ABC, abstractmethod +from dataclasses import dataclass, field +from typing import Set + +from ray._private.ray_logging import default_impl +from ray._private.ray_logging.constants import LOGRECORD_STANDARD_ATTRS +from ray._private.ray_logging.filters import CoreContextFilter +from ray._private.ray_logging.formatters import JSONFormatter, TextFormatter +from ray.util.annotations import PublicAPI + + +class LoggingConfigurator(ABC): + @abstractmethod + def get_supported_encodings(self) -> Set[str]: + raise NotImplementedError + + @abstractmethod + def configure(self, logging_config: "LoggingConfig"): + raise NotImplementedError + + +class DefaultLoggingConfigurator(LoggingConfigurator): + def __init__(self): + self._encoding_to_formatter = { + "TEXT": TextFormatter(), + "JSON": JSONFormatter(), + } + + def get_supported_encodings(self) -> Set[str]: + return self._encoding_to_formatter.keys() + + def configure(self, logging_config: "LoggingConfig"): + formatter = self._encoding_to_formatter[logging_config.encoding] + formatter.set_additional_log_standard_attrs( + logging_config.additional_log_standard_attrs + ) + + core_context_filter = CoreContextFilter() + handler = logging.StreamHandler() + handler.setLevel(logging_config.log_level) + handler.setFormatter(formatter) + handler.addFilter(core_context_filter) + + root_logger = logging.getLogger() + root_logger.setLevel(logging_config.log_level) + root_logger.addHandler(handler) + + ray_logger = logging.getLogger("ray") + ray_logger.setLevel(logging_config.log_level) + # Remove all existing handlers added by `ray/__init__.py`. + for h in ray_logger.handlers[:]: + ray_logger.removeHandler(h) + ray_logger.addHandler(handler) + ray_logger.propagate = False + + +_logging_configurator: LoggingConfigurator = default_impl.get_logging_configurator() + + +# Class defines the logging configurations for a Ray job. +# To add a new logging configuration: (1) add a new field to this class; (2) Update the +# logic in the __post_init__ method in this class to add the validation logic; +# (3) Update the configure method in the DefaultLoggingConfigurator +# class to use the new field. +@PublicAPI(stability="alpha") +@dataclass +class LoggingConfig: + encoding: str = "TEXT" + log_level: str = "INFO" + # The list of valid attributes are defined as LOGRECORD_STANDARD_ATTRS in + # constants.py. + additional_log_standard_attrs: list = field(default_factory=list) + + def __post_init__(self): + if self.encoding not in _logging_configurator.get_supported_encodings(): + raise ValueError( + f"Invalid encoding type: {self.encoding}. " + "Valid encoding types are: " + f"{list(_logging_configurator.get_supported_encodings())}" + ) + + for attr in self.additional_log_standard_attrs: + if attr not in LOGRECORD_STANDARD_ATTRS: + raise ValueError( + f"Unknown python logging standard attribute: {attr}. " + "The valid attributes are: " + f"{LOGRECORD_STANDARD_ATTRS}" + ) + + def _configure_logging(self): + """Set up the logging configuration for the current process.""" + _logging_configurator.configure(self) + + def _apply(self): + """Set up the logging configuration.""" + self._configure_logging() + + +LoggingConfig.__doc__ = """ + Logging configuration for a Ray job. These configurations are used to set up the + root logger of the driver process and all Ray tasks and actor processes that belong + to the job. + + Examples: 1. Configure the logging to use TEXT encoding. + .. testcode:: + + import ray + import logging + + ray.init( + logging_config=ray.LoggingConfig(encoding="TEXT", log_level="INFO", additional_log_standard_attrs=['name']) + ) + + @ray.remote + def f(): + logger = logging.getLogger(__name__) + logger.info("This is a Ray task") + + ray.get(f.remote()) + ray.shutdown() + + .. testoutput:: + :options: +MOCK + + 2025-02-12 12:25:16,836 INFO test-log-config.py:11 -- This is a Ray task name=__main__ job_id=01000000 worker_id=51188d9448be4664bf2ea26ac410b67acaaa970c4f31c5ad3ae776a5 node_id=f683dfbffe2c69984859bc19c26b77eaf3866c458884c49d115fdcd4 task_id=c8ef45ccd0112571ffffffffffffffffffffffff01000000 task_name=f task_func_name=test-log-config.f timestamp_ns=1739391916836884000 + + 2. Configure the logging to use JSON encoding. + .. testcode:: + + import ray + import logging + + ray.init( + logging_config=ray.LoggingConfig(encoding="JSON", log_level="INFO", additional_log_standard_attrs=['name']) + ) + + @ray.remote + def f(): + logger = logging.getLogger(__name__) + logger.info("This is a Ray task") + + ray.get(f.remote()) + ray.shutdown() + + .. testoutput:: + :options: +MOCK + + {"asctime": "2025-02-12 12:25:48,766", "levelname": "INFO", "message": "This is a Ray task", "filename": "test-log-config.py", "lineno": 11, "name": "__main__", "job_id": "01000000", "worker_id": "6d307578014873fcdada0fa22ea6d49e0fb1f78960e69d61dfe41f5a", "node_id": "69e3a5e68bdc7eb8ac9abb3155326ee3cc9fc63ea1be04d11c0d93c7", "task_id": "c8ef45ccd0112571ffffffffffffffffffffffff01000000", "task_name": "f", "task_func_name": "test-log-config.f", "timestamp_ns": 1739391948766949000} + + Args: + encoding: Encoding type for the logs. The valid values are + {list(_logging_configurator.get_supported_encodings())} + log_level: Log level for the logs. Defaults to 'INFO'. You can set + it to 'DEBUG' to receive more detailed debug logs. + additional_log_standard_attrs: List of additional standard python logger attributes to + include in the log. Defaults to an empty list. The list of already + included standard attributes are: "asctime", "levelname", "message", + "filename", "lineno", "exc_text". The list of valid attributes are specified + here: http://docs.python.org/library/logging.html#logrecord-attributes + """ # noqa: E501 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_microbenchmark_helpers.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_microbenchmark_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..f2986ab792bdcc1e2f5f16bda3e88d1e0e087c87 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_microbenchmark_helpers.py @@ -0,0 +1,92 @@ +import os +import time +from contextlib import contextmanager +from typing import List, Optional, Tuple + +import numpy as np + +import ray + +# Only run tests matching this filter pattern. + +filter_pattern = os.environ.get("TESTS_TO_RUN", "") +skip_pattern = os.environ.get("TESTS_TO_SKIP", "") + + +def timeit( + name, fn, multiplier=1, warmup_time_sec=10 +) -> List[Optional[Tuple[str, float, float]]]: + if filter_pattern and filter_pattern not in name: + return [None] + if skip_pattern and skip_pattern in name: + return [None] + # sleep for a while to avoid noisy neigbhors. + # related issue: https://github.com/ray-project/ray/issues/22045 + time.sleep(warmup_time_sec) + # warmup + start = time.perf_counter() + count = 0 + while time.perf_counter() - start < 1: + fn() + count += 1 + # real run + step = count // 10 + 1 + stats = [] + for _ in range(4): + start = time.perf_counter() + count = 0 + while time.perf_counter() - start < 2: + for _ in range(step): + fn() + count += step + end = time.perf_counter() + stats.append(multiplier * count / (end - start)) + + mean = np.mean(stats) + sd = np.std(stats) + print(name, "per second", round(mean, 2), "+-", round(sd, 2)) + return [(name, mean, sd)] + + +async def asyncio_timeit( + name, async_fn, multiplier=1, warmup_time_sec=10 +) -> List[Optional[Tuple[str, float, float]]]: + if filter_pattern and filter_pattern not in name: + return [None] + if skip_pattern and skip_pattern in name: + return [None] + # sleep for a while to avoid noisy neigbhors. + # related issue: https://github.com/ray-project/ray/issues/22045 + time.sleep(warmup_time_sec) + # warmup + start = time.perf_counter() + count = 0 + while time.perf_counter() - start < 1: + await async_fn() + count += 1 + # real run + step = count // 10 + 1 + stats = [] + for _ in range(4): + start = time.perf_counter() + count = 0 + while time.perf_counter() - start < 2: + for _ in range(step): + await async_fn() + count += step + end = time.perf_counter() + stats.append(multiplier * count / (end - start)) + + mean = np.mean(stats) + sd = np.std(stats) + print(name, "per second", round(mean, 2), "+-", round(sd, 2)) + return [(name, mean, sd)] + + +@contextmanager +def ray_setup_and_teardown(**init_args): + ray.init(**init_args) + try: + yield None + finally: + ray.shutdown() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_option_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_option_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..46291d4bf6371bbe54daa11b1f3b9bcf82e8a7ca --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_option_utils.py @@ -0,0 +1,391 @@ +"""Manage, parse and validate options for Ray tasks, actors and actor methods.""" +import warnings +from dataclasses import dataclass +from typing import Any, Callable, Dict, Optional, Tuple, Union + +import ray +from ray._private import ray_constants +from ray._private.label_utils import ( + validate_label_selector, +) +from ray._private.utils import get_ray_doc_version +from ray.util.placement_group import PlacementGroup +from ray.util.scheduling_strategies import ( + NodeAffinitySchedulingStrategy, + NodeLabelSchedulingStrategy, + PlacementGroupSchedulingStrategy, +) + + +@dataclass +class Option: + # Type constraint of an option. + type_constraint: Optional[Union[type, Tuple[type]]] = None + # Value constraint of an option. + # The callable should return None if there is no error. + # Otherwise, return the error message. + value_constraint: Optional[Callable[[Any], Optional[str]]] = None + # Default value. + default_value: Any = None + + def validate(self, keyword: str, value: Any): + """Validate the option.""" + if self.type_constraint is not None: + if not isinstance(value, self.type_constraint): + raise TypeError( + f"The type of keyword '{keyword}' must be {self.type_constraint}, " + f"but received type {type(value)}" + ) + if self.value_constraint is not None: + possible_error_message = self.value_constraint(value) + if possible_error_message: + raise ValueError(possible_error_message) + + +def _counting_option(name: str, infinite: bool = True, default_value: Any = None): + """This is used for positive and discrete options. + + Args: + name: The name of the option keyword. + infinite: If True, user could use -1 to represent infinity. + default_value: The default value for this option. + """ + if infinite: + return Option( + (int, type(None)), + lambda x: None + if (x is None or x >= -1) + else f"The keyword '{name}' only accepts None, 0, -1" + " or a positive integer, where -1 represents infinity.", + default_value=default_value, + ) + return Option( + (int, type(None)), + lambda x: None + if (x is None or x >= 0) + else f"The keyword '{name}' only accepts None, 0 or a positive integer.", + default_value=default_value, + ) + + +def _validate_resource_quantity(name, quantity): + if quantity < 0: + return f"The quantity of resource {name} cannot be negative" + if ( + isinstance(quantity, float) + and quantity != 0.0 + and int(quantity * ray._raylet.RESOURCE_UNIT_SCALING) == 0 + ): + return ( + f"The precision of the fractional quantity of resource {name}" + " cannot go beyond 0.0001" + ) + resource_name = "GPU" if name == "num_gpus" else name + if resource_name in ray._private.accelerators.get_all_accelerator_resource_names(): + ( + valid, + error_message, + ) = ray._private.accelerators.get_accelerator_manager_for_resource( + resource_name + ).validate_resource_request_quantity( + quantity + ) + if not valid: + return error_message + return None + + +def _resource_option(name: str, default_value: Any = None): + """This is used for resource related options.""" + return Option( + (float, int, type(None)), + lambda x: None if (x is None) else _validate_resource_quantity(name, x), + default_value=default_value, + ) + + +def _validate_resources(resources: Optional[Dict[str, float]]) -> Optional[str]: + if resources is None: + return None + + if "CPU" in resources or "GPU" in resources: + return ( + "Use the 'num_cpus' and 'num_gpus' keyword instead of 'CPU' and 'GPU' " + "in 'resources' keyword" + ) + + for name, quantity in resources.items(): + possible_error_message = _validate_resource_quantity(name, quantity) + if possible_error_message: + return possible_error_message + + return None + + +_common_options = { + "label_selector": Option((dict, type(None)), lambda x: validate_label_selector(x)), + "accelerator_type": Option((str, type(None))), + "memory": _resource_option("memory"), + "name": Option((str, type(None))), + "num_cpus": _resource_option("num_cpus"), + "num_gpus": _resource_option("num_gpus"), + "object_store_memory": _counting_option("object_store_memory", False), + # TODO(suquark): "placement_group", "placement_group_bundle_index" + # and "placement_group_capture_child_tasks" are deprecated, + # use "scheduling_strategy" instead. + "placement_group": Option( + (type(None), str, PlacementGroup), default_value="default" + ), + "placement_group_bundle_index": Option(int, default_value=-1), + "placement_group_capture_child_tasks": Option((bool, type(None))), + "resources": Option((dict, type(None)), lambda x: _validate_resources(x)), + "runtime_env": Option((dict, type(None))), + "scheduling_strategy": Option( + ( + type(None), + str, + PlacementGroupSchedulingStrategy, + NodeAffinitySchedulingStrategy, + NodeLabelSchedulingStrategy, + ) + ), + "_metadata": Option((dict, type(None))), + "enable_task_events": Option(bool, default_value=True), + "_labels": Option((dict, type(None))), +} + + +def issubclass_safe(obj: Any, cls_: type) -> bool: + try: + return issubclass(obj, cls_) + except TypeError: + return False + + +_task_only_options = { + "max_calls": _counting_option("max_calls", False, default_value=0), + # Normal tasks may be retried on failure this many times. + # TODO(swang): Allow this to be set globally for an application. + "max_retries": _counting_option( + "max_retries", default_value=ray_constants.DEFAULT_TASK_MAX_RETRIES + ), + # override "_common_options" + "num_cpus": _resource_option("num_cpus", default_value=1), + "num_returns": Option( + (int, str, type(None)), + lambda x: None + if (x is None or x == "dynamic" or x == "streaming" or x >= 0) + else "Default None. When None is passed, " + "The default value is 1 for a task and actor task, and " + "'streaming' for generator tasks and generator actor tasks. " + "The keyword 'num_returns' only accepts None, " + "a non-negative integer, " + "'streaming' (for generators), or 'dynamic'. 'dynamic' flag " + "will be deprecated in the future, and it is recommended to use " + "'streaming' instead.", + default_value=None, + ), + "object_store_memory": Option( # override "_common_options" + (int, type(None)), + lambda x: None + if (x is None) + else "Setting 'object_store_memory' is not implemented for tasks", + ), + "retry_exceptions": Option( + (bool, list, tuple), + lambda x: None + if ( + isinstance(x, bool) + or ( + isinstance(x, (list, tuple)) + and all(issubclass_safe(x_, Exception) for x_ in x) + ) + ) + else "retry_exceptions must be either a boolean or a list of exceptions", + default_value=False, + ), + "_generator_backpressure_num_objects": Option( + (int, type(None)), + lambda x: None + if x != 0 + else ( + "_generator_backpressure_num_objects=0 is not allowed. " + "Use a value > 0. If the value is equal to 1, the behavior " + "is identical to Python generator (generator 1 object " + "whenever `next` is called). Use -1 to disable this feature. " + ), + ), +} + +_actor_only_options = { + "concurrency_groups": Option((list, dict, type(None))), + "lifetime": Option( + (str, type(None)), + lambda x: None + if x in (None, "detached", "non_detached") + else "actor `lifetime` argument must be one of 'detached', " + "'non_detached' and 'None'.", + ), + "max_concurrency": _counting_option("max_concurrency", False), + "max_restarts": _counting_option("max_restarts", default_value=0), + "max_task_retries": _counting_option("max_task_retries", default_value=0), + "max_pending_calls": _counting_option("max_pending_calls", default_value=-1), + "namespace": Option((str, type(None))), + "get_if_exists": Option(bool, default_value=False), +} + +# Priority is important here because during dictionary update, same key with higher +# priority overrides the same key with lower priority. We make use of priority +# to set the correct default value for tasks / actors. + +# priority: _common_options > _actor_only_options > _task_only_options +valid_options: Dict[str, Option] = { + **_task_only_options, + **_actor_only_options, + **_common_options, +} +# priority: _task_only_options > _common_options +task_options: Dict[str, Option] = {**_common_options, **_task_only_options} +# priority: _actor_only_options > _common_options +actor_options: Dict[str, Option] = {**_common_options, **_actor_only_options} + +remote_args_error_string = ( + "The @ray.remote decorator must be applied either with no arguments and no " + "parentheses, for example '@ray.remote', or it must be applied using some of " + f"the arguments in the list {list(valid_options.keys())}, for example " + "'@ray.remote(num_returns=2, resources={\"CustomResource\": 1})'." +) + + +def _check_deprecate_placement_group(options: Dict[str, Any]): + """Check if deprecated placement group option exists.""" + placement_group = options.get("placement_group", "default") + scheduling_strategy = options.get("scheduling_strategy") + # TODO(suquark): @ray.remote(placement_group=None) is used in + # "python/ray.data._internal/remote_fn.py" and many other places, + # while "ray.data.read_api.read_datasource" set "scheduling_strategy=SPREAD". + # This might be a bug, but it is also ok to allow them co-exist. + if (placement_group not in ("default", None)) and (scheduling_strategy is not None): + raise ValueError( + "Placement groups should be specified via the " + "scheduling_strategy option. " + "The placement_group option is deprecated." + ) + + +def _warn_if_using_deprecated_placement_group( + options: Dict[str, Any], caller_stacklevel: int +): + placement_group = options["placement_group"] + placement_group_bundle_index = options["placement_group_bundle_index"] + placement_group_capture_child_tasks = options["placement_group_capture_child_tasks"] + if placement_group != "default": + warnings.warn( + "placement_group parameter is deprecated. Use " + "scheduling_strategy=PlacementGroupSchedulingStrategy(...) " + "instead, see the usage at " + f"https://docs.ray.io/en/{get_ray_doc_version()}/ray-core/package-ref.html#ray-remote.", # noqa: E501 + DeprecationWarning, + stacklevel=caller_stacklevel + 1, + ) + if placement_group_bundle_index != -1: + warnings.warn( + "placement_group_bundle_index parameter is deprecated. Use " + "scheduling_strategy=PlacementGroupSchedulingStrategy(...) " + "instead, see the usage at " + f"https://docs.ray.io/en/{get_ray_doc_version()}/ray-core/package-ref.html#ray-remote.", # noqa: E501 + DeprecationWarning, + stacklevel=caller_stacklevel + 1, + ) + if placement_group_capture_child_tasks: + warnings.warn( + "placement_group_capture_child_tasks parameter is deprecated. Use " + "scheduling_strategy=PlacementGroupSchedulingStrategy(...) " + "instead, see the usage at " + f"https://docs.ray.io/en/{get_ray_doc_version()}/ray-core/package-ref.html#ray-remote.", # noqa: E501 + DeprecationWarning, + stacklevel=caller_stacklevel + 1, + ) + + +def validate_task_options(options: Dict[str, Any], in_options: bool): + """Options check for Ray tasks. + + Args: + options: Options for Ray tasks. + in_options: If True, we are checking the options under the context of + ".options()". + """ + for k, v in options.items(): + if k not in task_options: + raise ValueError( + f"Invalid option keyword {k} for remote functions. " + f"Valid ones are {list(task_options)}." + ) + task_options[k].validate(k, v) + if in_options and "max_calls" in options: + raise ValueError("Setting 'max_calls' is not supported in '.options()'.") + _check_deprecate_placement_group(options) + + +def validate_actor_options(options: Dict[str, Any], in_options: bool): + """Options check for Ray actors. + + Args: + options: Options for Ray actors. + in_options: If True, we are checking the options under the context of + ".options()". + """ + for k, v in options.items(): + if k not in actor_options: + raise ValueError( + f"Invalid option keyword {k} for actors. " + f"Valid ones are {list(actor_options)}." + ) + actor_options[k].validate(k, v) + + if in_options and "concurrency_groups" in options: + raise ValueError( + "Setting 'concurrency_groups' is not supported in '.options()'." + ) + + if options.get("get_if_exists") and not options.get("name"): + raise ValueError("The actor name must be specified to use `get_if_exists`.") + + if "object_store_memory" in options: + warnings.warn( + "Setting 'object_store_memory'" + " for actors is deprecated since it doesn't actually" + " reserve the required object store memory." + f" Use object spilling that's enabled by default (https://docs.ray.io/en/{get_ray_doc_version()}/ray-core/objects/object-spilling.html) " # noqa: E501 + "instead to bypass the object store memory size limitation.", + DeprecationWarning, + stacklevel=1, + ) + + _check_deprecate_placement_group(options) + + +def update_options( + original_options: Dict[str, Any], new_options: Dict[str, Any] +) -> Dict[str, Any]: + """Update original options with new options and return. + The returned updated options contain shallow copy of original options. + """ + + updated_options = {**original_options, **new_options} + # Ensure we update each namespace in "_metadata" independently. + # "_metadata" is a dict like {namespace1: config1, namespace2: config2} + if ( + original_options.get("_metadata") is not None + and new_options.get("_metadata") is not None + ): + # make a shallow copy to avoid messing up the metadata dict in + # the original options. + metadata = original_options["_metadata"].copy() + for namespace, config in new_options["_metadata"].items(): + metadata[namespace] = {**metadata.get(namespace, {}), **config} + + updated_options["_metadata"] = metadata + + return updated_options diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_perf.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_perf.py new file mode 100644 index 0000000000000000000000000000000000000000..04e6d817d656e19c64765c10a55fe14eec2bc9e2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_perf.py @@ -0,0 +1,330 @@ +"""This is the script for `ray microbenchmark`.""" + +import asyncio +import logging +import multiprocessing + +import numpy as np + +import ray +from ray._private.ray_client_microbenchmark import main as client_microbenchmark_main +from ray._private.ray_microbenchmark_helpers import timeit + +logger = logging.getLogger(__name__) + + +@ray.remote(num_cpus=0) +class Actor: + def small_value(self): + return b"ok" + + def small_value_arg(self, x): + return b"ok" + + def small_value_batch(self, n): + ray.get([small_value.remote() for _ in range(n)]) + + +@ray.remote +class AsyncActor: + async def small_value(self): + return b"ok" + + async def small_value_with_arg(self, x): + return b"ok" + + async def small_value_batch(self, n): + await asyncio.wait([small_value.remote() for _ in range(n)]) + + +@ray.remote(num_cpus=0) +class Client: + def __init__(self, servers): + if not isinstance(servers, list): + servers = [servers] + self.servers = servers + + def small_value_batch(self, n): + results = [] + for s in self.servers: + results.extend([s.small_value.remote() for _ in range(n)]) + ray.get(results) + + def small_value_batch_arg(self, n): + x = ray.put(0) + results = [] + for s in self.servers: + results.extend([s.small_value_arg.remote(x) for _ in range(n)]) + ray.get(results) + + +@ray.remote +def small_value(): + return b"ok" + + +@ray.remote +def small_value_batch(n): + submitted = [small_value.remote() for _ in range(n)] + ray.get(submitted) + return 0 + + +@ray.remote +def create_object_containing_ref(): + obj_refs = [] + for _ in range(10000): + obj_refs.append(ray.put(1)) + return obj_refs + + +def check_optimized_build(): + if not ray._raylet.OPTIMIZED: + msg = ( + "WARNING: Unoptimized build! " + "To benchmark an optimized build, try:\n" + "\tbazel build -c opt //:ray_pkg\n" + "You can also make this permanent by adding\n" + "\tbuild --compilation_mode=opt\n" + "to your user-wide ~/.bazelrc file. " + "(Do not add this to the project-level .bazelrc file.)" + ) + logger.warning(msg) + + +def main(results=None): + results = results or [] + + check_optimized_build() + + print("Tip: set TESTS_TO_RUN='pattern' to run a subset of benchmarks") + + ray.init() + + value = ray.put(0) + + def get_small(): + ray.get(value) + + def put_small(): + ray.put(0) + + @ray.remote + def do_put_small(): + for _ in range(100): + ray.put(0) + + def put_multi_small(): + ray.get([do_put_small.remote() for _ in range(10)]) + + arr = np.zeros(100 * 1024 * 1024, dtype=np.int64) + + results += timeit("single client get calls (Plasma Store)", get_small) + + results += timeit("single client put calls (Plasma Store)", put_small) + + results += timeit("multi client put calls (Plasma Store)", put_multi_small, 1000) + + def put_large(): + ray.put(arr) + + results += timeit("single client put gigabytes", put_large, 8 * 0.1) + + def small_value_batch(): + submitted = [small_value.remote() for _ in range(1000)] + ray.get(submitted) + return 0 + + results += timeit("single client tasks and get batch", small_value_batch) + + @ray.remote + def do_put(): + for _ in range(10): + ray.put(np.zeros(10 * 1024 * 1024, dtype=np.int64)) + + def put_multi(): + ray.get([do_put.remote() for _ in range(10)]) + + results += timeit("multi client put gigabytes", put_multi, 10 * 8 * 0.1) + + obj_containing_ref = create_object_containing_ref.remote() + + def get_containing_object_ref(): + ray.get(obj_containing_ref) + + results += timeit( + "single client get object containing 10k refs", get_containing_object_ref + ) + + def wait_multiple_refs(): + num_objs = 1000 + not_ready = [small_value.remote() for _ in range(num_objs)] + # We only need to trigger the fetch_local once for each object, + # raylet will persist these fetch requests even after ray.wait returns. + # See https://github.com/ray-project/ray/issues/30375. + fetch_local = True + for _ in range(num_objs): + _ready, not_ready = ray.wait(not_ready, fetch_local=fetch_local) + if fetch_local: + fetch_local = False + + results += timeit("single client wait 1k refs", wait_multiple_refs) + + def small_task(): + ray.get(small_value.remote()) + + results += timeit("single client tasks sync", small_task) + + def small_task_async(): + ray.get([small_value.remote() for _ in range(1000)]) + + results += timeit("single client tasks async", small_task_async, 1000) + + n = 10000 + m = 4 + actors = [Actor.remote() for _ in range(m)] + + def multi_task(): + submitted = [a.small_value_batch.remote(n) for a in actors] + ray.get(submitted) + + results += timeit("multi client tasks async", multi_task, n * m) + + a = Actor.remote() + + def actor_sync(): + ray.get(a.small_value.remote()) + + results += timeit("1:1 actor calls sync", actor_sync) + + a = Actor.remote() + + def actor_async(): + ray.get([a.small_value.remote() for _ in range(1000)]) + + results += timeit("1:1 actor calls async", actor_async, 1000) + + a = Actor.options(max_concurrency=16).remote() + + def actor_concurrent(): + ray.get([a.small_value.remote() for _ in range(1000)]) + + results += timeit("1:1 actor calls concurrent", actor_concurrent, 1000) + + n = 5000 + n_cpu = multiprocessing.cpu_count() // 2 + actors = [Actor._remote() for _ in range(n_cpu)] + client = Client.remote(actors) + + def actor_async_direct(): + ray.get(client.small_value_batch.remote(n)) + + results += timeit("1:n actor calls async", actor_async_direct, n * len(actors)) + + n_cpu = multiprocessing.cpu_count() // 2 + a = [Actor.remote() for _ in range(n_cpu)] + + @ray.remote + def work(actors): + ray.get([actors[i % n_cpu].small_value.remote() for i in range(n)]) + + def actor_multi2(): + ray.get([work.remote(a) for _ in range(m)]) + + results += timeit("n:n actor calls async", actor_multi2, m * n) + + n = 1000 + actors = [Actor._remote() for _ in range(n_cpu)] + clients = [Client.remote(a) for a in actors] + + def actor_multi2_direct_arg(): + ray.get([c.small_value_batch_arg.remote(n) for c in clients]) + + results += timeit( + "n:n actor calls with arg async", actor_multi2_direct_arg, n * len(clients) + ) + + a = AsyncActor.remote() + + def actor_sync(): + ray.get(a.small_value.remote()) + + results += timeit("1:1 async-actor calls sync", actor_sync) + + a = AsyncActor.remote() + + def async_actor(): + ray.get([a.small_value.remote() for _ in range(1000)]) + + results += timeit("1:1 async-actor calls async", async_actor, 1000) + + a = AsyncActor.remote() + + def async_actor(): + ray.get([a.small_value_with_arg.remote(i) for i in range(1000)]) + + results += timeit("1:1 async-actor calls with args async", async_actor, 1000) + + n = 5000 + n_cpu = multiprocessing.cpu_count() // 2 + actors = [AsyncActor.remote() for _ in range(n_cpu)] + client = Client.remote(actors) + + def async_actor_async(): + ray.get(client.small_value_batch.remote(n)) + + results += timeit("1:n async-actor calls async", async_actor_async, n * len(actors)) + + n = 5000 + m = 4 + n_cpu = multiprocessing.cpu_count() // 2 + a = [AsyncActor.remote() for _ in range(n_cpu)] + + @ray.remote + def async_actor_work(actors): + ray.get([actors[i % n_cpu].small_value.remote() for i in range(n)]) + + def async_actor_multi(): + ray.get([async_actor_work.remote(a) for _ in range(m)]) + + results += timeit("n:n async-actor calls async", async_actor_multi, m * n) + ray.shutdown() + + ############################ + # End of channel perf tests. + ############################ + + NUM_PGS = 100 + NUM_BUNDLES = 1 + ray.init(resources={"custom": 100}) + + def placement_group_create_removal(num_pgs): + pgs = [ + ray.util.placement_group( + bundles=[{"custom": 0.001} for _ in range(NUM_BUNDLES)] + ) + for _ in range(num_pgs) + ] + [pg.wait(timeout_seconds=30) for pg in pgs] + # Include placement group removal here to clean up. + # If we don't clean up placement groups, the whole performance + # gets slower as it runs more. + # Since timeit function runs multiple times without + # the cleaning logic, we should have this method here. + for pg in pgs: + ray.util.remove_placement_group(pg) + + results += timeit( + "placement group create/removal", + lambda: placement_group_create_removal(NUM_PGS), + NUM_PGS, + ) + ray.shutdown() + + client_microbenchmark_main(results) + + return results + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_process_reaper.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_process_reaper.py new file mode 100644 index 0000000000000000000000000000000000000000..5e15a5e35a9c40c719835f5bf15b8ca4da753a75 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/ray_process_reaper.py @@ -0,0 +1,60 @@ +import atexit +import os +import signal +import sys +import time + +""" +This is a lightweight "reaper" process used to ensure that ray processes are +cleaned up properly when the main ray process dies unexpectedly (e.g., +segfaults or gets SIGKILLed). Note that processes may not be cleaned up +properly if this process is SIGTERMed or SIGKILLed. + +It detects that its parent has died by reading from stdin, which must be +inherited from the parent process so that the OS will deliver an EOF if the +parent dies. When this happens, the reaper process kills the rest of its +process group (first attempting graceful shutdown with SIGTERM, then escalating +to SIGKILL). +""" + +SIGTERM_GRACE_PERIOD_SECONDS = 1 + + +def reap_process_group(*args): + def sigterm_handler(*args): + # Give a one-second grace period for other processes to clean up. + time.sleep(SIGTERM_GRACE_PERIOD_SECONDS) + # SIGKILL the pgroup (including ourselves) as a last-resort. + if sys.platform == "win32": + atexit.unregister(sigterm_handler) + os.kill(0, signal.CTRL_BREAK_EVENT) + else: + os.killpg(0, signal.SIGKILL) + + # Set a SIGTERM handler to handle SIGTERMing ourselves with the group. + if sys.platform == "win32": + atexit.register(sigterm_handler) + else: + signal.signal(signal.SIGTERM, sigterm_handler) + + # Our parent must have died, SIGTERM the group (including ourselves). + if sys.platform == "win32": + os.kill(0, signal.CTRL_C_EVENT) + else: + os.killpg(0, signal.SIGTERM) + + +def main(): + # Read from stdin forever. Because stdin is a file descriptor + # inherited from our parent process, we will get an EOF if the parent + # dies, which is signaled by an empty return from read(). + # We intentionally don't set any signal handlers here, so a SIGTERM from + # the parent can be used to kill this process gracefully without it killing + # the rest of the process group. + while len(sys.stdin.read()) != 0: + pass + reap_process_group() + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/resource_isolation_config.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/resource_isolation_config.py new file mode 100644 index 0000000000000000000000000000000000000000..d8523f2e4927f0e8f6af726677de7ce38e217a60 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/resource_isolation_config.py @@ -0,0 +1,255 @@ +import logging +from typing import Optional + +import ray._common.utils +import ray._private.ray_constants as ray_constants +import ray._private.utils as utils + +logger = logging.getLogger(__name__) + +# See https://docs.kernel.org/admin-guide/cgroup-v2.html#weights +# for information about cpu weights +_CGROUP_CPU_MAX_WEIGHT: int = 10000 + + +class ResourceIsolationConfig: + """Configuration for enabling resource isolation by reserving memory + and cpu for ray system processes through cgroupv2. + This class validates configuration for resource isolation by + enforcing types, correct combinations of values, applying default values, + and sanity checking cpu and memory reservations. + Also, converts system_reserved_cpu into cpu.weights for cgroupv2. + + Raises: + ValueError: On invalid inputs. + + Attributes: + enable_resource_isolation: True if cgroupv2 based isolation of ray + system processes is enabled. + cgroup_path: The path for the cgroup the raylet should use to enforce + resource isolation. + system_reserved_cpu: The amount of cores reserved for ray system + processes. Must be >= ray_constants.MINIMUM_SYSTEM_RESERVED_CPU_CORES + and < the total number of cores available. + system_reserved_memory: The amount of memory in bytes reserved + for ray system processes. Must be >= ray_constants.MINIMUM_SYSTEM_RESERVED_MEMORY_BYTES + and system_reserved_cpu + object_store_bytes < the total memory available. + """ + + def __init__( + self, + enable_resource_isolation: bool = False, + cgroup_path: Optional[str] = None, + system_reserved_cpu: Optional[float] = None, + system_reserved_memory: Optional[int] = None, + ): + + self._resource_isolation_enabled = enable_resource_isolation + self.cgroup_path = cgroup_path + self.system_reserved_memory = system_reserved_memory + # cgroupv2 cpu.weight calculated from system_reserved_cpu + # assumes ray uses all available cores. + self.system_reserved_cpu_weight: int = None + # TODO(irabbani): this is used to ensure + # that object_store_memory is not added twice + # to self._system_reserved_memory. This should + # be refactored in the future so that ResourceIsolationConfig + # can take object_store_memory as a constructor parameter + # and be constructed fully by the constructor. + self._constructed = False + + if not enable_resource_isolation: + if system_reserved_cpu: + raise ValueError( + "system_reserved_cpu cannot be set when resource isolation is not enabled. " + "Set enable_resource_isolation to True if you're using ray.init or use the " + "--enable-resource-isolation flag if you're using the ray cli." + ) + + if self.system_reserved_memory: + raise ValueError( + "system_reserved_memory cannot be set when resource isolation is not enabled. " + "Set enable_resource_isolation to True if you're using ray.init or use the " + "--enable-resource-isolation flag if you're using the ray cli." + ) + if self.cgroup_path: + raise ValueError( + "cgroup_path cannot be set when resource isolation is not enabled. " + "Set enable_resource_isolation to True if you're using ray.init or use the " + "--enable-resource-isolation flag if you're using the ray cli." + ) + return + + # resource isolation is enabled + self.system_reserved_cpu_weight = self._validate_and_get_system_reserved_cpu( + system_reserved_cpu + ) + self.system_reserved_memory = self._validate_and_get_system_reserved_memory( + system_reserved_memory + ) + self.cgroup_path = self._validate_and_get_cgroup_path(cgroup_path) + + def is_enabled(self) -> bool: + return self._resource_isolation_enabled + + def add_object_store_memory(self, object_store_memory: int): + """This is only supposed to be called once. It also cannot be + called if resouce isolation is not enabled. + """ + assert self.is_enabled(), ( + "Cannot add object_store_memory to system_reserved_memory when " + "enable_resource_isolation is False." + ) + assert not self._constructed, ( + "Cannot add object_store_memory to system_reserved_memory when" + "multiple times." + ) + self.system_reserved_memory += object_store_memory + available_system_memory = ray._common.utils.get_system_memory() + if self.system_reserved_memory > available_system_memory: + raise ValueError( + f"The total requested system_reserved_memory={self.system_reserved_memory}, calculated by " + " object_store_bytes + system_reserved_memory, is greater than the total memory " + f" available={available_system_memory}. Pick a smaller number of bytes for object_store_bytes " + "or system_reserved_memory." + ) + self._constructed = True + + @staticmethod + def _validate_and_get_cgroup_path(cgroup_path: Optional[str]) -> str: + """Returns the ray_constants.DEFAULT_CGROUP_PATH if cgroup_path is not + specified. Checks the type of cgroup_path. + + Args: + cgroup_path: The path for the cgroup the raylet should use to enforce + resource isolation. + + Returns: + str: The validated cgroup path. + + Raises: + ValueError: If cgroup_path is not a string. + """ + if not cgroup_path: + cgroup_path = ray_constants.DEFAULT_CGROUP_PATH + + if not isinstance(cgroup_path, str): + raise ValueError( + f"Invalid value={cgroup_path} for cgroup_path. " + "Use a string to represent the path for the cgroup that the raylet should use " + "to enable resource isolation." + ) + + return cgroup_path + + @staticmethod + def _validate_and_get_system_reserved_cpu( + system_reserved_cpu: Optional[float], + ) -> int: + """If system_reserved_cpu is not specified, returns the default value. Otherwise, + checks the type, makes sure that the value is in range, and converts it into cpu.weights + for cgroupv2. See https://docs.kernel.org/admin-guide/cgroup-v2.html#weights for more information. + + Args: + system_reserved_cpu: The amount of cores reserved for ray system + processes. Must be >= ray_constants.MINIMUM_SYSTEM_RESERVED_CPU_CORES + and < the total number of cores available. + + Raises: + ValueError: If system_reserved_cpu is specified, but invalid. + """ + available_system_cpus = utils.get_num_cpus() + + if not system_reserved_cpu: + system_reserved_cpu = min( + ray_constants.DEFAULT_SYSTEM_RESERVED_CPU_CORES, + ray_constants.DEFAULT_SYSTEM_RESERVED_CPU_PROPORTION + * available_system_cpus, + ) + + if not ( + isinstance(system_reserved_cpu, float) + or isinstance(system_reserved_cpu, int) + ): + raise ValueError( + f"Invalid value={system_reserved_cpu} for system_reserved_cpu. " + "Use a float to represent the number of cores that need to be reserved for " + "ray system processes to enable resource isolation." + ) + + system_reserved_cpu = float(system_reserved_cpu) + + if system_reserved_cpu < ray_constants.MINIMUM_SYSTEM_RESERVED_CPU_CORES: + raise ValueError( + f"The requested system_reserved_cpu={system_reserved_cpu} is less than " + f"the minimum number of cpus that can be used for resource isolation. " + "Pick a number of cpu cores to reserve for ray system processes " + f"greater than or equal to {ray_constants.MINIMUM_SYSTEM_RESERVED_CPU_CORES}" + ) + + if system_reserved_cpu > available_system_cpus: + raise ValueError( + f"The requested system_reserved_cpu={system_reserved_cpu} is greater than " + f"the number of cpus available={available_system_cpus}. " + "Pick a smaller number of cpu cores to reserve for ray system processes." + ) + + # Converting the number of cores the user defined into cpu.weights + # This assumes that ray is allowed to use all available CPU + # cores and distribute them between system processes and + # application processes + return int( + (system_reserved_cpu / float(available_system_cpus)) + * _CGROUP_CPU_MAX_WEIGHT + ) + + @staticmethod + def _validate_and_get_system_reserved_memory( + system_reserved_memory: Optional[int], + ) -> int: + """If system_reserved_memory is not specified, returns the default value. Otherwise, + checks the type, makes sure that the value is in range. + + Args: + system_reserved_memory: The amount of memory in bytes reserved + for ray system processes. Must be >= ray_constants.MINIMUM_SYSTEM_RESERVED_MEMORY_BYTES + and < the total memory available. + + Returns: + int: The validated system reserved memory in bytes. + + Raises: + ValueError: If system_reserved_memory is specified, but invalid. + """ + available_system_memory = ray._common.utils.get_system_memory() + + if not system_reserved_memory: + system_reserved_memory = int( + min( + ray_constants.DEFAULT_SYSTEM_RESERVED_MEMORY_BYTES, + ray_constants.DEFAULT_SYSTEM_RESERVED_MEMORY_PROPORTION + * available_system_memory, + ) + ) + + if not isinstance(system_reserved_memory, int): + raise ValueError( + f"Invalid value={system_reserved_memory} for system_reserved_memory. " + "Use an integer to represent the number bytes that need to be reserved for " + "ray system processes to enable resource isolation." + ) + + if system_reserved_memory < ray_constants.MINIMUM_SYSTEM_RESERVED_MEMORY_BYTES: + raise ValueError( + f"The requested system_reserved_memory={system_reserved_memory} is less than " + f"the minimum number of bytes that can be used for resource isolation. " + "Pick a number of bytes to reserve for ray system processes " + f"greater than or equal to {ray_constants.MINIMUM_SYSTEM_RESERVED_MEMORY_BYTES}" + ) + + if system_reserved_memory > available_system_memory: + raise ValueError( + f"The total requested system_reserved_memory={system_reserved_memory} is greater than " + f"the amount of memory available={available_system_memory}." + ) + return system_reserved_memory diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/resource_spec.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/resource_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..0276ff9aded3af43021f770b3515dea792647d5c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/resource_spec.py @@ -0,0 +1,288 @@ +import logging +import sys +from collections import namedtuple +from typing import Optional + +import ray +import ray._private.ray_constants as ray_constants +from ray._common.utils import RESOURCE_CONSTRAINT_PREFIX + +logger = logging.getLogger(__name__) + +# Prefix for the node id resource that is automatically added to each node. +# For example, a node may have id `node:172.23.42.1`. +NODE_ID_PREFIX = "node:" +# The system resource that head node has. +HEAD_NODE_RESOURCE_NAME = NODE_ID_PREFIX + "__internal_head__" + + +class ResourceSpec( + namedtuple( + "ResourceSpec", + [ + "num_cpus", + "num_gpus", + "memory", + "object_store_memory", + "resources", + ], + ) +): + """Represents the resource configuration passed to a raylet. + + All fields can be None. Before starting services, resolve() should be + called to return a ResourceSpec with unknown values filled in with + defaults based on the local machine specifications. + + Attributes: + num_cpus: The CPUs allocated for this raylet. + num_gpus: The GPUs allocated for this raylet. + memory: The memory allocated for this raylet. + object_store_memory: The object store memory allocated for this raylet. + Note that when calling to_resource_dict(), this will be scaled down + by 30% to account for the global plasma LRU reserve. + resources: The custom resources allocated for this raylet. + """ + + def __new__( + cls, + num_cpus=None, + num_gpus=None, + memory=None, + object_store_memory=None, + resources=None, + ): + return super(ResourceSpec, cls).__new__( + cls, + num_cpus, + num_gpus, + memory, + object_store_memory, + resources, + ) + + def resolved(self): + """Returns if this ResourceSpec has default values filled out.""" + for v in self._asdict().values(): + if v is None: + return False + return True + + def to_resource_dict(self): + """Returns a dict suitable to pass to raylet initialization. + + This renames num_cpus / num_gpus to "CPU" / "GPU", + translates memory from bytes into 100MB memory units, and checks types. + """ + assert self.resolved() + + resources = dict( + self.resources, + CPU=self.num_cpus, + GPU=self.num_gpus, + memory=int(self.memory), + object_store_memory=int(self.object_store_memory), + ) + + resources = { + resource_label: resource_quantity + for resource_label, resource_quantity in resources.items() + if resource_quantity != 0 + } + + # Check types. + for resource_label, resource_quantity in resources.items(): + assert isinstance(resource_quantity, int) or isinstance( + resource_quantity, float + ), ( + f"{resource_label} ({type(resource_quantity)}): " f"{resource_quantity}" + ) + if ( + isinstance(resource_quantity, float) + and not resource_quantity.is_integer() + ): + raise ValueError( + "Resource quantities must all be whole numbers. " + "Violated by resource '{}' in {}.".format(resource_label, resources) + ) + if resource_quantity < 0: + raise ValueError( + "Resource quantities must be nonnegative. " + "Violated by resource '{}' in {}.".format(resource_label, resources) + ) + if resource_quantity > ray_constants.MAX_RESOURCE_QUANTITY: + raise ValueError( + "Resource quantities must be at most {}. " + "Violated by resource '{}' in {}.".format( + ray_constants.MAX_RESOURCE_QUANTITY, resource_label, resources + ) + ) + + return resources + + def resolve(self, is_head: bool, node_ip_address: Optional[str] = None): + """Returns a copy with values filled out with system defaults. + + Args: + is_head: Whether this is the head node. + node_ip_address: The IP address of the node that we are on. + This is used to automatically create a node id resource. + """ + + resources = (self.resources or {}).copy() + assert "CPU" not in resources, resources + assert "GPU" not in resources, resources + assert "memory" not in resources, resources + assert "object_store_memory" not in resources, resources + + if node_ip_address is None: + node_ip_address = ray.util.get_node_ip_address() + + # Automatically create a node id resource on each node. This is + # queryable with ray._private.state.node_ids() and + # ray._private.state.current_node_id(). + resources[NODE_ID_PREFIX + node_ip_address] = 1.0 + + # Automatically create a head node resource. + if HEAD_NODE_RESOURCE_NAME in resources: + raise ValueError( + f"{HEAD_NODE_RESOURCE_NAME}" + " is a reserved resource name, use another name instead." + ) + if is_head: + resources[HEAD_NODE_RESOURCE_NAME] = 1.0 + + num_cpus = self.num_cpus + if num_cpus is None: + num_cpus = ray._private.utils.get_num_cpus() + + num_gpus = 0 + for ( + accelerator_resource_name + ) in ray._private.accelerators.get_all_accelerator_resource_names(): + accelerator_manager = ( + ray._private.accelerators.get_accelerator_manager_for_resource( + accelerator_resource_name + ) + ) + num_accelerators = None + if accelerator_resource_name == "GPU": + num_accelerators = self.num_gpus + else: + num_accelerators = resources.get(accelerator_resource_name, None) + visible_accelerator_ids = ( + accelerator_manager.get_current_process_visible_accelerator_ids() + ) + # Check that the number of accelerators that the raylet wants doesn't + # exceed the amount allowed by visible accelerator ids. + if ( + num_accelerators is not None + and visible_accelerator_ids is not None + and num_accelerators > len(visible_accelerator_ids) + ): + raise ValueError( + f"Attempting to start raylet with {num_accelerators} " + f"{accelerator_resource_name}, " + f"but {accelerator_manager.get_visible_accelerator_ids_env_var()} " + f"contains {visible_accelerator_ids}." + ) + if num_accelerators is None: + # Try to automatically detect the number of accelerators. + num_accelerators = ( + accelerator_manager.get_current_node_num_accelerators() + ) + # Don't use more accelerators than allowed by visible accelerator ids. + if visible_accelerator_ids is not None: + num_accelerators = min( + num_accelerators, len(visible_accelerator_ids) + ) + + if num_accelerators: + if accelerator_resource_name == "GPU": + num_gpus = num_accelerators + else: + resources[accelerator_resource_name] = num_accelerators + + accelerator_type = ( + accelerator_manager.get_current_node_accelerator_type() + ) + if accelerator_type: + resources[f"{RESOURCE_CONSTRAINT_PREFIX}{accelerator_type}"] = 1 + + from ray._private.usage import usage_lib + + usage_lib.record_hardware_usage(accelerator_type) + additional_resources = ( + accelerator_manager.get_current_node_additional_resources() + ) + if additional_resources: + resources.update(additional_resources) + # Choose a default object store size. + system_memory = ray._common.utils.get_system_memory() + avail_memory = ray._private.utils.estimate_available_memory() + object_store_memory = self.object_store_memory + if object_store_memory is None: + object_store_memory = int( + avail_memory * ray_constants.DEFAULT_OBJECT_STORE_MEMORY_PROPORTION + ) + + # Set the object_store_memory size to 2GB on Mac + # to avoid degraded performance. + # (https://github.com/ray-project/ray/issues/20388) + if sys.platform == "darwin": + object_store_memory = min( + object_store_memory, ray_constants.MAC_DEGRADED_PERF_MMAP_SIZE_LIMIT + ) + + object_store_memory_cap = ( + ray_constants.DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES + ) + + # Cap by shm size by default to avoid low performance, but don't + # go lower than REQUIRE_SHM_SIZE_THRESHOLD. + if sys.platform == "linux" or sys.platform == "linux2": + # Multiple by 0.95 to give a bit of wiggle-room. + # https://github.com/ray-project/ray/pull/23034/files + shm_avail = ray._private.utils.get_shared_memory_bytes() * 0.95 + shm_cap = max(ray_constants.REQUIRE_SHM_SIZE_THRESHOLD, shm_avail) + + object_store_memory_cap = min(object_store_memory_cap, shm_cap) + + # Cap memory to avoid memory waste and perf issues on large nodes + if ( + object_store_memory_cap + and object_store_memory > object_store_memory_cap + ): + logger.debug( + "Warning: Capping object memory store to {}GB. ".format( + object_store_memory_cap // 1e9 + ) + + "To increase this further, specify `object_store_memory` " + "when calling ray.init() or ray start." + ) + object_store_memory = object_store_memory_cap + + memory = self.memory + if memory is None: + memory = avail_memory - object_store_memory + if memory < 100e6 and memory < 0.05 * system_memory: + raise ValueError( + "After taking into account object store and redis memory " + "usage, the amount of memory on this node available for " + "tasks and actors ({} GB) is less than {}% of total. " + "You can adjust these settings with " + "ray.init(memory=, " + "object_store_memory=).".format( + round(memory / 1e9, 2), int(100 * (memory / system_memory)) + ) + ) + + spec = ResourceSpec( + num_cpus, + num_gpus, + memory, + object_store_memory, + resources, + ) + assert spec.resolved() + return spec diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8d40c33d67ca8374373a3258a0daa4445480efb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__init__.py @@ -0,0 +1,3 @@ +# List of files to exclude from the Ray directory when using runtime_env for +# Ray development. These are not necessary in the Ray workers. +RAY_WORKER_DEV_EXCLUDES = ["raylet", "gcs_server", "cpp/", "tests/", "core/src"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f866adbd9e04288fc0319d41bbaf0deba954ca4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/_clonevirtualenv.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/_clonevirtualenv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de5b9f7ba794a52d88492dcb51d016df5a15cb80 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/_clonevirtualenv.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/conda.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/conda.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7920691e2b0c6e4b0bfa0649d3eac30c6c2aa5fb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/conda.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/conda_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/conda_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..324b7518cbf34b1aa2e4b3daeb45aee76e02f892 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/conda_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/constants.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a708c16ff73fb1f472a6045ab10e070081753f42 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/constants.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/context.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/context.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32a5f4f7be2851b50729b09bcde1a9cf828f81b6 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/context.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/default_impl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/default_impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eeb43c4b904c995805105165d76da63dee1f615c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/default_impl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/dependency_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/dependency_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3600ae53cb60bfcd505a85252ffc1b1e7b59fbaa Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/dependency_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/image_uri.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/image_uri.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42aea423de652543045652919a7eb234b177c1d4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/image_uri.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/java_jars.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/java_jars.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..051c13c3d7d02f837c21059fe04c7937aa0e42d3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/java_jars.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/mpi.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/mpi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9f68776ddc08e85d52ec465fda996c29a02d2bd Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/mpi.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/mpi_runner.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/mpi_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d61331e4b106478a52abece1bf2fb2f1d529d7a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/mpi_runner.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/nsight.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/nsight.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08ef0fcb171445c22bbe08fac115194fbfb4ad0e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/nsight.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/packaging.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/packaging.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0715ec7df49c8e8164bb5360b7d485f86b7cdbca Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/packaging.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/pip.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/pip.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..867a42ef0b72c8549534dd878f7c87ccb9452843 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/pip.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/plugin.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/plugin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c18cd79eebaa0a0ff2cd74e9b57ab97171cb3e1b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/plugin.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/plugin_schema_manager.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/plugin_schema_manager.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f56dd4dc2d94e273fea11353f12653081bf4d23a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/plugin_schema_manager.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/protocol.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cf7455a6554f133abb820ce12acb44b73ad5b28 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/protocol.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/py_executable.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/py_executable.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bfa7d382332c347f933fed8cb67ceb75de32b54d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/py_executable.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/py_modules.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/py_modules.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5d590c3b48a5f7810eb3a36b070354ccccadf83 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/py_modules.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/rocprof_sys.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/rocprof_sys.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..54ff1bcfcbb72a91c065a4b66416651a970bdf61 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/rocprof_sys.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/setup_hook.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/setup_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09cbbca3c25cd1c7168bfbed938131d93a29d44a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/setup_hook.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uri_cache.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uri_cache.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca705f0328f3fb4d0748ba5d6d1af81f0cd47b8a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uri_cache.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1269e49ed008269ac9028285bcd54b4c7e695ab Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uv.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uv.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..607514c5d2388e17e3fa04eb19555affcb6b7051 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uv.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uv_runtime_env_hook.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uv_runtime_env_hook.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6ac9571fb02f78c06f4fe0e51bfabe5e5369bf5b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/uv_runtime_env_hook.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/validation.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/validation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d4e3815e42bc9941b392571c58b778961b2ea05 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/validation.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/virtualenv_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/virtualenv_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55813b5eda83e27e7d9b363d5ebc50da41cc4dbf Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/virtualenv_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/working_dir.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/working_dir.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..76dfc94ec8f8da226fd6d45cccb8d4bbc66b2ba2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/__pycache__/working_dir.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/_clonevirtualenv.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/_clonevirtualenv.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2eab3d1040352a0a673323838004f2f4cc7f2c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/_clonevirtualenv.py @@ -0,0 +1,334 @@ +#!/usr/bin/env python + +from __future__ import with_statement + +import logging +import optparse +import os +import os.path +import re +import shutil +import subprocess +import sys +import itertools + +__version__ = "0.5.7" + + +logger = logging.getLogger() + + +env_bin_dir = "bin" +if sys.platform == "win32": + env_bin_dir = "Scripts" + _WIN32 = True +else: + _WIN32 = False + + +class UserError(Exception): + pass + + +def _dirmatch(path, matchwith): + """Check if path is within matchwith's tree. + >>> _dirmatch('/home/foo/bar', '/home/foo/bar') + True + >>> _dirmatch('/home/foo/bar/', '/home/foo/bar') + True + >>> _dirmatch('/home/foo/bar/etc', '/home/foo/bar') + True + >>> _dirmatch('/home/foo/bar2', '/home/foo/bar') + False + >>> _dirmatch('/home/foo/bar2/etc', '/home/foo/bar') + False + """ + matchlen = len(matchwith) + if path.startswith(matchwith) and path[matchlen : matchlen + 1] in [os.sep, ""]: + return True + return False + + +def _virtualenv_sys(venv_path): + """obtain version and path info from a virtualenv.""" + executable = os.path.join(venv_path, env_bin_dir, "python") + if _WIN32: + env = os.environ.copy() + else: + env = {} + # Must use "executable" as the first argument rather than as the + # keyword argument "executable" to get correct value from sys.path + p = subprocess.Popen( + [ + executable, + "-c", + "import sys;" + 'print ("%d.%d" % (sys.version_info.major, sys.version_info.minor));' + 'print ("\\n".join(sys.path));', + ], + env=env, + stdout=subprocess.PIPE, + ) + stdout, err = p.communicate() + assert not p.returncode and stdout + lines = stdout.decode("utf-8").splitlines() + return lines[0], list(filter(bool, lines[1:])) + + +def clone_virtualenv(src_dir, dst_dir): + if not os.path.exists(src_dir): + raise UserError("src dir %r does not exist" % src_dir) + if os.path.exists(dst_dir): + raise UserError("dest dir %r exists" % dst_dir) + # sys_path = _virtualenv_syspath(src_dir) + logger.info("cloning virtualenv '%s' => '%s'..." % (src_dir, dst_dir)) + shutil.copytree( + src_dir, dst_dir, symlinks=True, ignore=shutil.ignore_patterns("*.pyc") + ) + version, sys_path = _virtualenv_sys(dst_dir) + logger.info("fixing scripts in bin...") + fixup_scripts(src_dir, dst_dir, version) + + has_old = lambda s: any(i for i in s if _dirmatch(i, src_dir)) # noqa: E731 + + if has_old(sys_path): + # only need to fix stuff in sys.path if we have old + # paths in the sys.path of new python env. right? + logger.info("fixing paths in sys.path...") + fixup_syspath_items(sys_path, src_dir, dst_dir) + v_sys = _virtualenv_sys(dst_dir) + remaining = has_old(v_sys[1]) + assert not remaining, v_sys + fix_symlink_if_necessary(src_dir, dst_dir) + + +def fix_symlink_if_necessary(src_dir, dst_dir): + # sometimes the source virtual environment has symlinks that point to itself + # one example is $OLD_VIRTUAL_ENV/local/lib points to $OLD_VIRTUAL_ENV/lib + # this function makes sure + # $NEW_VIRTUAL_ENV/local/lib will point to $NEW_VIRTUAL_ENV/lib + # usually this goes unnoticed unless one tries to upgrade a package though pip, + # so this bug is hard to find. + logger.info("scanning for internal symlinks that point to the original virtual env") + for dirpath, dirnames, filenames in os.walk(dst_dir): + for a_file in itertools.chain(filenames, dirnames): + full_file_path = os.path.join(dirpath, a_file) + if os.path.islink(full_file_path): + target = os.path.realpath(full_file_path) + if target.startswith(src_dir): + new_target = target.replace(src_dir, dst_dir) + logger.debug("fixing symlink in %s" % (full_file_path,)) + os.remove(full_file_path) + os.symlink(new_target, full_file_path) + + +def fixup_scripts(old_dir, new_dir, version, rewrite_env_python=False): + bin_dir = os.path.join(new_dir, env_bin_dir) + root, dirs, files = next(os.walk(bin_dir)) + pybinre = re.compile(r"pythonw?([0-9]+(\.[0-9]+(\.[0-9]+)?)?)?$") + for file_ in files: + filename = os.path.join(root, file_) + if file_ in ["python", "python%s" % version, "activate_this.py"]: + continue + elif file_.startswith("python") and pybinre.match(file_): + # ignore other possible python binaries + continue + elif file_.endswith(".pyc"): + # ignore compiled files + continue + elif file_ == "activate" or file_.startswith("activate."): + fixup_activate(os.path.join(root, file_), old_dir, new_dir) + elif os.path.islink(filename): + fixup_link(filename, old_dir, new_dir) + elif os.path.isfile(filename): + fixup_script_( + root, + file_, + old_dir, + new_dir, + version, + rewrite_env_python=rewrite_env_python, + ) + + +def fixup_script_(root, file_, old_dir, new_dir, version, rewrite_env_python=False): + old_shebang = "#!%s/bin/python" % os.path.normcase(os.path.abspath(old_dir)) + new_shebang = "#!%s/bin/python" % os.path.normcase(os.path.abspath(new_dir)) + env_shebang = "#!/usr/bin/env python" + + filename = os.path.join(root, file_) + with open(filename, "rb") as f: + if f.read(2) != b"#!": + # no shebang + return + f.seek(0) + lines = f.readlines() + + if not lines: + # warn: empty script + return + + def rewrite_shebang(version=None): + logger.debug("fixing %s" % filename) + shebang = new_shebang + if version: + shebang = shebang + version + shebang = (shebang + "\n").encode("utf-8") + with open(filename, "wb") as f: + f.write(shebang) + f.writelines(lines[1:]) + + try: + bang = lines[0].decode("utf-8").strip() + except UnicodeDecodeError: + # binary file + return + + # This takes care of the scheme in which shebang is of type + # '#!/venv/bin/python3' while the version of system python + # is of type 3.x e.g. 3.5. + short_version = bang[len(old_shebang) :] + + if not bang.startswith("#!"): + return + elif bang == old_shebang: + rewrite_shebang() + elif bang.startswith(old_shebang) and bang[len(old_shebang) :] == version: + rewrite_shebang(version) + elif ( + bang.startswith(old_shebang) + and short_version + and bang[len(old_shebang) :] == short_version + ): + rewrite_shebang(short_version) + elif rewrite_env_python and bang.startswith(env_shebang): + if bang == env_shebang: + rewrite_shebang() + elif bang[len(env_shebang) :] == version: + rewrite_shebang(version) + else: + # can't do anything + return + + +def fixup_activate(filename, old_dir, new_dir): + logger.debug("fixing %s" % filename) + with open(filename, "rb") as f: + data = f.read().decode("utf-8") + + data = data.replace(old_dir, new_dir) + with open(filename, "wb") as f: + f.write(data.encode("utf-8")) + + +def fixup_link(filename, old_dir, new_dir, target=None): + logger.debug("fixing %s" % filename) + if target is None: + target = os.readlink(filename) + + origdir = os.path.dirname(os.path.abspath(filename)).replace(new_dir, old_dir) + if not os.path.isabs(target): + target = os.path.abspath(os.path.join(origdir, target)) + rellink = True + else: + rellink = False + + if _dirmatch(target, old_dir): + if rellink: + # keep relative links, but don't keep original in case it + # traversed up out of, then back into the venv. + # so, recreate a relative link from absolute. + target = target[len(origdir) :].lstrip(os.sep) + else: + target = target.replace(old_dir, new_dir, 1) + + # else: links outside the venv, replaced with absolute path to target. + _replace_symlink(filename, target) + + +def _replace_symlink(filename, newtarget): + tmpfn = "%s.new" % filename + os.symlink(newtarget, tmpfn) + os.rename(tmpfn, filename) + + +def fixup_syspath_items(syspath, old_dir, new_dir): + for path in syspath: + if not os.path.isdir(path): + continue + path = os.path.normcase(os.path.abspath(path)) + if _dirmatch(path, old_dir): + path = path.replace(old_dir, new_dir, 1) + if not os.path.exists(path): + continue + elif not _dirmatch(path, new_dir): + continue + root, dirs, files = next(os.walk(path)) + for file_ in files: + filename = os.path.join(root, file_) + if filename.endswith(".pth"): + fixup_pth_file(filename, old_dir, new_dir) + elif filename.endswith(".egg-link"): + fixup_egglink_file(filename, old_dir, new_dir) + + +def fixup_pth_file(filename, old_dir, new_dir): + logger.debug("fixup_pth_file %s" % filename) + + with open(filename, "r") as f: + lines = f.readlines() + + has_change = False + + for num, line in enumerate(lines): + line = (line.decode("utf-8") if hasattr(line, "decode") else line).strip() + + if not line or line.startswith("#") or line.startswith("import "): + continue + elif _dirmatch(line, old_dir): + lines[num] = line.replace(old_dir, new_dir, 1) + has_change = True + + if has_change: + with open(filename, "w") as f: + payload = os.linesep.join([line.strip() for line in lines]) + os.linesep + f.write(payload) + + +def fixup_egglink_file(filename, old_dir, new_dir): + logger.debug("fixing %s" % filename) + with open(filename, "rb") as f: + link = f.read().decode("utf-8").strip() + if _dirmatch(link, old_dir): + link = link.replace(old_dir, new_dir, 1) + with open(filename, "wb") as f: + link = (link + "\n").encode("utf-8") + f.write(link) + + +def main(): + parser = optparse.OptionParser( + "usage: %prog [options] /path/to/existing/venv /path/to/cloned/venv" + ) + parser.add_option( + "-v", action="count", dest="verbose", default=False, help="verbosity" + ) + options, args = parser.parse_args() + try: + old_dir, new_dir = args + except ValueError: + print("virtualenv-clone %s" % (__version__,)) + parser.error("not enough arguments given.") + old_dir = os.path.realpath(old_dir) + new_dir = os.path.realpath(new_dir) + loglevel = (logging.WARNING, logging.INFO, logging.DEBUG)[min(2, options.verbose)] + logging.basicConfig(level=loglevel, format="%(message)s") + try: + clone_virtualenv(old_dir, new_dir) + except UserError: + e = sys.exc_info()[1] + parser.error(str(e)) + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57b9f199a572bf54e8c8a48f423550e2eb6876b2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/main.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/main.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d92a101119d910082833bbc8452417e8c45beaf Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/main.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/runtime_env_agent.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/runtime_env_agent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ca1488d512d906134b29146bcf5f14c8761a3ab3 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/runtime_env_agent.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/runtime_env_consts.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/runtime_env_consts.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b261fcf143c6d99e58465f004bb80e9d90e2b70 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/__pycache__/runtime_env_consts.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/main.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/main.py new file mode 100644 index 0000000000000000000000000000000000000000..f9beaa6167c9d3e4be9422572765675689a398ac --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/main.py @@ -0,0 +1,237 @@ +import argparse +import logging +import os +import sys + +import ray._private.ray_constants as ray_constants +from ray._common.utils import ( + get_or_create_event_loop, +) +from ray._private import logging_utils +from ray._private.process_watcher import create_check_raylet_task +from ray._raylet import GcsClient +from ray.core.generated import ( + runtime_env_agent_pb2, +) + + +def import_libs(): + my_dir = os.path.abspath(os.path.dirname(__file__)) + sys.path.insert(0, os.path.join(my_dir, "thirdparty_files")) # for aiohttp + sys.path.insert(0, my_dir) # for runtime_env_agent and runtime_env_consts + + +import_libs() + +import runtime_env_consts # noqa: E402 +from aiohttp import web # noqa: E402 +from runtime_env_agent import RuntimeEnvAgent # noqa: E402 + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Runtime env agent.") + parser.add_argument( + "--node-ip-address", + required=True, + type=str, + help="the IP address of this node.", + ) + parser.add_argument( + "--runtime-env-agent-port", + required=True, + type=int, + default=None, + help="The port on which the runtime env agent will receive HTTP requests.", + ) + + parser.add_argument( + "--gcs-address", required=True, type=str, help="The address (ip:port) of GCS." + ) + parser.add_argument( + "--cluster-id-hex", required=True, type=str, help="The cluster id in hex." + ) + parser.add_argument( + "--runtime-env-dir", + required=True, + type=str, + default=None, + help="Specify the path of the resource directory used by runtime_env.", + ) + + parser.add_argument( + "--logging-level", + required=False, + type=lambda s: logging.getLevelName(s.upper()), + default=ray_constants.LOGGER_LEVEL, + choices=ray_constants.LOGGER_LEVEL_CHOICES, + help=ray_constants.LOGGER_LEVEL_HELP, + ) + parser.add_argument( + "--logging-format", + required=False, + type=str, + default=ray_constants.LOGGER_FORMAT, + help=ray_constants.LOGGER_FORMAT_HELP, + ) + parser.add_argument( + "--logging-filename", + required=False, + type=str, + default=runtime_env_consts.RUNTIME_ENV_AGENT_LOG_FILENAME, + help="Specify the name of log file, " + 'log to stdout if set empty, default is "{}".'.format( + runtime_env_consts.RUNTIME_ENV_AGENT_LOG_FILENAME + ), + ) + parser.add_argument( + "--logging-rotate-bytes", + required=True, + type=int, + help="Specify the max bytes for rotating log file", + ) + parser.add_argument( + "--logging-rotate-backup-count", + required=True, + type=int, + help="Specify the backup count of rotated log file", + ) + parser.add_argument( + "--log-dir", + required=True, + type=str, + default=None, + help="Specify the path of log directory.", + ) + parser.add_argument( + "--temp-dir", + required=True, + type=str, + default=None, + help="Specify the path of the temporary directory use by Ray process.", + ) + parser.add_argument( + "--stdout-filepath", + required=False, + type=str, + default="", + help="The filepath to dump runtime env agent stdout.", + ) + parser.add_argument( + "--stderr-filepath", + required=False, + type=str, + default="", + help="The filepath to dump runtime env agent stderr.", + ) + + args = parser.parse_args() + + # Disable log rotation for windows platform. + logging_rotation_bytes = args.logging_rotate_bytes if sys.platform != "win32" else 0 + logging_rotation_backup_count = ( + args.logging_rotate_backup_count if sys.platform != "win32" else 1 + ) + + logging_params = dict( + logging_level=args.logging_level, + logging_format=args.logging_format, + log_dir=args.log_dir, + filename=args.logging_filename, + max_bytes=logging_rotation_bytes, + backup_count=logging_rotation_backup_count, + ) + + # Setup stdout/stderr redirect files if redirection enabled. + logging_utils.redirect_stdout_stderr_if_needed( + args.stdout_filepath, + args.stderr_filepath, + logging_rotation_bytes, + logging_rotation_backup_count, + ) + + gcs_client = GcsClient(address=args.gcs_address, cluster_id=args.cluster_id_hex) + agent = RuntimeEnvAgent( + runtime_env_dir=args.runtime_env_dir, + logging_params=logging_params, + gcs_client=gcs_client, + temp_dir=args.temp_dir, + address=args.node_ip_address, + runtime_env_agent_port=args.runtime_env_agent_port, + ) + + # POST /get_or_create_runtime_env + # body is serialzied protobuf GetOrCreateRuntimeEnvRequest + # reply is serialzied protobuf GetOrCreateRuntimeEnvReply + async def get_or_create_runtime_env(request: web.Request) -> web.Response: + data = await request.read() + request = runtime_env_agent_pb2.GetOrCreateRuntimeEnvRequest() + request.ParseFromString(data) + reply = await agent.GetOrCreateRuntimeEnv(request) + return web.Response( + body=reply.SerializeToString(), content_type="application/octet-stream" + ) + + # POST /delete_runtime_env_if_possible + # body is serialzied protobuf DeleteRuntimeEnvIfPossibleRequest + # reply is serialzied protobuf DeleteRuntimeEnvIfPossibleReply + async def delete_runtime_env_if_possible(request: web.Request) -> web.Response: + data = await request.read() + request = runtime_env_agent_pb2.DeleteRuntimeEnvIfPossibleRequest() + request.ParseFromString(data) + reply = await agent.DeleteRuntimeEnvIfPossible(request) + return web.Response( + body=reply.SerializeToString(), content_type="application/octet-stream" + ) + + # POST /get_runtime_envs_info + # body is serialzied protobuf GetRuntimeEnvsInfoRequest + # reply is serialzied protobuf GetRuntimeEnvsInfoReply + async def get_runtime_envs_info(request: web.Request) -> web.Response: + data = await request.read() + request = runtime_env_agent_pb2.GetRuntimeEnvsInfoRequest() + request.ParseFromString(data) + reply = await agent.GetRuntimeEnvsInfo(request) + return web.Response( + body=reply.SerializeToString(), content_type="application/octet-stream" + ) + + app = web.Application() + + app.router.add_post("/get_or_create_runtime_env", get_or_create_runtime_env) + app.router.add_post( + "/delete_runtime_env_if_possible", delete_runtime_env_if_possible + ) + app.router.add_post("/get_runtime_envs_info", get_runtime_envs_info) + + loop = get_or_create_event_loop() + check_raylet_task = None + if sys.platform not in ["win32", "cygwin"]: + + def parent_dead_callback(msg): + agent._logger.info( + "Raylet is dead! Exiting Runtime Env Agent. " + f"addr: {args.node_ip_address}, " + f"port: {args.runtime_env_agent_port}\n" + f"{msg}" + ) + + # No need to await this task. + check_raylet_task = create_check_raylet_task( + args.log_dir, gcs_client, parent_dead_callback, loop + ) + runtime_env_agent_ip = ( + "127.0.0.1" if args.node_ip_address == "127.0.0.1" else "0.0.0.0" + ) + try: + web.run_app( + app, + host=runtime_env_agent_ip, + port=args.runtime_env_agent_port, + loop=loop, + ) + except SystemExit as e: + agent._logger.info(f"SystemExit! {e}") + # We have to poke the task exception, or there's an error message + # "task exception was never retrieved". + if check_raylet_task is not None: + check_raylet_task.exception() + sys.exit(e.code) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/runtime_env_agent.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/runtime_env_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..2e6e4c7204a708e5d3dbf6c2421deba27d468176 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/runtime_env_agent.py @@ -0,0 +1,595 @@ +import asyncio +import logging +import os +import time +import traceback +from collections import defaultdict +from dataclasses import dataclass +from typing import Callable, Dict, List, Set, Tuple + +import ray._private.runtime_env.agent.runtime_env_consts as runtime_env_consts +from ray._common.utils import get_or_create_event_loop +from ray._private.ray_constants import ( + DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS, +) +from ray._private.ray_logging import setup_component_logger +from ray._private.runtime_env.conda import CondaPlugin +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.default_impl import get_image_uri_plugin_cls +from ray._private.runtime_env.image_uri import ContainerPlugin +from ray._private.runtime_env.java_jars import JavaJarsPlugin +from ray._private.runtime_env.mpi import MPIPlugin +from ray._private.runtime_env.nsight import NsightPlugin +from ray._private.runtime_env.pip import PipPlugin +from ray._private.runtime_env.plugin import ( + RuntimeEnvPlugin, + RuntimeEnvPluginManager, + create_for_plugin_if_needed, +) +from ray._private.runtime_env.py_executable import PyExecutablePlugin +from ray._private.runtime_env.py_modules import PyModulesPlugin +from ray._private.runtime_env.rocprof_sys import RocProfSysPlugin +from ray._private.runtime_env.uv import UvPlugin +from ray._private.runtime_env.working_dir import WorkingDirPlugin +from ray._raylet import GcsClient +from ray.core.generated import runtime_env_agent_pb2 +from ray.core.generated.runtime_env_common_pb2 import ( + RuntimeEnvState as ProtoRuntimeEnvState, +) +from ray.runtime_env import RuntimeEnv, RuntimeEnvConfig + +default_logger = logging.getLogger(__name__) + +# TODO(edoakes): this is used for unit tests. We should replace it with a +# better pluggability mechanism once available. +SLEEP_FOR_TESTING_S = os.environ.get("RAY_RUNTIME_ENV_SLEEP_FOR_TESTING_S") + + +@dataclass +class CreatedEnvResult: + # Whether or not the env was installed correctly. + success: bool + # If success is True, will be a serialized RuntimeEnvContext + # If success is False, will be an error message. + result: str + # The time to create a runtime env in ms. + creation_time_ms: int + + +# e.g., "working_dir" +UriType = str + + +class ReferenceTable: + """ + The URI reference table which is used for GC. + When the reference count is decreased to zero, + the URI should be removed from this table and + added to cache if needed. + """ + + def __init__( + self, + uris_parser: Callable[[RuntimeEnv], Tuple[str, UriType]], + unused_uris_callback: Callable[[List[Tuple[str, UriType]]], None], + unused_runtime_env_callback: Callable[[str], None], + ): + # Runtime Environment reference table. The key is serialized runtime env and + # the value is reference count. + self._runtime_env_reference: Dict[str, int] = defaultdict(int) + # URI reference table. The key is URI parsed from runtime env and the value + # is reference count. + self._uri_reference: Dict[str, int] = defaultdict(int) + self._uris_parser = uris_parser + self._unused_uris_callback = unused_uris_callback + self._unused_runtime_env_callback = unused_runtime_env_callback + # send the `DeleteRuntimeEnvIfPossible` RPC when the client exits. The URI won't + # be leaked now because the reference count will be reset to zero when the job + # finished. + self._reference_exclude_sources: Set[str] = { + "client_server", + } + + def _increase_reference_for_uris(self, uris): + default_logger.debug(f"Increase reference for uris {uris}.") + for uri, _ in uris: + self._uri_reference[uri] += 1 + + def _decrease_reference_for_uris(self, uris): + default_logger.debug(f"Decrease reference for uris {uris}.") + unused_uris = list() + for uri, uri_type in uris: + if self._uri_reference[uri] > 0: + self._uri_reference[uri] -= 1 + if self._uri_reference[uri] == 0: + unused_uris.append((uri, uri_type)) + del self._uri_reference[uri] + else: + default_logger.warning(f"URI {uri} does not exist.") + if unused_uris: + default_logger.info(f"Unused uris {unused_uris}.") + self._unused_uris_callback(unused_uris) + return unused_uris + + def _increase_reference_for_runtime_env(self, serialized_env: str): + default_logger.debug(f"Increase reference for runtime env {serialized_env}.") + self._runtime_env_reference[serialized_env] += 1 + + def _decrease_reference_for_runtime_env(self, serialized_env: str): + """Decrease reference count for the given [serialized_env]. Throw exception if we cannot decrement reference.""" + default_logger.debug(f"Decrease reference for runtime env {serialized_env}.") + unused = False + if self._runtime_env_reference[serialized_env] > 0: + self._runtime_env_reference[serialized_env] -= 1 + if self._runtime_env_reference[serialized_env] == 0: + unused = True + del self._runtime_env_reference[serialized_env] + else: + default_logger.warning(f"Runtime env {serialized_env} does not exist.") + raise ValueError( + f"{serialized_env} cannot decrement reference since the reference count is 0" + ) + if unused: + default_logger.info(f"Unused runtime env {serialized_env}.") + self._unused_runtime_env_callback(serialized_env) + + def increase_reference( + self, runtime_env: RuntimeEnv, serialized_env: str, source_process: str + ) -> None: + if source_process in self._reference_exclude_sources: + return + self._increase_reference_for_runtime_env(serialized_env) + uris = self._uris_parser(runtime_env) + self._increase_reference_for_uris(uris) + + def decrease_reference( + self, runtime_env: RuntimeEnv, serialized_env: str, source_process: str + ) -> None: + """Decrease reference count for runtime env and uri. Throw exception if decrement reference count fails.""" + if source_process in self._reference_exclude_sources: + return + self._decrease_reference_for_runtime_env(serialized_env) + uris = self._uris_parser(runtime_env) + self._decrease_reference_for_uris(uris) + + @property + def runtime_env_refs(self) -> Dict[str, int]: + """Return the runtime_env -> ref count mapping. + + Returns: + The mapping of serialized runtime env -> ref count. + """ + return self._runtime_env_reference + + +class RuntimeEnvAgent: + """An RPC server to create and delete runtime envs. + + Attributes: + dashboard_agent: The DashboardAgent object contains global config. + """ + + def __init__( + self, + runtime_env_dir, + logging_params, + gcs_client: GcsClient, + temp_dir, + address, + runtime_env_agent_port, + ): + super().__init__() + + self._logger = default_logger + self._logging_params = logging_params + self._logger = setup_component_logger( + logger_name=default_logger.name, **self._logging_params + ) + # Don't propagate logs to the root logger, because these logs + # might contain sensitive information. Instead, these logs should + # be confined to the runtime env agent log file `self.LOG_FILENAME`. + self._logger.propagate = False + + self._logger.info("Starting runtime env agent at pid %s", os.getpid()) + self._logger.info(f"Parent raylet pid is {os.environ.get('RAY_RAYLET_PID')}") + + self._runtime_env_dir = runtime_env_dir + self._per_job_logger_cache = dict() + # Cache the results of creating envs to avoid repeatedly calling into + # conda and other slow calls. + self._env_cache: Dict[str, CreatedEnvResult] = dict() + # Maps a serialized runtime env to a lock that is used + # to prevent multiple concurrent installs of the same env. + self._env_locks: Dict[str, asyncio.Lock] = dict() + self._gcs_client = gcs_client + + self._pip_plugin = PipPlugin(self._runtime_env_dir) + self._uv_plugin = UvPlugin(self._runtime_env_dir) + self._conda_plugin = CondaPlugin(self._runtime_env_dir) + self._py_modules_plugin = PyModulesPlugin( + self._runtime_env_dir, self._gcs_client + ) + self._py_executable_plugin = PyExecutablePlugin() + self._java_jars_plugin = JavaJarsPlugin(self._runtime_env_dir, self._gcs_client) + self._working_dir_plugin = WorkingDirPlugin( + self._runtime_env_dir, self._gcs_client + ) + self._container_plugin = ContainerPlugin(temp_dir) + # TODO(jonathan-anyscale): change the plugin to ProfilerPlugin + # and unify with nsight and other profilers. + self._nsight_plugin = NsightPlugin(self._runtime_env_dir) + self._rocprof_sys_plugin = RocProfSysPlugin(self._runtime_env_dir) + self._mpi_plugin = MPIPlugin() + self._image_uri_plugin = get_image_uri_plugin_cls()(temp_dir) + + # TODO(architkulkarni): "base plugins" and third-party plugins should all go + # through the same code path. We should never need to refer to + # self._xxx_plugin, we should just iterate through self._plugins. + self._base_plugins: List[RuntimeEnvPlugin] = [ + self._working_dir_plugin, + self._uv_plugin, + self._pip_plugin, + self._conda_plugin, + self._py_modules_plugin, + self._py_executable_plugin, + self._java_jars_plugin, + self._container_plugin, + self._nsight_plugin, + self._rocprof_sys_plugin, + self._mpi_plugin, + self._image_uri_plugin, + ] + self._plugin_manager = RuntimeEnvPluginManager() + for plugin in self._base_plugins: + self._plugin_manager.add_plugin(plugin) + + self._reference_table = ReferenceTable( + self.uris_parser, + self.unused_uris_processor, + self.unused_runtime_env_processor, + ) + + self._logger.info( + "Listening to address %s, port %d", address, runtime_env_agent_port + ) + + def uris_parser(self, runtime_env: RuntimeEnv): + result = list() + for name, plugin_setup_context in self._plugin_manager.plugins.items(): + plugin = plugin_setup_context.class_instance + uris = plugin.get_uris(runtime_env) + for uri in uris: + result.append((uri, UriType(name))) + return result + + def unused_uris_processor(self, unused_uris: List[Tuple[str, UriType]]) -> None: + for uri, uri_type in unused_uris: + self._plugin_manager.plugins[str(uri_type)].uri_cache.mark_unused(uri) + + def unused_runtime_env_processor(self, unused_runtime_env: str) -> None: + def delete_runtime_env(): + del self._env_cache[unused_runtime_env] + self._logger.info( + "Runtime env %s removed from env-level cache.", unused_runtime_env + ) + + if unused_runtime_env in self._env_cache: + if not self._env_cache[unused_runtime_env].success: + loop = get_or_create_event_loop() + # Cache the bad runtime env result by ttl seconds. + loop.call_later( + runtime_env_consts.BAD_RUNTIME_ENV_CACHE_TTL_SECONDS, + delete_runtime_env, + ) + else: + delete_runtime_env() + + def get_or_create_logger(self, job_id: bytes, log_files: List[str]): + job_id = job_id.decode() + if job_id not in self._per_job_logger_cache: + params = self._logging_params.copy() + params["filename"] = [f"runtime_env_setup-{job_id}.log", *log_files] + params["logger_name"] = f"runtime_env_{job_id}" + params["propagate"] = False + per_job_logger = setup_component_logger(**params) + self._per_job_logger_cache[job_id] = per_job_logger + return self._per_job_logger_cache[job_id] + + async def GetOrCreateRuntimeEnv(self, request): + self._logger.debug( + f"Got request from {request.source_process} to increase " + "reference for runtime env: " + f"{request.serialized_runtime_env}." + ) + + async def _setup_runtime_env( + runtime_env: RuntimeEnv, + runtime_env_config: RuntimeEnvConfig, + ): + log_files = runtime_env_config.get("log_files", []) + # Use a separate logger for each job. + per_job_logger = self.get_or_create_logger(request.job_id, log_files) + context = RuntimeEnvContext(env_vars=runtime_env.env_vars()) + + # Warn about unrecognized fields in the runtime env. + for name, _ in runtime_env.plugins(): + if name not in self._plugin_manager.plugins: + per_job_logger.warning( + f"runtime_env field {name} is not recognized by " + "Ray and will be ignored. In the future, unrecognized " + "fields in the runtime_env will raise an exception." + ) + + # Creates each runtime env URI by their priority. `working_dir` is special + # because it needs to be created before other plugins. All other plugins are + # created in the priority order (smaller priority value -> earlier to + # create), with a special environment variable being set to the working dir. + # ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR} + + # First create working dir... + working_dir_ctx = self._plugin_manager.plugins[WorkingDirPlugin.name] + await create_for_plugin_if_needed( + runtime_env, + working_dir_ctx.class_instance, + working_dir_ctx.uri_cache, + context, + per_job_logger, + ) + + # Then within the working dir, create the other plugins. + working_dir_uri_or_none = runtime_env.working_dir_uri() + with self._working_dir_plugin.with_working_dir_env(working_dir_uri_or_none): + """Run setup for each plugin unless it has already been cached.""" + for ( + plugin_setup_context + ) in self._plugin_manager.sorted_plugin_setup_contexts(): + plugin = plugin_setup_context.class_instance + if plugin.name != WorkingDirPlugin.name: + uri_cache = plugin_setup_context.uri_cache + await create_for_plugin_if_needed( + runtime_env, plugin, uri_cache, context, per_job_logger + ) + return context + + async def _create_runtime_env_with_retry( + runtime_env, + setup_timeout_seconds, + runtime_env_config: RuntimeEnvConfig, + ) -> Tuple[bool, str, str]: + """Create runtime env with retry times. This function won't raise exceptions. + + Args: + runtime_env: The instance of RuntimeEnv class. + setup_timeout_seconds: The timeout of runtime environment creation for + each attempt. + runtime_env_config: The configuration for the runtime environment. + + Returns: + Tuple[bool, str, str]: A tuple containing: + - result (bool): Whether the creation was successful + - runtime_env_context (str): The serialized context if successful, None otherwise + - error_message (str): Error message if failed, None otherwise + """ + self._logger.info( + f"Creating runtime env: {serialized_env} with timeout " + f"{setup_timeout_seconds} seconds." + ) + num_retries = runtime_env_consts.RUNTIME_ENV_RETRY_TIMES + error_message = None + serialized_context = None + for i in range(num_retries): + # Only sleep when retrying. + if i != 0: + await asyncio.sleep( + runtime_env_consts.RUNTIME_ENV_RETRY_INTERVAL_MS / 1000 + ) + + try: + runtime_env_setup_task = _setup_runtime_env( + runtime_env, runtime_env_config + ) + runtime_env_context = await asyncio.wait_for( + runtime_env_setup_task, timeout=setup_timeout_seconds + ) + serialized_context = runtime_env_context.serialize() + error_message = None + break + except Exception as e: + err_msg = f"Failed to create runtime env {serialized_env}." + self._logger.exception(err_msg) + error_message = "".join( + traceback.format_exception(type(e), e, e.__traceback__) + ) + if isinstance(e, asyncio.TimeoutError): + hint = ( + f"Failed to install runtime_env within the " + f"timeout of {setup_timeout_seconds} seconds. Consider " + "increasing the timeout in the runtime_env config. " + "For example: \n" + ' runtime_env={"config": {"setup_timeout_seconds":' + " 1800}, ...}\n" + "If not provided, the default timeout is " + f"{DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS} seconds. " + ) + error_message = hint + error_message + + if error_message: + self._logger.error( + "runtime_env creation failed %d times, giving up.", + num_retries, + ) + return False, None, error_message + else: + self._logger.info( + "Successfully created runtime env: %s, context: %s", + serialized_env, + serialized_context, + ) + return True, serialized_context, None + + try: + serialized_env = request.serialized_runtime_env + runtime_env = RuntimeEnv.deserialize(serialized_env) + except Exception as e: + self._logger.exception( + "[Increase] Failed to parse runtime env: " f"{serialized_env}" + ) + return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply( + status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED, + error_message="".join( + traceback.format_exception(type(e), e, e.__traceback__) + ), + ) + + # Increase reference + self._reference_table.increase_reference( + runtime_env, serialized_env, request.source_process + ) + + if serialized_env not in self._env_locks: + # async lock to prevent the same env being concurrently installed + self._env_locks[serialized_env] = asyncio.Lock() + + async with self._env_locks[serialized_env]: + if serialized_env in self._env_cache: + serialized_context = self._env_cache[serialized_env] + result = self._env_cache[serialized_env] + if result.success: + context = result.result + self._logger.info( + "Runtime env already created " + f"successfully. Env: {serialized_env}, " + f"context: {context}" + ) + return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply( + status=runtime_env_agent_pb2.AGENT_RPC_STATUS_OK, + serialized_runtime_env_context=context, + ) + else: + error_message = result.result + self._logger.info( + "Runtime env already failed. " + f"Env: {serialized_env}, " + f"err: {error_message}" + ) + # Recover the reference. + self._reference_table.decrease_reference( + runtime_env, serialized_env, request.source_process + ) + return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply( + status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED, + error_message=error_message, + ) + + if SLEEP_FOR_TESTING_S: + self._logger.info(f"Sleeping for {SLEEP_FOR_TESTING_S}s.") + time.sleep(int(SLEEP_FOR_TESTING_S)) + + runtime_env_config = RuntimeEnvConfig.from_proto(request.runtime_env_config) + + # accroding to the document of `asyncio.wait_for`, + # None means disable timeout logic + setup_timeout_seconds = ( + None + if runtime_env_config["setup_timeout_seconds"] == -1 + else runtime_env_config["setup_timeout_seconds"] + ) + + start = time.perf_counter() + ( + successful, + serialized_context, + error_message, + ) = await _create_runtime_env_with_retry( + runtime_env, + setup_timeout_seconds, + runtime_env_config, + ) + creation_time_ms = int(round((time.perf_counter() - start) * 1000, 0)) + if not successful: + # Recover the reference. + self._reference_table.decrease_reference( + runtime_env, serialized_env, request.source_process + ) + # Add the result to env cache. + self._env_cache[serialized_env] = CreatedEnvResult( + successful, + serialized_context if successful else error_message, + creation_time_ms, + ) + # Reply the RPC + return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply( + status=runtime_env_agent_pb2.AGENT_RPC_STATUS_OK + if successful + else runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED, + serialized_runtime_env_context=serialized_context, + error_message=error_message, + ) + + async def DeleteRuntimeEnvIfPossible(self, request): + self._logger.info( + f"Got request from {request.source_process} to decrease " + "reference for runtime env: " + f"{request.serialized_runtime_env}." + ) + + try: + runtime_env = RuntimeEnv.deserialize(request.serialized_runtime_env) + except Exception as e: + self._logger.exception( + "[Decrease] Failed to parse runtime env: " + f"{request.serialized_runtime_env}" + ) + return runtime_env_agent_pb2.GetOrCreateRuntimeEnvReply( + status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED, + error_message="".join( + traceback.format_exception(type(e), e, e.__traceback__) + ), + ) + + try: + self._reference_table.decrease_reference( + runtime_env, request.serialized_runtime_env, request.source_process + ) + except Exception as e: + return runtime_env_agent_pb2.DeleteRuntimeEnvIfPossibleReply( + status=runtime_env_agent_pb2.AGENT_RPC_STATUS_FAILED, + error_message=f"Fails to decrement reference for runtime env for {str(e)}", + ) + + return runtime_env_agent_pb2.DeleteRuntimeEnvIfPossibleReply( + status=runtime_env_agent_pb2.AGENT_RPC_STATUS_OK + ) + + async def GetRuntimeEnvsInfo(self, request): + """Return the runtime env information of the node.""" + # TODO(sang): Currently, it only includes runtime_env information. + # We should include the URI information which includes, + # URIs + # Caller + # Ref counts + # Cache information + # Metrics (creation time & success) + # Deleted URIs + limit = request.limit if request.HasField("limit") else -1 + runtime_env_states = defaultdict(ProtoRuntimeEnvState) + runtime_env_refs = self._reference_table.runtime_env_refs + for runtime_env, ref_cnt in runtime_env_refs.items(): + runtime_env_states[runtime_env].runtime_env = runtime_env + runtime_env_states[runtime_env].ref_cnt = ref_cnt + for runtime_env, result in self._env_cache.items(): + runtime_env_states[runtime_env].runtime_env = runtime_env + runtime_env_states[runtime_env].success = result.success + if not result.success: + runtime_env_states[runtime_env].error = result.result + runtime_env_states[runtime_env].creation_time_ms = result.creation_time_ms + + reply = runtime_env_agent_pb2.GetRuntimeEnvsInfoReply() + count = 0 + for runtime_env_state in runtime_env_states.values(): + if limit != -1 and count >= limit: + break + count += 1 + reply.runtime_env_states.append(runtime_env_state) + reply.total = len(runtime_env_states) + return reply diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/runtime_env_consts.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/runtime_env_consts.py new file mode 100644 index 0000000000000000000000000000000000000000..31545913168fa29397995d4d0c6c118fe583365f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/runtime_env_consts.py @@ -0,0 +1,20 @@ +import ray._private.ray_constants as ray_constants + +RUNTIME_ENV_RETRY_TIMES = ray_constants.env_integer("RUNTIME_ENV_RETRY_TIMES", 3) + +RUNTIME_ENV_RETRY_INTERVAL_MS = ray_constants.env_integer( + "RUNTIME_ENV_RETRY_INTERVAL_MS", 1000 +) + +# Cache TTL for bad runtime env. After this time, delete the cache and retry to create +# runtime env if needed. +BAD_RUNTIME_ENV_CACHE_TTL_SECONDS = ray_constants.env_integer( + "BAD_RUNTIME_ENV_CACHE_TTL_SECONDS", 60 * 10 +) + +RUNTIME_ENV_LOG_FILENAME = "runtime_env.log" +RUNTIME_ENV_AGENT_PORT_PREFIX = "RUNTIME_ENV_AGENT_PORT_PREFIX:" +RUNTIME_ENV_AGENT_LOG_FILENAME = "runtime_env_agent.log" +RUNTIME_ENV_AGENT_CHECK_PARENT_INTERVAL_S_ENV_NAME = ( + "RAY_RUNTIME_ENV_AGENT_CHECK_PARENT_INTERVAL_S" # noqa +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/__pycache__/typing_extensions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/__pycache__/typing_extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7279e7b74aa4fbaa8e644925921934b86d022b5d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/__pycache__/typing_extensions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bed1239d6069b030483775d5e470c7370d5dfe20ece1984e0f01e5c370e8da92 +size 162219 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/INSTALLER b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/LICENSE b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f26bcf4d2de6eb136e31006ca3ab447d5e488adf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/LICENSE @@ -0,0 +1,279 @@ +A. HISTORY OF THE SOFTWARE +========================== + +Python was created in the early 1990s by Guido van Rossum at Stichting +Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands +as a successor of a language called ABC. Guido remains Python's +principal author, although it includes many contributions from others. + +In 1995, Guido continued his work on Python at the Corporation for +National Research Initiatives (CNRI, see https://www.cnri.reston.va.us) +in Reston, Virginia where he released several versions of the +software. + +In May 2000, Guido and the Python core development team moved to +BeOpen.com to form the BeOpen PythonLabs team. In October of the same +year, the PythonLabs team moved to Digital Creations, which became +Zope Corporation. In 2001, the Python Software Foundation (PSF, see +https://www.python.org/psf/) was formed, a non-profit organization +created specifically to own Python-related Intellectual Property. +Zope Corporation was a sponsoring member of the PSF. + +All Python releases are Open Source (see https://opensource.org for +the Open Source Definition). Historically, most, but not all, Python +releases have also been GPL-compatible; the table below summarizes +the various releases. + + Release Derived Year Owner GPL- + from compatible? (1) + + 0.9.0 thru 1.2 1991-1995 CWI yes + 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes + 1.6 1.5.2 2000 CNRI no + 2.0 1.6 2000 BeOpen.com no + 1.6.1 1.6 2001 CNRI yes (2) + 2.1 2.0+1.6.1 2001 PSF no + 2.0.1 2.0+1.6.1 2001 PSF yes + 2.1.1 2.1+2.0.1 2001 PSF yes + 2.1.2 2.1.1 2002 PSF yes + 2.1.3 2.1.2 2002 PSF yes + 2.2 and above 2.1.1 2001-now PSF yes + +Footnotes: + +(1) GPL-compatible doesn't mean that we're distributing Python under + the GPL. All Python licenses, unlike the GPL, let you distribute + a modified version without making your changes open source. The + GPL-compatible licenses make it possible to combine Python with + other software that is released under the GPL; the others don't. + +(2) According to Richard Stallman, 1.6.1 is not GPL-compatible, + because its license has a choice of law clause. According to + CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 + is "not incompatible" with the GPL. + +Thanks to the many outside volunteers who have worked under Guido's +direction to make these releases possible. + + +B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON +=============================================================== + +Python software and documentation are licensed under the +Python Software Foundation License Version 2. + +Starting with Python 3.8.6, examples, recipes, and other code in +the documentation are dual licensed under the PSF License Version 2 +and the Zero-Clause BSD license. + +Some software incorporated into Python is under different licenses. +The licenses are listed with code falling under that license. + + +PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 +-------------------------------------------- + +1. This LICENSE AGREEMENT is between the Python Software Foundation +("PSF"), and the Individual or Organization ("Licensee") accessing and +otherwise using this software ("Python") in source or binary form and +its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, PSF hereby +grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, +analyze, test, perform and/or display publicly, prepare derivative works, +distribute, and otherwise use Python alone or in any derivative version, +provided, however, that PSF's License Agreement and PSF's notice of copyright, +i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation; +All Rights Reserved" are retained in Python alone or in any derivative version +prepared by Licensee. + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python. + +4. PSF is making Python available to Licensee on an "AS IS" +basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between PSF and +Licensee. This License Agreement does not grant permission to use PSF +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using Python, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 +------------------------------------------- + +BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 + +1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an +office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the +Individual or Organization ("Licensee") accessing and otherwise using +this software in source or binary form and its associated +documentation ("the Software"). + +2. Subject to the terms and conditions of this BeOpen Python License +Agreement, BeOpen hereby grants Licensee a non-exclusive, +royalty-free, world-wide license to reproduce, analyze, test, perform +and/or display publicly, prepare derivative works, distribute, and +otherwise use the Software alone or in any derivative version, +provided, however, that the BeOpen Python License is retained in the +Software, alone or in any derivative version prepared by Licensee. + +3. BeOpen is making the Software available to Licensee on an "AS IS" +basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE +SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS +AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY +DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +5. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +6. This License Agreement shall be governed by and interpreted in all +respects by the law of the State of California, excluding conflict of +law provisions. Nothing in this License Agreement shall be deemed to +create any relationship of agency, partnership, or joint venture +between BeOpen and Licensee. This License Agreement does not grant +permission to use BeOpen trademarks or trade names in a trademark +sense to endorse or promote products or services of Licensee, or any +third party. As an exception, the "BeOpen Python" logos available at +http://www.pythonlabs.com/logos.html may be used according to the +permissions granted on that web page. + +7. By copying, installing or otherwise using the software, Licensee +agrees to be bound by the terms and conditions of this License +Agreement. + + +CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 +--------------------------------------- + +1. This LICENSE AGREEMENT is between the Corporation for National +Research Initiatives, having an office at 1895 Preston White Drive, +Reston, VA 20191 ("CNRI"), and the Individual or Organization +("Licensee") accessing and otherwise using Python 1.6.1 software in +source or binary form and its associated documentation. + +2. Subject to the terms and conditions of this License Agreement, CNRI +hereby grants Licensee a nonexclusive, royalty-free, world-wide +license to reproduce, analyze, test, perform and/or display publicly, +prepare derivative works, distribute, and otherwise use Python 1.6.1 +alone or in any derivative version, provided, however, that CNRI's +License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) +1995-2001 Corporation for National Research Initiatives; All Rights +Reserved" are retained in Python 1.6.1 alone or in any derivative +version prepared by Licensee. Alternately, in lieu of CNRI's License +Agreement, Licensee may substitute the following text (omitting the +quotes): "Python 1.6.1 is made available subject to the terms and +conditions in CNRI's License Agreement. This Agreement together with +Python 1.6.1 may be located on the internet using the following +unique, persistent identifier (known as a handle): 1895.22/1013. This +Agreement may also be obtained from a proxy server on the internet +using the following URL: http://hdl.handle.net/1895.22/1013". + +3. In the event Licensee prepares a derivative work that is based on +or incorporates Python 1.6.1 or any part thereof, and wants to make +the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to Python 1.6.1. + +4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" +basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT +INFRINGE ANY THIRD PARTY RIGHTS. + +5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON +1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS +A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, +OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. This License Agreement shall be governed by the federal +intellectual property law of the United States, including without +limitation the federal copyright law, and, to the extent such +U.S. federal law does not apply, by the law of the Commonwealth of +Virginia, excluding Virginia's conflict of law provisions. +Notwithstanding the foregoing, with regard to derivative works based +on Python 1.6.1 that incorporate non-separable material that was +previously distributed under the GNU General Public License (GPL), the +law of the Commonwealth of Virginia shall govern this License +Agreement only as to issues arising under or with respect to +Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this +License Agreement shall be deemed to create any relationship of +agency, partnership, or joint venture between CNRI and Licensee. This +License Agreement does not grant permission to use CNRI trademarks or +trade name in a trademark sense to endorse or promote products or +services of Licensee, or any third party. + +8. By clicking on the "ACCEPT" button where indicated, or by copying, +installing or otherwise using Python 1.6.1, Licensee agrees to be +bound by the terms and conditions of this License Agreement. + + ACCEPT + + +CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 +-------------------------------------------------- + +Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, +The Netherlands. All rights reserved. + +Permission to use, copy, modify, and distribute this software and its +documentation for any purpose and without fee is hereby granted, +provided that the above copyright notice appear in all copies and that +both that copyright notice and this permission notice appear in +supporting documentation, and that the name of Stichting Mathematisch +Centrum or CWI not be used in advertising or publicity pertaining to +distribution of the software without specific, written prior +permission. + +STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO +THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE +FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION +---------------------------------------------------------------------- + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/METADATA b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..c632040d66bf120a377fc3785940934361273a66 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/METADATA @@ -0,0 +1,123 @@ +Metadata-Version: 2.3 +Name: aiohappyeyeballs +Version: 2.6.1 +Summary: Happy Eyeballs for asyncio +License: PSF-2.0 +Author: J. Nick Koston +Author-email: nick@koston.org +Requires-Python: >=3.9 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Natural Language :: English +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: License :: OSI Approved :: Python Software Foundation License +Project-URL: Bug Tracker, https://github.com/aio-libs/aiohappyeyeballs/issues +Project-URL: Changelog, https://github.com/aio-libs/aiohappyeyeballs/blob/main/CHANGELOG.md +Project-URL: Documentation, https://aiohappyeyeballs.readthedocs.io +Project-URL: Repository, https://github.com/aio-libs/aiohappyeyeballs +Description-Content-Type: text/markdown + +# aiohappyeyeballs + +

+ + CI Status + + + Documentation Status + + + Test coverage percentage + +

+

+ + Poetry + + + Ruff + + + pre-commit + +

+

+ + PyPI Version + + Supported Python versions + License +

+ +--- + +**Documentation**: https://aiohappyeyeballs.readthedocs.io + +**Source Code**: https://github.com/aio-libs/aiohappyeyeballs + +--- + +[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs) +([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html)) + +## Use case + +This library exists to allow connecting with +[Happy Eyeballs](https://en.wikipedia.org/wiki/Happy_Eyeballs) +([RFC 8305](https://www.rfc-editor.org/rfc/rfc8305.html)) +when you +already have a list of addrinfo and not a DNS name. + +The stdlib version of `loop.create_connection()` +will only work when you pass in an unresolved name which +is not a good fit when using DNS caching or resolving +names via another method such as `zeroconf`. + +## Installation + +Install this via pip (or your favourite package manager): + +`pip install aiohappyeyeballs` + +## License + +[aiohappyeyeballs is licensed under the same terms as cpython itself.](https://github.com/python/cpython/blob/main/LICENSE) + +## Example usage + +```python + +addr_infos = await loop.getaddrinfo("example.org", 80) + +socket = await start_connection(addr_infos) +socket = await start_connection(addr_infos, local_addr_infos=local_addr_infos, happy_eyeballs_delay=0.2) + +transport, protocol = await loop.create_connection( + MyProtocol, sock=socket, ...) + +# Remove the first address for each family from addr_info +pop_addr_infos_interleave(addr_info, 1) + +# Remove all matching address from addr_info +remove_addr_infos(addr_info, "dead::beef::") + +# Convert a local_addr to local_addr_infos +local_addr_infos = addr_to_addr_infos(("127.0.0.1",0)) +``` + +## Credits + +This package contains code from cpython and is licensed under the same terms as cpython itself. + +This package was created with +[Copier](https://copier.readthedocs.io/) and the +[browniebroke/pypackage-template](https://github.com/browniebroke/pypackage-template) +project template. + diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/RECORD b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..9e0e2023f21e2df03b9b2d75aae5b116887feede --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/RECORD @@ -0,0 +1,16 @@ +aiohappyeyeballs-2.6.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiohappyeyeballs-2.6.1.dist-info/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +aiohappyeyeballs-2.6.1.dist-info/METADATA,sha256=NSXlhJwAfi380eEjAo7BQ4P_TVal9xi0qkyZWibMsVM,5915 +aiohappyeyeballs-2.6.1.dist-info/RECORD,, +aiohappyeyeballs-2.6.1.dist-info/WHEEL,sha256=XbeZDeTWKc1w7CSIyre5aMDU_-PohRwTQceYnisIYYY,88 +aiohappyeyeballs/__init__.py,sha256=x7kktHEtaD9quBcWDJPuLeKyjuVAI-Jj14S9B_5hcTs,361 +aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc,, +aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc,, +aiohappyeyeballs/__pycache__/impl.cpython-312.pyc,, +aiohappyeyeballs/__pycache__/types.cpython-312.pyc,, +aiohappyeyeballs/__pycache__/utils.cpython-312.pyc,, +aiohappyeyeballs/_staggered.py,sha256=edfVowFx-P-ywJjIEF3MdPtEMVODujV6CeMYr65otac,6900 +aiohappyeyeballs/impl.py,sha256=Dlcm2mTJ28ucrGnxkb_fo9CZzLAkOOBizOt7dreBbXE,9681 +aiohappyeyeballs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiohappyeyeballs/types.py,sha256=YZJIAnyoV4Dz0WFtlaf_OyE4EW7Xus1z7aIfNI6tDDQ,425 +aiohappyeyeballs/utils.py,sha256=on9GxIR0LhEfZu8P6Twi9hepX9zDanuZM20MWsb3xlQ,3028 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/WHEEL b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..0582547b15f02d3a51659106262832565d5dc5ea --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs-2.6.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: poetry-core 2.1.1 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..71c689cc83ffdec6c079a22984cf80a5ab7bb272 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__init__.py @@ -0,0 +1,14 @@ +__version__ = "2.6.1" + +from .impl import start_connection +from .types import AddrInfoType, SocketFactoryType +from .utils import addr_to_addr_infos, pop_addr_infos_interleave, remove_addr_infos + +__all__ = ( + "AddrInfoType", + "SocketFactoryType", + "addr_to_addr_infos", + "pop_addr_infos_interleave", + "remove_addr_infos", + "start_connection", +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8aed4dae9737dbcd6551082572cd0aee45e69e9d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3892dbaf22b52d974374e174de449957c6cf1f4d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/_staggered.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/impl.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/impl.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57f2765f29fe501821a0480034c86a5272615f8d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/impl.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/types.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/types.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fbab234f215f0660e6996890db785bf6306aa51 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/types.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5813701ead7270b0e3a776649526673036f9358c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/__pycache__/utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/_staggered.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/_staggered.py new file mode 100644 index 0000000000000000000000000000000000000000..9a4ba7205eda2ddeb2ebb6c5a34108c1a61cce6d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/_staggered.py @@ -0,0 +1,207 @@ +import asyncio +import contextlib + +# PY3.9: Import Callable from typing until we drop Python 3.9 support +# https://github.com/python/cpython/issues/87131 +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Iterable, + List, + Optional, + Set, + Tuple, + TypeVar, + Union, +) + +_T = TypeVar("_T") + +RE_RAISE_EXCEPTIONS = (SystemExit, KeyboardInterrupt) + + +def _set_result(wait_next: "asyncio.Future[None]") -> None: + """Set the result of a future if it is not already done.""" + if not wait_next.done(): + wait_next.set_result(None) + + +async def _wait_one( + futures: "Iterable[asyncio.Future[Any]]", + loop: asyncio.AbstractEventLoop, +) -> _T: + """Wait for the first future to complete.""" + wait_next = loop.create_future() + + def _on_completion(fut: "asyncio.Future[Any]") -> None: + if not wait_next.done(): + wait_next.set_result(fut) + + for f in futures: + f.add_done_callback(_on_completion) + + try: + return await wait_next + finally: + for f in futures: + f.remove_done_callback(_on_completion) + + +async def staggered_race( + coro_fns: Iterable[Callable[[], Awaitable[_T]]], + delay: Optional[float], + *, + loop: Optional[asyncio.AbstractEventLoop] = None, +) -> Tuple[Optional[_T], Optional[int], List[Optional[BaseException]]]: + """ + Run coroutines with staggered start times and take the first to finish. + + This method takes an iterable of coroutine functions. The first one is + started immediately. From then on, whenever the immediately preceding one + fails (raises an exception), or when *delay* seconds has passed, the next + coroutine is started. This continues until one of the coroutines complete + successfully, in which case all others are cancelled, or until all + coroutines fail. + + The coroutines provided should be well-behaved in the following way: + + * They should only ``return`` if completed successfully. + + * They should always raise an exception if they did not complete + successfully. In particular, if they handle cancellation, they should + probably reraise, like this:: + + try: + # do work + except asyncio.CancelledError: + # undo partially completed work + raise + + Args: + ---- + coro_fns: an iterable of coroutine functions, i.e. callables that + return a coroutine object when called. Use ``functools.partial`` or + lambdas to pass arguments. + + delay: amount of time, in seconds, between starting coroutines. If + ``None``, the coroutines will run sequentially. + + loop: the event loop to use. If ``None``, the running loop is used. + + Returns: + ------- + tuple *(winner_result, winner_index, exceptions)* where + + - *winner_result*: the result of the winning coroutine, or ``None`` + if no coroutines won. + + - *winner_index*: the index of the winning coroutine in + ``coro_fns``, or ``None`` if no coroutines won. If the winning + coroutine may return None on success, *winner_index* can be used + to definitively determine whether any coroutine won. + + - *exceptions*: list of exceptions returned by the coroutines. + ``len(exceptions)`` is equal to the number of coroutines actually + started, and the order is the same as in ``coro_fns``. The winning + coroutine's entry is ``None``. + + """ + loop = loop or asyncio.get_running_loop() + exceptions: List[Optional[BaseException]] = [] + tasks: Set[asyncio.Task[Optional[Tuple[_T, int]]]] = set() + + async def run_one_coro( + coro_fn: Callable[[], Awaitable[_T]], + this_index: int, + start_next: "asyncio.Future[None]", + ) -> Optional[Tuple[_T, int]]: + """ + Run a single coroutine. + + If the coroutine fails, set the exception in the exceptions list and + start the next coroutine by setting the result of the start_next. + + If the coroutine succeeds, return the result and the index of the + coroutine in the coro_fns list. + + If SystemExit or KeyboardInterrupt is raised, re-raise it. + """ + try: + result = await coro_fn() + except RE_RAISE_EXCEPTIONS: + raise + except BaseException as e: + exceptions[this_index] = e + _set_result(start_next) # Kickstart the next coroutine + return None + + return result, this_index + + start_next_timer: Optional[asyncio.TimerHandle] = None + start_next: Optional[asyncio.Future[None]] + task: asyncio.Task[Optional[Tuple[_T, int]]] + done: Union[asyncio.Future[None], asyncio.Task[Optional[Tuple[_T, int]]]] + coro_iter = iter(coro_fns) + this_index = -1 + try: + while True: + if coro_fn := next(coro_iter, None): + this_index += 1 + exceptions.append(None) + start_next = loop.create_future() + task = loop.create_task(run_one_coro(coro_fn, this_index, start_next)) + tasks.add(task) + start_next_timer = ( + loop.call_later(delay, _set_result, start_next) if delay else None + ) + elif not tasks: + # We exhausted the coro_fns list and no tasks are running + # so we have no winner and all coroutines failed. + break + + while tasks or start_next: + done = await _wait_one( + (*tasks, start_next) if start_next else tasks, loop + ) + if done is start_next: + # The current task has failed or the timer has expired + # so we need to start the next task. + start_next = None + if start_next_timer: + start_next_timer.cancel() + start_next_timer = None + + # Break out of the task waiting loop to start the next + # task. + break + + if TYPE_CHECKING: + assert isinstance(done, asyncio.Task) + + tasks.remove(done) + if winner := done.result(): + return *winner, exceptions + finally: + # We either have: + # - a winner + # - all tasks failed + # - a KeyboardInterrupt or SystemExit. + + # + # If the timer is still running, cancel it. + # + if start_next_timer: + start_next_timer.cancel() + + # + # If there are any tasks left, cancel them and than + # wait them so they fill the exceptions list. + # + for task in tasks: + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + return None, None, exceptions diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/impl.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/impl.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3919a0c959f6dc84cbdfce470218a9ac7fac65 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/impl.py @@ -0,0 +1,259 @@ +"""Base implementation.""" + +import asyncio +import collections +import contextlib +import functools +import itertools +import socket +from typing import List, Optional, Sequence, Set, Union + +from . import _staggered +from .types import AddrInfoType, SocketFactoryType + + +async def start_connection( + addr_infos: Sequence[AddrInfoType], + *, + local_addr_infos: Optional[Sequence[AddrInfoType]] = None, + happy_eyeballs_delay: Optional[float] = None, + interleave: Optional[int] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + socket_factory: Optional[SocketFactoryType] = None, +) -> socket.socket: + """ + Connect to a TCP server. + + Create a socket connection to a specified destination. The + destination is specified as a list of AddrInfoType tuples as + returned from getaddrinfo(). + + The arguments are, in order: + + * ``family``: the address family, e.g. ``socket.AF_INET`` or + ``socket.AF_INET6``. + * ``type``: the socket type, e.g. ``socket.SOCK_STREAM`` or + ``socket.SOCK_DGRAM``. + * ``proto``: the protocol, e.g. ``socket.IPPROTO_TCP`` or + ``socket.IPPROTO_UDP``. + * ``canonname``: the canonical name of the address, e.g. + ``"www.python.org"``. + * ``sockaddr``: the socket address + + This method is a coroutine which will try to establish the connection + in the background. When successful, the coroutine returns a + socket. + + The expected use case is to use this method in conjunction with + loop.create_connection() to establish a connection to a server:: + + socket = await start_connection(addr_infos) + transport, protocol = await loop.create_connection( + MyProtocol, sock=socket, ...) + """ + if not (current_loop := loop): + current_loop = asyncio.get_running_loop() + + single_addr_info = len(addr_infos) == 1 + + if happy_eyeballs_delay is not None and interleave is None: + # If using happy eyeballs, default to interleave addresses by family + interleave = 1 + + if interleave and not single_addr_info: + addr_infos = _interleave_addrinfos(addr_infos, interleave) + + sock: Optional[socket.socket] = None + # uvloop can raise RuntimeError instead of OSError + exceptions: List[List[Union[OSError, RuntimeError]]] = [] + if happy_eyeballs_delay is None or single_addr_info: + # not using happy eyeballs + for addrinfo in addr_infos: + try: + sock = await _connect_sock( + current_loop, + exceptions, + addrinfo, + local_addr_infos, + None, + socket_factory, + ) + break + except (RuntimeError, OSError): + continue + else: # using happy eyeballs + open_sockets: Set[socket.socket] = set() + try: + sock, _, _ = await _staggered.staggered_race( + ( + functools.partial( + _connect_sock, + current_loop, + exceptions, + addrinfo, + local_addr_infos, + open_sockets, + socket_factory, + ) + for addrinfo in addr_infos + ), + happy_eyeballs_delay, + ) + finally: + # If we have a winner, staggered_race will + # cancel the other tasks, however there is a + # small race window where any of the other tasks + # can be done before they are cancelled which + # will leave the socket open. To avoid this problem + # we pass a set to _connect_sock to keep track of + # the open sockets and close them here if there + # are any "runner up" sockets. + for s in open_sockets: + if s is not sock: + with contextlib.suppress(OSError): + s.close() + open_sockets = None # type: ignore[assignment] + + if sock is None: + all_exceptions = [exc for sub in exceptions for exc in sub] + try: + first_exception = all_exceptions[0] + if len(all_exceptions) == 1: + raise first_exception + else: + # If they all have the same str(), raise one. + model = str(first_exception) + if all(str(exc) == model for exc in all_exceptions): + raise first_exception + # Raise a combined exception so the user can see all + # the various error messages. + msg = "Multiple exceptions: {}".format( + ", ".join(str(exc) for exc in all_exceptions) + ) + # If the errno is the same for all exceptions, raise + # an OSError with that errno. + if isinstance(first_exception, OSError): + first_errno = first_exception.errno + if all( + isinstance(exc, OSError) and exc.errno == first_errno + for exc in all_exceptions + ): + raise OSError(first_errno, msg) + elif isinstance(first_exception, RuntimeError) and all( + isinstance(exc, RuntimeError) for exc in all_exceptions + ): + raise RuntimeError(msg) + # We have a mix of OSError and RuntimeError + # so we have to pick which one to raise. + # and we raise OSError for compatibility + raise OSError(msg) + finally: + all_exceptions = None # type: ignore[assignment] + exceptions = None # type: ignore[assignment] + + return sock + + +async def _connect_sock( + loop: asyncio.AbstractEventLoop, + exceptions: List[List[Union[OSError, RuntimeError]]], + addr_info: AddrInfoType, + local_addr_infos: Optional[Sequence[AddrInfoType]] = None, + open_sockets: Optional[Set[socket.socket]] = None, + socket_factory: Optional[SocketFactoryType] = None, +) -> socket.socket: + """ + Create, bind and connect one socket. + + If open_sockets is passed, add the socket to the set of open sockets. + Any failure caught here will remove the socket from the set and close it. + + Callers can use this set to close any sockets that are not the winner + of all staggered tasks in the result there are runner up sockets aka + multiple winners. + """ + my_exceptions: List[Union[OSError, RuntimeError]] = [] + exceptions.append(my_exceptions) + family, type_, proto, _, address = addr_info + sock = None + try: + if socket_factory is not None: + sock = socket_factory(addr_info) + else: + sock = socket.socket(family=family, type=type_, proto=proto) + if open_sockets is not None: + open_sockets.add(sock) + sock.setblocking(False) + if local_addr_infos is not None: + for lfamily, _, _, _, laddr in local_addr_infos: + # skip local addresses of different family + if lfamily != family: + continue + try: + sock.bind(laddr) + break + except OSError as exc: + msg = ( + f"error while attempting to bind on " + f"address {laddr!r}: " + f"{(exc.strerror or '').lower()}" + ) + exc = OSError(exc.errno, msg) + my_exceptions.append(exc) + else: # all bind attempts failed + if my_exceptions: + raise my_exceptions.pop() + else: + raise OSError(f"no matching local address with {family=} found") + await loop.sock_connect(sock, address) + return sock + except (RuntimeError, OSError) as exc: + my_exceptions.append(exc) + if sock is not None: + if open_sockets is not None: + open_sockets.remove(sock) + try: + sock.close() + except OSError as e: + my_exceptions.append(e) + raise + raise + except: + if sock is not None: + if open_sockets is not None: + open_sockets.remove(sock) + try: + sock.close() + except OSError as e: + my_exceptions.append(e) + raise + raise + finally: + exceptions = my_exceptions = None # type: ignore[assignment] + + +def _interleave_addrinfos( + addrinfos: Sequence[AddrInfoType], first_address_family_count: int = 1 +) -> List[AddrInfoType]: + """Interleave list of addrinfo tuples by family.""" + # Group addresses by family + addrinfos_by_family: collections.OrderedDict[int, List[AddrInfoType]] = ( + collections.OrderedDict() + ) + for addr in addrinfos: + family = addr[0] + if family not in addrinfos_by_family: + addrinfos_by_family[family] = [] + addrinfos_by_family[family].append(addr) + addrinfos_lists = list(addrinfos_by_family.values()) + + reordered: List[AddrInfoType] = [] + if first_address_family_count > 1: + reordered.extend(addrinfos_lists[0][: first_address_family_count - 1]) + del addrinfos_lists[0][: first_address_family_count - 1] + reordered.extend( + a + for a in itertools.chain.from_iterable(itertools.zip_longest(*addrinfos_lists)) + if a is not None + ) + return reordered diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/py.typed b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/types.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/types.py new file mode 100644 index 0000000000000000000000000000000000000000..e8c75074e7ab397af7ee1d1eb57cf04957a7a619 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/types.py @@ -0,0 +1,17 @@ +"""Types for aiohappyeyeballs.""" + +import socket + +# PY3.9: Import Callable from typing until we drop Python 3.9 support +# https://github.com/python/cpython/issues/87131 +from typing import Callable, Tuple, Union + +AddrInfoType = Tuple[ + Union[int, socket.AddressFamily], + Union[int, socket.SocketKind], + int, + str, + Tuple, # type: ignore[type-arg] +] + +SocketFactoryType = Callable[[AddrInfoType], socket.socket] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ea29adb9be9edd751cd6d7b93ca9c4bd8d08b658 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohappyeyeballs/utils.py @@ -0,0 +1,97 @@ +"""Utility functions for aiohappyeyeballs.""" + +import ipaddress +import socket +from typing import Dict, List, Optional, Tuple, Union + +from .types import AddrInfoType + + +def addr_to_addr_infos( + addr: Optional[ + Union[Tuple[str, int, int, int], Tuple[str, int, int], Tuple[str, int]] + ], +) -> Optional[List[AddrInfoType]]: + """Convert an address tuple to a list of addr_info tuples.""" + if addr is None: + return None + host = addr[0] + port = addr[1] + is_ipv6 = ":" in host + if is_ipv6: + flowinfo = 0 + scopeid = 0 + addr_len = len(addr) + if addr_len >= 4: + scopeid = addr[3] # type: ignore[misc] + if addr_len >= 3: + flowinfo = addr[2] # type: ignore[misc] + addr = (host, port, flowinfo, scopeid) + family = socket.AF_INET6 + else: + addr = (host, port) + family = socket.AF_INET + return [(family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr)] + + +def pop_addr_infos_interleave( + addr_infos: List[AddrInfoType], interleave: Optional[int] = None +) -> None: + """ + Pop addr_info from the list of addr_infos by family up to interleave times. + + The interleave parameter is used to know how many addr_infos for + each family should be popped of the top of the list. + """ + seen: Dict[int, int] = {} + if interleave is None: + interleave = 1 + to_remove: List[AddrInfoType] = [] + for addr_info in addr_infos: + family = addr_info[0] + if family not in seen: + seen[family] = 0 + if seen[family] < interleave: + to_remove.append(addr_info) + seen[family] += 1 + for addr_info in to_remove: + addr_infos.remove(addr_info) + + +def _addr_tuple_to_ip_address( + addr: Union[Tuple[str, int], Tuple[str, int, int, int]], +) -> Union[ + Tuple[ipaddress.IPv4Address, int], Tuple[ipaddress.IPv6Address, int, int, int] +]: + """Convert an address tuple to an IPv4Address.""" + return (ipaddress.ip_address(addr[0]), *addr[1:]) + + +def remove_addr_infos( + addr_infos: List[AddrInfoType], + addr: Union[Tuple[str, int], Tuple[str, int, int, int]], +) -> None: + """ + Remove an address from the list of addr_infos. + + The addr value is typically the return value of + sock.getpeername(). + """ + bad_addrs_infos: List[AddrInfoType] = [] + for addr_info in addr_infos: + if addr_info[-1] == addr: + bad_addrs_infos.append(addr_info) + if bad_addrs_infos: + for bad_addr_info in bad_addrs_infos: + addr_infos.remove(bad_addr_info) + return + # Slow path in case addr is formatted differently + match_addr = _addr_tuple_to_ip_address(addr) + for addr_info in addr_infos: + if match_addr == _addr_tuple_to_ip_address(addr_info[-1]): + bad_addrs_infos.append(addr_info) + if bad_addrs_infos: + for bad_addr_info in bad_addrs_infos: + addr_infos.remove(bad_addr_info) + return + raise ValueError(f"Address {addr} not found in addr_infos") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/INSTALLER b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/METADATA b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..4f71fd11d756c0ba828a14a8ee13acaa89f5ea0a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/METADATA @@ -0,0 +1,250 @@ +Metadata-Version: 2.4 +Name: aiohttp +Version: 3.12.14 +Summary: Async http client/server framework (asyncio) +Home-page: https://github.com/aio-libs/aiohttp +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache-2.0 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiohttp +Project-URL: Docs: Changelog, https://docs.aiohttp.org/en/stable/changes.html +Project-URL: Docs: RTD, https://docs.aiohttp.org +Project-URL: GitHub: issues, https://github.com/aio-libs/aiohttp/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/aiohttp +Classifier: Development Status :: 5 - Production/Stable +Classifier: Framework :: AsyncIO +Classifier: Intended Audience :: Developers +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Internet :: WWW/HTTP +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE.txt +Requires-Dist: aiohappyeyeballs>=2.5.0 +Requires-Dist: aiosignal>=1.4.0 +Requires-Dist: async-timeout<6.0,>=4.0; python_version < "3.11" +Requires-Dist: attrs>=17.3.0 +Requires-Dist: frozenlist>=1.1.1 +Requires-Dist: multidict<7.0,>=4.5 +Requires-Dist: propcache>=0.2.0 +Requires-Dist: yarl<2.0,>=1.17.0 +Provides-Extra: speedups +Requires-Dist: aiodns>=3.3.0; extra == "speedups" +Requires-Dist: Brotli; platform_python_implementation == "CPython" and extra == "speedups" +Requires-Dist: brotlicffi; platform_python_implementation != "CPython" and extra == "speedups" +Dynamic: license-file + +================================== +Async http client/server framework +================================== + +.. image:: https://raw.githubusercontent.com/aio-libs/aiohttp/master/docs/aiohttp-plain.svg + :height: 64px + :width: 64px + :alt: aiohttp logo + +| + +.. image:: https://github.com/aio-libs/aiohttp/workflows/CI/badge.svg + :target: https://github.com/aio-libs/aiohttp/actions?query=workflow%3ACI + :alt: GitHub Actions status for master branch + +.. image:: https://codecov.io/gh/aio-libs/aiohttp/branch/master/graph/badge.svg + :target: https://codecov.io/gh/aio-libs/aiohttp + :alt: codecov.io status for master branch + +.. image:: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json + :target: https://codspeed.io/aio-libs/aiohttp + :alt: Codspeed.io status for aiohttp + +.. image:: https://badge.fury.io/py/aiohttp.svg + :target: https://pypi.org/project/aiohttp + :alt: Latest PyPI package version + +.. image:: https://readthedocs.org/projects/aiohttp/badge/?version=latest + :target: https://docs.aiohttp.org/ + :alt: Latest Read The Docs + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + + +Key Features +============ + +- Supports both client and server side of HTTP protocol. +- Supports both client and server Web-Sockets out-of-the-box and avoids + Callback Hell. +- Provides Web-server with middleware and pluggable routing. + + +Getting started +=============== + +Client +------ + +To get something from the web: + +.. code-block:: python + + import aiohttp + import asyncio + + async def main(): + + async with aiohttp.ClientSession() as session: + async with session.get('http://python.org') as response: + + print("Status:", response.status) + print("Content-type:", response.headers['content-type']) + + html = await response.text() + print("Body:", html[:15], "...") + + asyncio.run(main()) + +This prints: + +.. code-block:: + + Status: 200 + Content-type: text/html; charset=utf-8 + Body: ... + +Coming from `requests `_ ? Read `why we need so many lines `_. + +Server +------ + +An example using a simple server: + +.. code-block:: python + + # examples/server_simple.py + from aiohttp import web + + async def handle(request): + name = request.match_info.get('name', "Anonymous") + text = "Hello, " + name + return web.Response(text=text) + + async def wshandle(request): + ws = web.WebSocketResponse() + await ws.prepare(request) + + async for msg in ws: + if msg.type == web.WSMsgType.text: + await ws.send_str("Hello, {}".format(msg.data)) + elif msg.type == web.WSMsgType.binary: + await ws.send_bytes(msg.data) + elif msg.type == web.WSMsgType.close: + break + + return ws + + + app = web.Application() + app.add_routes([web.get('/', handle), + web.get('/echo', wshandle), + web.get('/{name}', handle)]) + + if __name__ == '__main__': + web.run_app(app) + + +Documentation +============= + +https://aiohttp.readthedocs.io/ + + +Demos +===== + +https://github.com/aio-libs/aiohttp-demos + + +External links +============== + +* `Third party libraries + `_ +* `Built with aiohttp + `_ +* `Powered by aiohttp + `_ + +Feel free to make a Pull Request for adding your link to these pages! + + +Communication channels +====================== + +*aio-libs Discussions*: https://github.com/aio-libs/aiohttp/discussions + +*Matrix*: `#aio-libs:matrix.org `_ + +We support `Stack Overflow +`_. +Please add *aiohttp* tag to your question there. + +Requirements +============ + +- attrs_ +- multidict_ +- yarl_ +- frozenlist_ + +Optionally you may install the aiodns_ library (highly recommended for sake of speed). + +.. _aiodns: https://pypi.python.org/pypi/aiodns +.. _attrs: https://github.com/python-attrs/attrs +.. _multidict: https://pypi.python.org/pypi/multidict +.. _frozenlist: https://pypi.org/project/frozenlist/ +.. _yarl: https://pypi.python.org/pypi/yarl +.. _async-timeout: https://pypi.python.org/pypi/async_timeout + +License +======= + +``aiohttp`` is offered under the Apache 2 license. + + +Keepsafe +======== + +The aiohttp community would like to thank Keepsafe +(https://www.getkeepsafe.com) for its support in the early days of +the project. + + +Source code +=========== + +The latest developer version is available in a GitHub repository: +https://github.com/aio-libs/aiohttp + +Benchmarks +========== + +If you are interested in efficiency, the AsyncIO community maintains a +list of benchmarks on the official wiki: +https://github.com/python/asyncio/wiki/Benchmarks diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/RECORD b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..250ab1057e255297053e0fb834e5d667e75aff53 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/RECORD @@ -0,0 +1,138 @@ +aiohttp-3.12.14.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiohttp-3.12.14.dist-info/METADATA,sha256=eANbIsB4Kj7_7QofG0pGvr-qVDn7-uqvxOTGuI0iX_w,7613 +aiohttp-3.12.14.dist-info/RECORD,, +aiohttp-3.12.14.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +aiohttp-3.12.14.dist-info/WHEEL,sha256=aSgG0F4rGPZtV0iTEIfy6dtHq6g67Lze3uLfk0vWn88,151 +aiohttp-3.12.14.dist-info/licenses/LICENSE.txt,sha256=n4DQ2311WpQdtFchcsJw7L2PCCuiFd3QlZhZQu2Uqes,588 +aiohttp-3.12.14.dist-info/top_level.txt,sha256=iv-JIaacmTl-hSho3QmphcKnbRRYx1st47yjz_178Ro,8 +aiohttp/.hash/_cparser.pxd.hash,sha256=pjs-sEXNw_eijXGAedwG-BHnlFp8B7sOCgUagIWaU2A,121 +aiohttp/.hash/_find_header.pxd.hash,sha256=_mbpD6vM-CVCKq3ulUvsOAz5Wdo88wrDzfpOsMQaMNA,125 +aiohttp/.hash/_http_parser.pyx.hash,sha256=8LCTs_O4fFH1HswgQLgjUn8gknOO8Z8V63c_hQ4fNnM,125 +aiohttp/.hash/_http_writer.pyx.hash,sha256=uhOanbDG8R2Pxria3xMb15h7biBeeT3ioBoQNwqKYp8,125 +aiohttp/.hash/hdrs.py.hash,sha256=v6IaKbsxjsdQxBzhb5AjP0x_9G3rUe84D7avf7AI4cs,116 +aiohttp/__init__.py,sha256=Pzr8s2ho-qqwAaB81nT1jk2rkDSL3dcAbMguPmcLpyc,8303 +aiohttp/__pycache__/__init__.cpython-312.pyc,, +aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc,, +aiohttp/__pycache__/abc.cpython-312.pyc,, +aiohttp/__pycache__/base_protocol.cpython-312.pyc,, +aiohttp/__pycache__/client.cpython-312.pyc,, +aiohttp/__pycache__/client_exceptions.cpython-312.pyc,, +aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc,, +aiohttp/__pycache__/client_middlewares.cpython-312.pyc,, +aiohttp/__pycache__/client_proto.cpython-312.pyc,, +aiohttp/__pycache__/client_reqrep.cpython-312.pyc,, +aiohttp/__pycache__/client_ws.cpython-312.pyc,, +aiohttp/__pycache__/compression_utils.cpython-312.pyc,, +aiohttp/__pycache__/connector.cpython-312.pyc,, +aiohttp/__pycache__/cookiejar.cpython-312.pyc,, +aiohttp/__pycache__/formdata.cpython-312.pyc,, +aiohttp/__pycache__/hdrs.cpython-312.pyc,, +aiohttp/__pycache__/helpers.cpython-312.pyc,, +aiohttp/__pycache__/http.cpython-312.pyc,, +aiohttp/__pycache__/http_exceptions.cpython-312.pyc,, +aiohttp/__pycache__/http_parser.cpython-312.pyc,, +aiohttp/__pycache__/http_websocket.cpython-312.pyc,, +aiohttp/__pycache__/http_writer.cpython-312.pyc,, +aiohttp/__pycache__/log.cpython-312.pyc,, +aiohttp/__pycache__/multipart.cpython-312.pyc,, +aiohttp/__pycache__/payload.cpython-312.pyc,, +aiohttp/__pycache__/payload_streamer.cpython-312.pyc,, +aiohttp/__pycache__/pytest_plugin.cpython-312.pyc,, +aiohttp/__pycache__/resolver.cpython-312.pyc,, +aiohttp/__pycache__/streams.cpython-312.pyc,, +aiohttp/__pycache__/tcp_helpers.cpython-312.pyc,, +aiohttp/__pycache__/test_utils.cpython-312.pyc,, +aiohttp/__pycache__/tracing.cpython-312.pyc,, +aiohttp/__pycache__/typedefs.cpython-312.pyc,, +aiohttp/__pycache__/web.cpython-312.pyc,, +aiohttp/__pycache__/web_app.cpython-312.pyc,, +aiohttp/__pycache__/web_exceptions.cpython-312.pyc,, +aiohttp/__pycache__/web_fileresponse.cpython-312.pyc,, +aiohttp/__pycache__/web_log.cpython-312.pyc,, +aiohttp/__pycache__/web_middlewares.cpython-312.pyc,, +aiohttp/__pycache__/web_protocol.cpython-312.pyc,, +aiohttp/__pycache__/web_request.cpython-312.pyc,, +aiohttp/__pycache__/web_response.cpython-312.pyc,, +aiohttp/__pycache__/web_routedef.cpython-312.pyc,, +aiohttp/__pycache__/web_runner.cpython-312.pyc,, +aiohttp/__pycache__/web_server.cpython-312.pyc,, +aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc,, +aiohttp/__pycache__/web_ws.cpython-312.pyc,, +aiohttp/__pycache__/worker.cpython-312.pyc,, +aiohttp/_cookie_helpers.py,sha256=xjCVZKrQIfH1bwN5UeNrem8kevnXwZcBoNY94yyk8Qc,12418 +aiohttp/_cparser.pxd,sha256=UnbUYCHg4NdXfgyRVYAMv2KTLWClB4P-xCrvtj_r7ew,4295 +aiohttp/_find_header.pxd,sha256=0GfwFCPN2zxEKTO1_MA5sYq2UfzsG8kcV3aTqvwlz3g,68 +aiohttp/_headers.pxi,sha256=n701k28dVPjwRnx5j6LpJhLTfj7dqu2vJt7f0O60Oyg,2007 +aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so,sha256=ealDvc9qJCkwzAIYgtKMLkij41Qxk78JXdZiUokTTvg,2878000 +aiohttp/_http_parser.pyx,sha256=1L07PKuJjgDGQuqlmy965a5aoTdOaYWX99gFowLyPiE,28239 +aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so,sha256=fGELEfKELoBWO-C9VKXunQnqSLURO1RvlGL59rVyOt8,511688 +aiohttp/_http_writer.pyx,sha256=96seJigne4J3LVnB3DAzwTSV12nfZ7HR1JsaR0p13VI,4561 +aiohttp/_websocket/.hash/mask.pxd.hash,sha256=Y0zBddk_ck3pi9-BFzMcpkcvCKvwvZ4GTtZFb9u1nxQ,128 +aiohttp/_websocket/.hash/mask.pyx.hash,sha256=90owpXYM8_kIma4KUcOxhWSk-Uv4NVMBoCYeFM1B3d0,128 +aiohttp/_websocket/.hash/reader_c.pxd.hash,sha256=5xf3oobk6vx4xbJm-xtZ1_QufB8fYFtLQV2MNdqUc1w,132 +aiohttp/_websocket/__init__.py,sha256=Mar3R9_vBN_Ea4lsW7iTAVXD7OKswKPGqF5xgSyt77k,44 +aiohttp/_websocket/__pycache__/__init__.cpython-312.pyc,, +aiohttp/_websocket/__pycache__/helpers.cpython-312.pyc,, +aiohttp/_websocket/__pycache__/models.cpython-312.pyc,, +aiohttp/_websocket/__pycache__/reader.cpython-312.pyc,, +aiohttp/_websocket/__pycache__/reader_c.cpython-312.pyc,, +aiohttp/_websocket/__pycache__/reader_py.cpython-312.pyc,, +aiohttp/_websocket/__pycache__/writer.cpython-312.pyc,, +aiohttp/_websocket/helpers.py,sha256=P-XLv8IUaihKzDenVUqfKU5DJbWE5HvG8uhvUZK8Ic4,5038 +aiohttp/_websocket/mask.cpython-312-x86_64-linux-gnu.so,sha256=PISNT8-1dxCmHxX3aMjYsrAatk5CLnJtjvIvpL7sUcA,258728 +aiohttp/_websocket/mask.pxd,sha256=sBmZ1Amym9kW4Ge8lj1fLZ7mPPya4LzLdpkQExQXv5M,112 +aiohttp/_websocket/mask.pyx,sha256=BHjOtV0O0w7xp9p0LNADRJvGmgfPn9sGeJvSs0fL__4,1397 +aiohttp/_websocket/models.py,sha256=XAzjs_8JYszWXIgZ6R3ZRrF-tX9Q_6LiD49WRYojopM,2121 +aiohttp/_websocket/reader.py,sha256=eC4qS0c5sOeQ2ebAHLaBpIaTVFaSKX79pY2xvh3Pqyw,1030 +aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so,sha256=VkB5K9VXo-zC9aaa7p3xOwSTs-OgeYsqZE21uJ1Jd4w,1818512 +aiohttp/_websocket/reader_c.pxd,sha256=nl_njtDrzlQU0rjgGGjZDB-swguE0tX_bCPobkShVa4,2625 +aiohttp/_websocket/reader_c.py,sha256=gSsE_iSBr7-ORvOmgkCT7Jpj4_j3854i_Cp88Se1_6E,18791 +aiohttp/_websocket/reader_py.py,sha256=gSsE_iSBr7-ORvOmgkCT7Jpj4_j3854i_Cp88Se1_6E,18791 +aiohttp/_websocket/writer.py,sha256=9qCnQnCFwPmvf6U6i_7VfTldjpcDfQ_ojeCv5mXoMkw,7139 +aiohttp/abc.py,sha256=jA2jRYAxc217gO96C-wDXcAPcDWjVJpqXrTGfa7uwqM,7148 +aiohttp/base_protocol.py,sha256=Tp8cxUPQvv9kUPk3w6lAzk6d2MAzV3scwI_3Go3C47c,3025 +aiohttp/client.py,sha256=UmwwoDurmDDvxTwa4e1VElko4mc8_Snsvs3CA6SE-kc,57584 +aiohttp/client_exceptions.py,sha256=uyKbxI2peZhKl7lELBMx3UeusNkfpemPWpGFq0r6JeM,11367 +aiohttp/client_middleware_digest_auth.py,sha256=_1RpbyJtbY42-qy5TGYvEa0PXZjAsFmf1CMXp-_626U,16938 +aiohttp/client_middlewares.py,sha256=kP5N9CMzQPMGPIEydeVUiLUTLsw8Vl8Gr4qAWYdu3vM,1918 +aiohttp/client_proto.py,sha256=56_WtLStZGBFPYKzgEgY6v24JkhV1y6JEmmuxeJT2So,12110 +aiohttp/client_reqrep.py,sha256=OJuvhGlFMxq7i0z2WLovzeaAcICeNn3qKA25MhwsZrY,53524 +aiohttp/client_ws.py,sha256=1CIjIXwyzOMIYw6AjUES4-qUwbyVHW1seJKQfg_Rta8,15109 +aiohttp/compression_utils.py,sha256=LDUVfDiChHNb_ojMEITJuoSEbOAQ4Qznu07vTHL-_pY,8868 +aiohttp/connector.py,sha256=WQetKoSW7XnHA9r4o9OWwO3-n7ymOwBd2Tg_xHNw0Bs,68456 +aiohttp/cookiejar.py,sha256=e28ZMQwJ5P0vbPX1OX4Se7-k3zeGvocFEqzGhwpG53k,18922 +aiohttp/formdata.py,sha256=dRmQY8LA6WSj5HzqF9tUzu_SNe6mzZ1DqXXkyg4ga20,6410 +aiohttp/hdrs.py,sha256=2rj5MyA-6yRdYPhW5UKkW4iNWhEAlGIOSBH5D4FmKNE,5111 +aiohttp/helpers.py,sha256=bblNEhp4hFimEmxMdPNxEluBY17L5YUArHYvoxzoEe4,29614 +aiohttp/http.py,sha256=8o8j8xH70OWjnfTWA9V44NR785QPxEPrUtzMXiAVpwc,1842 +aiohttp/http_exceptions.py,sha256=AZafFHgtAkAgrKZf8zYPU8VX2dq32-VAoP-UZxBLU0c,2960 +aiohttp/http_parser.py,sha256=SRADKjgUtYJxUgvvYTyJA0wB8WpKjTcKpzIT8fsE1aE,36896 +aiohttp/http_websocket.py,sha256=8VXFKw6KQUEmPg48GtRMB37v0gTK7A0inoxXuDxMZEc,842 +aiohttp/http_writer.py,sha256=fbRtKPYSqRbtAdr_gqpjF2-4sI1ESL8dPDF-xY_mAMY,12446 +aiohttp/log.py,sha256=BbNKx9e3VMIm0xYjZI0IcBBoS7wjdeIeSaiJE7-qK2g,325 +aiohttp/multipart.py,sha256=YvgDa5-vOAk9njEJAVwa-L6XVu83PNdct56tDJsfSjI,39867 +aiohttp/payload.py,sha256=qHpvXhgJyODHjb6tEq7oyB6ChCBRVZV7kd3QAoMhW8k,41044 +aiohttp/payload_streamer.py,sha256=ZzEYyfzcjGWkVkK3XR2pBthSCSIykYvY3Wr5cGQ2eTc,2211 +aiohttp/py.typed,sha256=sow9soTwP9T_gEAQSVh7Gb8855h04Nwmhs2We-JRgZM,7 +aiohttp/pytest_plugin.py,sha256=z4XwqmsKdyJCKxbGiA5kFf90zcedvomqk4RqjZbhKNk,12901 +aiohttp/resolver.py,sha256=gsrfUpFf8iHlcHfJvY-1fiBHW3PRvRVNb5lNZBg3zlY,10031 +aiohttp/streams.py,sha256=U-qTkuAqIfpJChuKEy-vYn8nQ_Z1MVcW0WO2DHiJz_o,22329 +aiohttp/tcp_helpers.py,sha256=BSadqVWaBpMFDRWnhaaR941N9MiDZ7bdTrxgCb0CW-M,961 +aiohttp/test_utils.py,sha256=ZJSzZWjC76KSbtwddTKcP6vHpUl_ozfAf3F93ewmHRU,23016 +aiohttp/tracing.py,sha256=-6aaW6l0J9uJD45LzR4cijYH0j62pt0U_nn_aVzFku4,14558 +aiohttp/typedefs.py,sha256=wUlqwe9Mw9W8jT3HsYJcYk00qP3EMPz3nTkYXmeNN48,1657 +aiohttp/web.py,sha256=sG_U41AY4S_LBY9sReiBzXKJRZpXk8xgiE_l5S_UPPg,18390 +aiohttp/web_app.py,sha256=lGU_aAMN-h3wy-LTTHi6SeKH8ydt1G51BXcCspgD5ZA,19452 +aiohttp/web_exceptions.py,sha256=7nIuiwhZ39vJJ9KrWqArA5QcWbUdqkz2CLwEpJapeN8,10360 +aiohttp/web_fileresponse.py,sha256=EtDuw5mF7uGkjrrwSBaDQk6F1FJW4pnwE2pZGv3T1QI,16474 +aiohttp/web_log.py,sha256=rX5D7xLOX2B6BMdiZ-chme_KfJfW5IXEoFwLfkfkajs,7865 +aiohttp/web_middlewares.py,sha256=sFI0AgeNjdyAjuz92QtMIpngmJSOxrqe2Jfbs4BNUu0,4165 +aiohttp/web_protocol.py,sha256=c8a0PKGqfhIAiq2RboMsy1NRza4dnj6gnXIWvJUeCF0,27015 +aiohttp/web_request.py,sha256=zN96OlMRlrCFOMRpdh7y9rvHP0Hm8zavC0OFCj0wlSg,29833 +aiohttp/web_response.py,sha256=GlxFuiUqqHoXkGGFymII59SbIKU-itLgsl-bD0wGrzc,29342 +aiohttp/web_routedef.py,sha256=VT1GAx6BrawoDh5RwBwBu5wSABSqgWwAe74AUCyZAEo,6110 +aiohttp/web_runner.py,sha256=v1G1nKiOOQgFnTSR4IMc6I9ReEFDMaHtMLvO_roDM-A,11786 +aiohttp/web_server.py,sha256=-9WDKUAiR9ll-rSdwXSqG6YjaoW79d1R4y0BGSqgUMA,2888 +aiohttp/web_urldispatcher.py,sha256=sFkcsa8qLFkDp47_oW7Z7fiq7DcVXiff1Etn0QN8DJA,44000 +aiohttp/web_ws.py,sha256=lItgmyatkXh0M6EY7JoZnSZkUl6R0wv8B88X4ILqQbU,22739 +aiohttp/worker.py,sha256=zT0iWN5Xze194bO6_VjHou0x7lR_k0MviN6Kadnk22g,8152 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/REQUESTED b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/REQUESTED new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/WHEEL b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e21e9f2f89caabbb0f5e84c1775fbe781dd45a63 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_17_x86_64 +Tag: cp312-cp312-manylinux2014_x86_64 + diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/licenses/LICENSE.txt b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..e497a322f2091d022983b9c5c043082ab61d1a8c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/licenses/LICENSE.txt @@ -0,0 +1,13 @@ + Copyright aio-libs contributors. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/top_level.txt b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee4ba4f3d739e094878215c84eb41ba85c80e4a8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp-3.12.14.dist-info/top_level.txt @@ -0,0 +1 @@ +aiohttp diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_cparser.pxd.hash b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_cparser.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..3f5cd0e6f720a049ee19149790c808558b492726 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_cparser.pxd.hash @@ -0,0 +1 @@ +5276d46021e0e0d7577e0c9155800cbf62932d60a50783fec42aefb63febedec /home/runner/work/aiohttp/aiohttp/aiohttp/_cparser.pxd diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_find_header.pxd.hash b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_find_header.pxd.hash new file mode 100644 index 0000000000000000000000000000000000000000..f006c2de5d24a1b5a9c26f83c858127b5e12b07c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_find_header.pxd.hash @@ -0,0 +1 @@ +d067f01423cddb3c442933b5fcc039b18ab651fcec1bc91c577693aafc25cf78 /home/runner/work/aiohttp/aiohttp/aiohttp/_find_header.pxd diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_http_parser.pyx.hash b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_http_parser.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..d8c2036a4ec28ee081de8fcd49f107bc0a7222d3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_http_parser.pyx.hash @@ -0,0 +1 @@ +d4bd3b3cab898e00c642eaa59b2f7ae5ae5aa1374e698597f7d805a302f23e21 /home/runner/work/aiohttp/aiohttp/aiohttp/_http_parser.pyx diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_http_writer.pyx.hash b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_http_writer.pyx.hash new file mode 100644 index 0000000000000000000000000000000000000000..771a6b17aa5bc2ecd8909c2d3c4b10ce769e55d0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/_http_writer.pyx.hash @@ -0,0 +1 @@ +f7ab1e2628277b82772d59c1dc3033c13495d769df67b1d1d49b1a474a75dd52 /home/runner/work/aiohttp/aiohttp/aiohttp/_http_writer.pyx diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/hdrs.py.hash b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/hdrs.py.hash new file mode 100644 index 0000000000000000000000000000000000000000..c8d55240e6a55c305c99244966dee5615565716b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/.hash/hdrs.py.hash @@ -0,0 +1 @@ +dab8f933203eeb245d60f856e542a45b888d5a110094620e4811f90f816628d1 /home/runner/work/aiohttp/aiohttp/aiohttp/hdrs.py diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a3ab781e98419cf1f161b7efa93fccf84e106e0e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__init__.py @@ -0,0 +1,278 @@ +__version__ = "3.12.14" + +from typing import TYPE_CHECKING, Tuple + +from . import hdrs as hdrs +from .client import ( + BaseConnector, + ClientConnectionError, + ClientConnectionResetError, + ClientConnectorCertificateError, + ClientConnectorDNSError, + ClientConnectorError, + ClientConnectorSSLError, + ClientError, + ClientHttpProxyError, + ClientOSError, + ClientPayloadError, + ClientProxyConnectionError, + ClientRequest, + ClientResponse, + ClientResponseError, + ClientSession, + ClientSSLError, + ClientTimeout, + ClientWebSocketResponse, + ClientWSTimeout, + ConnectionTimeoutError, + ContentTypeError, + Fingerprint, + InvalidURL, + InvalidUrlClientError, + InvalidUrlRedirectClientError, + NamedPipeConnector, + NonHttpUrlClientError, + NonHttpUrlRedirectClientError, + RedirectClientError, + RequestInfo, + ServerConnectionError, + ServerDisconnectedError, + ServerFingerprintMismatch, + ServerTimeoutError, + SocketTimeoutError, + TCPConnector, + TooManyRedirects, + UnixConnector, + WSMessageTypeError, + WSServerHandshakeError, + request, +) +from .client_middleware_digest_auth import DigestAuthMiddleware +from .client_middlewares import ClientHandlerType, ClientMiddlewareType +from .compression_utils import set_zlib_backend +from .connector import ( + AddrInfoType as AddrInfoType, + SocketFactoryType as SocketFactoryType, +) +from .cookiejar import CookieJar as CookieJar, DummyCookieJar as DummyCookieJar +from .formdata import FormData as FormData +from .helpers import BasicAuth, ChainMapProxy, ETag +from .http import ( + HttpVersion as HttpVersion, + HttpVersion10 as HttpVersion10, + HttpVersion11 as HttpVersion11, + WebSocketError as WebSocketError, + WSCloseCode as WSCloseCode, + WSMessage as WSMessage, + WSMsgType as WSMsgType, +) +from .multipart import ( + BadContentDispositionHeader as BadContentDispositionHeader, + BadContentDispositionParam as BadContentDispositionParam, + BodyPartReader as BodyPartReader, + MultipartReader as MultipartReader, + MultipartWriter as MultipartWriter, + content_disposition_filename as content_disposition_filename, + parse_content_disposition as parse_content_disposition, +) +from .payload import ( + PAYLOAD_REGISTRY as PAYLOAD_REGISTRY, + AsyncIterablePayload as AsyncIterablePayload, + BufferedReaderPayload as BufferedReaderPayload, + BytesIOPayload as BytesIOPayload, + BytesPayload as BytesPayload, + IOBasePayload as IOBasePayload, + JsonPayload as JsonPayload, + Payload as Payload, + StringIOPayload as StringIOPayload, + StringPayload as StringPayload, + TextIOPayload as TextIOPayload, + get_payload as get_payload, + payload_type as payload_type, +) +from .payload_streamer import streamer as streamer +from .resolver import ( + AsyncResolver as AsyncResolver, + DefaultResolver as DefaultResolver, + ThreadedResolver as ThreadedResolver, +) +from .streams import ( + EMPTY_PAYLOAD as EMPTY_PAYLOAD, + DataQueue as DataQueue, + EofStream as EofStream, + FlowControlDataQueue as FlowControlDataQueue, + StreamReader as StreamReader, +) +from .tracing import ( + TraceConfig as TraceConfig, + TraceConnectionCreateEndParams as TraceConnectionCreateEndParams, + TraceConnectionCreateStartParams as TraceConnectionCreateStartParams, + TraceConnectionQueuedEndParams as TraceConnectionQueuedEndParams, + TraceConnectionQueuedStartParams as TraceConnectionQueuedStartParams, + TraceConnectionReuseconnParams as TraceConnectionReuseconnParams, + TraceDnsCacheHitParams as TraceDnsCacheHitParams, + TraceDnsCacheMissParams as TraceDnsCacheMissParams, + TraceDnsResolveHostEndParams as TraceDnsResolveHostEndParams, + TraceDnsResolveHostStartParams as TraceDnsResolveHostStartParams, + TraceRequestChunkSentParams as TraceRequestChunkSentParams, + TraceRequestEndParams as TraceRequestEndParams, + TraceRequestExceptionParams as TraceRequestExceptionParams, + TraceRequestHeadersSentParams as TraceRequestHeadersSentParams, + TraceRequestRedirectParams as TraceRequestRedirectParams, + TraceRequestStartParams as TraceRequestStartParams, + TraceResponseChunkReceivedParams as TraceResponseChunkReceivedParams, +) + +if TYPE_CHECKING: + # At runtime these are lazy-loaded at the bottom of the file. + from .worker import ( + GunicornUVLoopWebWorker as GunicornUVLoopWebWorker, + GunicornWebWorker as GunicornWebWorker, + ) + +__all__: Tuple[str, ...] = ( + "hdrs", + # client + "AddrInfoType", + "BaseConnector", + "ClientConnectionError", + "ClientConnectionResetError", + "ClientConnectorCertificateError", + "ClientConnectorDNSError", + "ClientConnectorError", + "ClientConnectorSSLError", + "ClientError", + "ClientHttpProxyError", + "ClientOSError", + "ClientPayloadError", + "ClientProxyConnectionError", + "ClientResponse", + "ClientRequest", + "ClientResponseError", + "ClientSSLError", + "ClientSession", + "ClientTimeout", + "ClientWebSocketResponse", + "ClientWSTimeout", + "ConnectionTimeoutError", + "ContentTypeError", + "Fingerprint", + "FlowControlDataQueue", + "InvalidURL", + "InvalidUrlClientError", + "InvalidUrlRedirectClientError", + "NonHttpUrlClientError", + "NonHttpUrlRedirectClientError", + "RedirectClientError", + "RequestInfo", + "ServerConnectionError", + "ServerDisconnectedError", + "ServerFingerprintMismatch", + "ServerTimeoutError", + "SocketFactoryType", + "SocketTimeoutError", + "TCPConnector", + "TooManyRedirects", + "UnixConnector", + "NamedPipeConnector", + "WSServerHandshakeError", + "request", + # client_middleware + "ClientMiddlewareType", + "ClientHandlerType", + # cookiejar + "CookieJar", + "DummyCookieJar", + # formdata + "FormData", + # helpers + "BasicAuth", + "ChainMapProxy", + "DigestAuthMiddleware", + "ETag", + "set_zlib_backend", + # http + "HttpVersion", + "HttpVersion10", + "HttpVersion11", + "WSMsgType", + "WSCloseCode", + "WSMessage", + "WebSocketError", + # multipart + "BadContentDispositionHeader", + "BadContentDispositionParam", + "BodyPartReader", + "MultipartReader", + "MultipartWriter", + "content_disposition_filename", + "parse_content_disposition", + # payload + "AsyncIterablePayload", + "BufferedReaderPayload", + "BytesIOPayload", + "BytesPayload", + "IOBasePayload", + "JsonPayload", + "PAYLOAD_REGISTRY", + "Payload", + "StringIOPayload", + "StringPayload", + "TextIOPayload", + "get_payload", + "payload_type", + # payload_streamer + "streamer", + # resolver + "AsyncResolver", + "DefaultResolver", + "ThreadedResolver", + # streams + "DataQueue", + "EMPTY_PAYLOAD", + "EofStream", + "StreamReader", + # tracing + "TraceConfig", + "TraceConnectionCreateEndParams", + "TraceConnectionCreateStartParams", + "TraceConnectionQueuedEndParams", + "TraceConnectionQueuedStartParams", + "TraceConnectionReuseconnParams", + "TraceDnsCacheHitParams", + "TraceDnsCacheMissParams", + "TraceDnsResolveHostEndParams", + "TraceDnsResolveHostStartParams", + "TraceRequestChunkSentParams", + "TraceRequestEndParams", + "TraceRequestExceptionParams", + "TraceRequestHeadersSentParams", + "TraceRequestRedirectParams", + "TraceRequestStartParams", + "TraceResponseChunkReceivedParams", + # workers (imported lazily with __getattr__) + "GunicornUVLoopWebWorker", + "GunicornWebWorker", + "WSMessageTypeError", +) + + +def __dir__() -> Tuple[str, ...]: + return __all__ + ("__doc__",) + + +def __getattr__(name: str) -> object: + global GunicornUVLoopWebWorker, GunicornWebWorker + + # Importing gunicorn takes a long time (>100ms), so only import if actually needed. + if name in ("GunicornUVLoopWebWorker", "GunicornWebWorker"): + try: + from .worker import GunicornUVLoopWebWorker as guv, GunicornWebWorker as gw + except ImportError: + return None + + GunicornUVLoopWebWorker = guv # type: ignore[misc] + GunicornWebWorker = gw # type: ignore[misc] + return guv if name == "GunicornUVLoopWebWorker" else gw + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9295cd014056382d6588e859041df007afcd59e4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/__init__.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4abbe621a5ee834bc9e7c6341082c1468552100 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/_cookie_helpers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/abc.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/abc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6da95236c79e0e1b06821f7400043daa8280cb1f Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/abc.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/base_protocol.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/base_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39c65bc5e06507512fc406516b2808147e5e524c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/base_protocol.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..71d1974c23e561c503804654b9a761fe6a8568bb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_exceptions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1c50672b5066edbf5b9fdca9916b70cbf15ad2b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_exceptions.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb6b5eed817d37eaa6b961a0bfbb54b69d603fb4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_middleware_digest_auth.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_middlewares.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_middlewares.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f1303ab7adb7f44027bac9d57d32fa7be6068d5 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_middlewares.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_proto.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_proto.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0ddb968eb52cd08b0ea9f560cb7e71c0db1d20d Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_proto.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_reqrep.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_reqrep.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fbc8b956b7e88f2d21d5abce31f6b30e226df1e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_reqrep.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_ws.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_ws.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39401c1e91188ff3f472f5f9644388980102e7d8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/client_ws.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/compression_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/compression_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5710012d6673a798f3cb204bad910202f764cda Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/compression_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/connector.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/connector.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14c05fc86e4ab9228c2afac32dd440fe28dcb51b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/connector.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/cookiejar.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/cookiejar.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f576c880146adc199e7a01ccd3eef73c319fcdf2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/cookiejar.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/formdata.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/formdata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..638e2f79d3ea4771e599a7fa5a80389498f7b3a4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/formdata.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/hdrs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/hdrs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..178ee241c6b6ab7d310cdb7782e1ea6807d6bad4 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/hdrs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/helpers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4df5bd97b40bbd0eb46da643b922a1e06fa2e6f9 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/helpers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aee453ee31adba9116ad71a7d01799691e0ac1f0 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_exceptions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e600c4a31f0bc4a25fbddcfae3104e6966ab95cb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_exceptions.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_parser.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_parser.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f292ea34d8f13fe3f45a52916d68aa42b9e89e75 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_parser.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_websocket.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_websocket.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf9782ad8352864a11ef28ffdb16aff445025864 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_websocket.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_writer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_writer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8560c9cf5aa8392fca6655d6dbba5f22d269d79 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/http_writer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/log.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02d6929a49f297c8b7009024f12ffe5d88653c72 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/log.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/multipart.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/multipart.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7983f9d88bf1febcb9a27f29b5d2c5c7c296224b Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/multipart.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/payload.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/payload.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dfd70f6f731664cb4d288575e2802fb4ea331d33 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/payload.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/payload_streamer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/payload_streamer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..917f186a23ddd38e81287f8df669338c9480ced2 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/payload_streamer.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/pytest_plugin.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/pytest_plugin.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..12e9bf40d789ed4e59f26e2c387b50b91c0f362e Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/pytest_plugin.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/resolver.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/resolver.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d94c92e5001a4e6f96517515c6ce1fe9c5d9fc37 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/resolver.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/streams.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/streams.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2384877607719c163fcb5c2615b8dc24c078d7c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/streams.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b3165f606257e83059c8b977ee4a0f5607cdd73 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/tcp_helpers.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/test_utils.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/test_utils.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b0443a8ea1482113b1a73d5e794f01f7744d2df Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/test_utils.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/tracing.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/tracing.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4e829f0f148cec9e8d5cebc6b8f82d6bce031d8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/tracing.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/typedefs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/typedefs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..542091cb2b2048eba5df3ee5da822e094cc3989a Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/typedefs.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6580962436e6f67d59d7b4b5a5b3a98f768c2bb Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_app.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_app.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a78bbefc86c81a639f60d9b1489974fde973c43 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_app.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_exceptions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_exceptions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5522a04272bf4de2628dc429a23ca402b3aee7c8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_exceptions.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..071fda2ca92ff0734bb65593c2ac7b191f1f9328 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_fileresponse.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_log.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_log.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9facbc222b506227e00295501bfe2bd7f2b4aedd Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_log.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_middlewares.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_middlewares.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5505d9fe1e32066b862261b94694f712a7645247 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_middlewares.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_protocol.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_protocol.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..28c3f70046722208994ea5d94920307a70f949ec Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_protocol.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_request.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_request.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..966166df6aefaf0cdb706385b820186b25b866a7 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_request.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_response.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_response.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e5631aed43c37a0426817c00b030da258d29d9f8 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_response.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_routedef.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_routedef.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..984a851cdb1a8f93be7c029977ff78034ddbb830 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_routedef.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_runner.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_runner.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba289d846a81f7da47700fe957935cf52797ed59 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_runner.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_server.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_server.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c57ca38fc3d002c4e84578ad193061440cebb03 Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_server.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2a4070668be43df16ec6f2d490c09f596ed9ac1c Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/web_urldispatcher.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/worker.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/worker.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4adf1fd897cae47cc47e69180d8690146e0150aa Binary files /dev/null and b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/__pycache__/worker.cpython-312.pyc differ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_cookie_helpers.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_cookie_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..4e9fc968814efa9a4990a1a40f39dfea7553b6aa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_cookie_helpers.py @@ -0,0 +1,309 @@ +""" +Internal cookie handling helpers. + +This module contains internal utilities for cookie parsing and manipulation. +These are not part of the public API and may change without notice. +""" + +import re +import sys +from http.cookies import Morsel +from typing import List, Optional, Sequence, Tuple, cast + +from .log import internal_logger + +__all__ = ( + "parse_set_cookie_headers", + "parse_cookie_header", + "preserve_morsel_with_coded_value", +) + +# Cookie parsing constants +# Allow more characters in cookie names to handle real-world cookies +# that don't strictly follow RFC standards (fixes #2683) +# RFC 6265 defines cookie-name token as per RFC 2616 Section 2.2, +# but many servers send cookies with characters like {} [] () etc. +# This makes the cookie parser more tolerant of real-world cookies +# while still providing some validation to catch obviously malformed names. +_COOKIE_NAME_RE = re.compile(r"^[!#$%&\'()*+\-./0-9:<=>?@A-Z\[\]^_`a-z{|}~]+$") +_COOKIE_KNOWN_ATTRS = frozenset( # AKA Morsel._reserved + ( + "path", + "domain", + "max-age", + "expires", + "secure", + "httponly", + "samesite", + "partitioned", + "version", + "comment", + ) +) +_COOKIE_BOOL_ATTRS = frozenset( # AKA Morsel._flags + ("secure", "httponly", "partitioned") +) + +# SimpleCookie's pattern for parsing cookies with relaxed validation +# Based on http.cookies pattern but extended to allow more characters in cookie names +# to handle real-world cookies (fixes #2683) +_COOKIE_PATTERN = re.compile( + r""" + \s* # Optional whitespace at start of cookie + (?P # Start of group 'key' + # aiohttp has extended to include [] for compatibility with real-world cookies + [\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=\[\]]+? # Any word of at least one letter + ) # End of group 'key' + ( # Optional group: there may not be a value. + \s*=\s* # Equal Sign + (?P # Start of group 'val' + "(?:[^\\"]|\\.)*" # Any double-quoted string (properly closed) + | # or + "[^";]* # Unmatched opening quote (differs from SimpleCookie - issue #7993) + | # or + # Special case for "expires" attr - RFC 822, RFC 850, RFC 1036, RFC 1123 + (\w{3,6}day|\w{3}),\s # Day of the week or abbreviated day (with comma) + [\w\d\s-]{9,11}\s[\d:]{8}\s # Date and time in specific format + (GMT|[+-]\d{4}) # Timezone: GMT or RFC 2822 offset like -0000, +0100 + # NOTE: RFC 2822 timezone support is an aiohttp extension + # for issue #4493 - SimpleCookie does NOT support this + | # or + # ANSI C asctime() format: "Wed Jun 9 10:18:14 2021" + # NOTE: This is an aiohttp extension for issue #4327 - SimpleCookie does NOT support this format + \w{3}\s+\w{3}\s+[\s\d]\d\s+\d{2}:\d{2}:\d{2}\s+\d{4} + | # or + [\w\d!#%&'~_`><@,:/\$\*\+\-\.\^\|\)\(\?\}\{\=\[\]]* # Any word or empty string + ) # End of group 'val' + )? # End of optional value group + \s* # Any number of spaces. + (\s+|;|$) # Ending either at space, semicolon, or EOS. + """, + re.VERBOSE | re.ASCII, +) + + +def preserve_morsel_with_coded_value(cookie: Morsel[str]) -> Morsel[str]: + """ + Preserve a Morsel's coded_value exactly as received from the server. + + This function ensures that cookie encoding is preserved exactly as sent by + the server, which is critical for compatibility with old servers that have + strict requirements about cookie formats. + + This addresses the issue described in https://github.com/aio-libs/aiohttp/pull/1453 + where Python's SimpleCookie would re-encode cookies, breaking authentication + with certain servers. + + Args: + cookie: A Morsel object from SimpleCookie + + Returns: + A Morsel object with preserved coded_value + + """ + mrsl_val = cast("Morsel[str]", cookie.get(cookie.key, Morsel())) + # We use __setstate__ instead of the public set() API because it allows us to + # bypass validation and set already validated state. This is more stable than + # setting protected attributes directly and unlikely to change since it would + # break pickling. + mrsl_val.__setstate__( # type: ignore[attr-defined] + {"key": cookie.key, "value": cookie.value, "coded_value": cookie.coded_value} + ) + return mrsl_val + + +_unquote_sub = re.compile(r"\\(?:([0-3][0-7][0-7])|(.))").sub + + +def _unquote_replace(m: re.Match[str]) -> str: + """ + Replace function for _unquote_sub regex substitution. + + Handles escaped characters in cookie values: + - Octal sequences are converted to their character representation + - Other escaped characters are unescaped by removing the backslash + """ + if m[1]: + return chr(int(m[1], 8)) + return m[2] + + +def _unquote(value: str) -> str: + """ + Unquote a cookie value. + + Vendored from http.cookies._unquote to ensure compatibility. + + Note: The original implementation checked for None, but we've removed + that check since all callers already ensure the value is not None. + """ + # If there aren't any doublequotes, + # then there can't be any special characters. See RFC 2109. + if len(value) < 2: + return value + if value[0] != '"' or value[-1] != '"': + return value + + # We have to assume that we must decode this string. + # Down to work. + + # Remove the "s + value = value[1:-1] + + # Check for special sequences. Examples: + # \012 --> \n + # \" --> " + # + return _unquote_sub(_unquote_replace, value) + + +def parse_cookie_header(header: str) -> List[Tuple[str, Morsel[str]]]: + """ + Parse a Cookie header according to RFC 6265 Section 5.4. + + Cookie headers contain only name-value pairs separated by semicolons. + There are no attributes in Cookie headers - even names that match + attribute names (like 'path' or 'secure') should be treated as cookies. + + This parser uses the same regex-based approach as parse_set_cookie_headers + to properly handle quoted values that may contain semicolons. + + Args: + header: The Cookie header value to parse + + Returns: + List of (name, Morsel) tuples for compatibility with SimpleCookie.update() + """ + if not header: + return [] + + cookies: List[Tuple[str, Morsel[str]]] = [] + i = 0 + n = len(header) + + while i < n: + # Use the same pattern as parse_set_cookie_headers to find cookies + match = _COOKIE_PATTERN.match(header, i) + if not match: + break + + key = match.group("key") + value = match.group("val") or "" + i = match.end(0) + + # Validate the name + if not key or not _COOKIE_NAME_RE.match(key): + internal_logger.warning("Can not load cookie: Illegal cookie name %r", key) + continue + + # Create new morsel + morsel: Morsel[str] = Morsel() + # Preserve the original value as coded_value (with quotes if present) + # We use __setstate__ instead of the public set() API because it allows us to + # bypass validation and set already validated state. This is more stable than + # setting protected attributes directly and unlikely to change since it would + # break pickling. + morsel.__setstate__( # type: ignore[attr-defined] + {"key": key, "value": _unquote(value), "coded_value": value} + ) + + cookies.append((key, morsel)) + + return cookies + + +def parse_set_cookie_headers(headers: Sequence[str]) -> List[Tuple[str, Morsel[str]]]: + """ + Parse cookie headers using a vendored version of SimpleCookie parsing. + + This implementation is based on SimpleCookie.__parse_string to ensure + compatibility with how SimpleCookie parses cookies, including handling + of malformed cookies with missing semicolons. + + This function is used for both Cookie and Set-Cookie headers in order to be + forgiving. Ideally we would have followed RFC 6265 Section 5.2 (for Cookie + headers) and RFC 6265 Section 4.2.1 (for Set-Cookie headers), but the + real world data makes it impossible since we need to be a bit more forgiving. + + NOTE: This implementation differs from SimpleCookie in handling unmatched quotes. + SimpleCookie will stop parsing when it encounters a cookie value with an unmatched + quote (e.g., 'cookie="value'), causing subsequent cookies to be silently dropped. + This implementation handles unmatched quotes more gracefully to prevent cookie loss. + See https://github.com/aio-libs/aiohttp/issues/7993 + """ + parsed_cookies: List[Tuple[str, Morsel[str]]] = [] + + for header in headers: + if not header: + continue + + # Parse cookie string using SimpleCookie's algorithm + i = 0 + n = len(header) + current_morsel: Optional[Morsel[str]] = None + morsel_seen = False + + while 0 <= i < n: + # Start looking for a cookie + match = _COOKIE_PATTERN.match(header, i) + if not match: + # No more cookies + break + + key, value = match.group("key"), match.group("val") + i = match.end(0) + lower_key = key.lower() + + if key[0] == "$": + if not morsel_seen: + # We ignore attributes which pertain to the cookie + # mechanism as a whole, such as "$Version". + continue + # Process as attribute + if current_morsel is not None: + attr_lower_key = lower_key[1:] + if attr_lower_key in _COOKIE_KNOWN_ATTRS: + current_morsel[attr_lower_key] = value or "" + elif lower_key in _COOKIE_KNOWN_ATTRS: + if not morsel_seen: + # Invalid cookie string - attribute before cookie + break + if lower_key in _COOKIE_BOOL_ATTRS: + # Boolean attribute with any value should be True + if current_morsel is not None: + if lower_key == "partitioned" and sys.version_info < (3, 14): + dict.__setitem__(current_morsel, lower_key, True) + else: + current_morsel[lower_key] = True + elif value is None: + # Invalid cookie string - non-boolean attribute without value + break + elif current_morsel is not None: + # Regular attribute with value + current_morsel[lower_key] = _unquote(value) + elif value is not None: + # This is a cookie name=value pair + # Validate the name + if key in _COOKIE_KNOWN_ATTRS or not _COOKIE_NAME_RE.match(key): + internal_logger.warning( + "Can not load cookies: Illegal cookie name %r", key + ) + current_morsel = None + else: + # Create new morsel + current_morsel = Morsel() + # Preserve the original value as coded_value (with quotes if present) + # We use __setstate__ instead of the public set() API because it allows us to + # bypass validation and set already validated state. This is more stable than + # setting protected attributes directly and unlikely to change since it would + # break pickling. + current_morsel.__setstate__( # type: ignore[attr-defined] + {"key": key, "value": _unquote(value), "coded_value": value} + ) + parsed_cookies.append((key, current_morsel)) + morsel_seen = True + else: + # Invalid cookie string - no value for non-attribute + break + + return parsed_cookies diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_cparser.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_cparser.pxd new file mode 100644 index 0000000000000000000000000000000000000000..1b3be6d4efb682bca9397da34f8e727b381bc84f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_cparser.pxd @@ -0,0 +1,158 @@ +from libc.stdint cimport int32_t, uint8_t, uint16_t, uint64_t + + +cdef extern from "llhttp.h": + + struct llhttp__internal_s: + int32_t _index + void* _span_pos0 + void* _span_cb0 + int32_t error + const char* reason + const char* error_pos + void* data + void* _current + uint64_t content_length + uint8_t type + uint8_t method + uint8_t http_major + uint8_t http_minor + uint8_t header_state + uint8_t lenient_flags + uint8_t upgrade + uint8_t finish + uint16_t flags + uint16_t status_code + void* settings + + ctypedef llhttp__internal_s llhttp__internal_t + ctypedef llhttp__internal_t llhttp_t + + ctypedef int (*llhttp_data_cb)(llhttp_t*, const char *at, size_t length) except -1 + ctypedef int (*llhttp_cb)(llhttp_t*) except -1 + + struct llhttp_settings_s: + llhttp_cb on_message_begin + llhttp_data_cb on_url + llhttp_data_cb on_status + llhttp_data_cb on_header_field + llhttp_data_cb on_header_value + llhttp_cb on_headers_complete + llhttp_data_cb on_body + llhttp_cb on_message_complete + llhttp_cb on_chunk_header + llhttp_cb on_chunk_complete + + llhttp_cb on_url_complete + llhttp_cb on_status_complete + llhttp_cb on_header_field_complete + llhttp_cb on_header_value_complete + + ctypedef llhttp_settings_s llhttp_settings_t + + enum llhttp_errno: + HPE_OK, + HPE_INTERNAL, + HPE_STRICT, + HPE_LF_EXPECTED, + HPE_UNEXPECTED_CONTENT_LENGTH, + HPE_CLOSED_CONNECTION, + HPE_INVALID_METHOD, + HPE_INVALID_URL, + HPE_INVALID_CONSTANT, + HPE_INVALID_VERSION, + HPE_INVALID_HEADER_TOKEN, + HPE_INVALID_CONTENT_LENGTH, + HPE_INVALID_CHUNK_SIZE, + HPE_INVALID_STATUS, + HPE_INVALID_EOF_STATE, + HPE_INVALID_TRANSFER_ENCODING, + HPE_CB_MESSAGE_BEGIN, + HPE_CB_HEADERS_COMPLETE, + HPE_CB_MESSAGE_COMPLETE, + HPE_CB_CHUNK_HEADER, + HPE_CB_CHUNK_COMPLETE, + HPE_PAUSED, + HPE_PAUSED_UPGRADE, + HPE_USER + + ctypedef llhttp_errno llhttp_errno_t + + enum llhttp_flags: + F_CHUNKED, + F_CONTENT_LENGTH + + enum llhttp_type: + HTTP_REQUEST, + HTTP_RESPONSE, + HTTP_BOTH + + enum llhttp_method: + HTTP_DELETE, + HTTP_GET, + HTTP_HEAD, + HTTP_POST, + HTTP_PUT, + HTTP_CONNECT, + HTTP_OPTIONS, + HTTP_TRACE, + HTTP_COPY, + HTTP_LOCK, + HTTP_MKCOL, + HTTP_MOVE, + HTTP_PROPFIND, + HTTP_PROPPATCH, + HTTP_SEARCH, + HTTP_UNLOCK, + HTTP_BIND, + HTTP_REBIND, + HTTP_UNBIND, + HTTP_ACL, + HTTP_REPORT, + HTTP_MKACTIVITY, + HTTP_CHECKOUT, + HTTP_MERGE, + HTTP_MSEARCH, + HTTP_NOTIFY, + HTTP_SUBSCRIBE, + HTTP_UNSUBSCRIBE, + HTTP_PATCH, + HTTP_PURGE, + HTTP_MKCALENDAR, + HTTP_LINK, + HTTP_UNLINK, + HTTP_SOURCE, + HTTP_PRI, + HTTP_DESCRIBE, + HTTP_ANNOUNCE, + HTTP_SETUP, + HTTP_PLAY, + HTTP_PAUSE, + HTTP_TEARDOWN, + HTTP_GET_PARAMETER, + HTTP_SET_PARAMETER, + HTTP_REDIRECT, + HTTP_RECORD, + HTTP_FLUSH + + ctypedef llhttp_method llhttp_method_t; + + void llhttp_settings_init(llhttp_settings_t* settings) + void llhttp_init(llhttp_t* parser, llhttp_type type, + const llhttp_settings_t* settings) + + llhttp_errno_t llhttp_execute(llhttp_t* parser, const char* data, size_t len) + + int llhttp_should_keep_alive(const llhttp_t* parser) + + void llhttp_resume_after_upgrade(llhttp_t* parser) + + llhttp_errno_t llhttp_get_errno(const llhttp_t* parser) + const char* llhttp_get_error_reason(const llhttp_t* parser) + const char* llhttp_get_error_pos(const llhttp_t* parser) + + const char* llhttp_method_name(llhttp_method_t method) + + void llhttp_set_lenient_headers(llhttp_t* parser, int enabled) + void llhttp_set_lenient_optional_cr_before_lf(llhttp_t* parser, int enabled) + void llhttp_set_lenient_spaces_after_chunk_size(llhttp_t* parser, int enabled) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_find_header.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_find_header.pxd new file mode 100644 index 0000000000000000000000000000000000000000..37a6c37268ee30b182fd77d109688d35d5577c7f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_find_header.pxd @@ -0,0 +1,2 @@ +cdef extern from "_find_header.h": + int find_header(char *, int) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_headers.pxi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_headers.pxi new file mode 100644 index 0000000000000000000000000000000000000000..3744721d4786a6c79b90aa349c8d02fa66204ecc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_headers.pxi @@ -0,0 +1,83 @@ +# The file is autogenerated from aiohttp/hdrs.py +# Run ./tools/gen.py to update it after the origin changing. + +from . import hdrs +cdef tuple headers = ( + hdrs.ACCEPT, + hdrs.ACCEPT_CHARSET, + hdrs.ACCEPT_ENCODING, + hdrs.ACCEPT_LANGUAGE, + hdrs.ACCEPT_RANGES, + hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, + hdrs.ACCESS_CONTROL_ALLOW_HEADERS, + hdrs.ACCESS_CONTROL_ALLOW_METHODS, + hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, + hdrs.ACCESS_CONTROL_EXPOSE_HEADERS, + hdrs.ACCESS_CONTROL_MAX_AGE, + hdrs.ACCESS_CONTROL_REQUEST_HEADERS, + hdrs.ACCESS_CONTROL_REQUEST_METHOD, + hdrs.AGE, + hdrs.ALLOW, + hdrs.AUTHORIZATION, + hdrs.CACHE_CONTROL, + hdrs.CONNECTION, + hdrs.CONTENT_DISPOSITION, + hdrs.CONTENT_ENCODING, + hdrs.CONTENT_LANGUAGE, + hdrs.CONTENT_LENGTH, + hdrs.CONTENT_LOCATION, + hdrs.CONTENT_MD5, + hdrs.CONTENT_RANGE, + hdrs.CONTENT_TRANSFER_ENCODING, + hdrs.CONTENT_TYPE, + hdrs.COOKIE, + hdrs.DATE, + hdrs.DESTINATION, + hdrs.DIGEST, + hdrs.ETAG, + hdrs.EXPECT, + hdrs.EXPIRES, + hdrs.FORWARDED, + hdrs.FROM, + hdrs.HOST, + hdrs.IF_MATCH, + hdrs.IF_MODIFIED_SINCE, + hdrs.IF_NONE_MATCH, + hdrs.IF_RANGE, + hdrs.IF_UNMODIFIED_SINCE, + hdrs.KEEP_ALIVE, + hdrs.LAST_EVENT_ID, + hdrs.LAST_MODIFIED, + hdrs.LINK, + hdrs.LOCATION, + hdrs.MAX_FORWARDS, + hdrs.ORIGIN, + hdrs.PRAGMA, + hdrs.PROXY_AUTHENTICATE, + hdrs.PROXY_AUTHORIZATION, + hdrs.RANGE, + hdrs.REFERER, + hdrs.RETRY_AFTER, + hdrs.SEC_WEBSOCKET_ACCEPT, + hdrs.SEC_WEBSOCKET_EXTENSIONS, + hdrs.SEC_WEBSOCKET_KEY, + hdrs.SEC_WEBSOCKET_KEY1, + hdrs.SEC_WEBSOCKET_PROTOCOL, + hdrs.SEC_WEBSOCKET_VERSION, + hdrs.SERVER, + hdrs.SET_COOKIE, + hdrs.TE, + hdrs.TRAILER, + hdrs.TRANSFER_ENCODING, + hdrs.URI, + hdrs.UPGRADE, + hdrs.USER_AGENT, + hdrs.VARY, + hdrs.VIA, + hdrs.WWW_AUTHENTICATE, + hdrs.WANT_DIGEST, + hdrs.WARNING, + hdrs.X_FORWARDED_FOR, + hdrs.X_FORWARDED_HOST, + hdrs.X_FORWARDED_PROTO, +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..65edff13ac8e10dc2844f6d7977b261dda37e68f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_parser.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79a943bdcf6a242930cc021882d28c2e48a3e3543193bf095dd6625289134ef8 +size 2878000 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_parser.pyx b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_parser.pyx new file mode 100644 index 0000000000000000000000000000000000000000..16893f00e7435f4125d68446a6187791c4604549 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_parser.pyx @@ -0,0 +1,837 @@ +#cython: language_level=3 +# +# Based on https://github.com/MagicStack/httptools +# + +from cpython cimport ( + Py_buffer, + PyBUF_SIMPLE, + PyBuffer_Release, + PyBytes_AsString, + PyBytes_AsStringAndSize, + PyObject_GetBuffer, +) +from cpython.mem cimport PyMem_Free, PyMem_Malloc +from libc.limits cimport ULLONG_MAX +from libc.string cimport memcpy + +from multidict import CIMultiDict as _CIMultiDict, CIMultiDictProxy as _CIMultiDictProxy +from yarl import URL as _URL + +from aiohttp import hdrs +from aiohttp.helpers import DEBUG, set_exception + +from .http_exceptions import ( + BadHttpMessage, + BadHttpMethod, + BadStatusLine, + ContentLengthError, + InvalidHeader, + InvalidURLError, + LineTooLong, + PayloadEncodingError, + TransferEncodingError, +) +from .http_parser import DeflateBuffer as _DeflateBuffer +from .http_writer import ( + HttpVersion as _HttpVersion, + HttpVersion10 as _HttpVersion10, + HttpVersion11 as _HttpVersion11, +) +from .streams import EMPTY_PAYLOAD as _EMPTY_PAYLOAD, StreamReader as _StreamReader + +cimport cython + +from aiohttp cimport _cparser as cparser + +include "_headers.pxi" + +from aiohttp cimport _find_header + +ALLOWED_UPGRADES = frozenset({"websocket"}) +DEF DEFAULT_FREELIST_SIZE = 250 + +cdef extern from "Python.h": + int PyByteArray_Resize(object, Py_ssize_t) except -1 + Py_ssize_t PyByteArray_Size(object) except -1 + char* PyByteArray_AsString(object) + +__all__ = ('HttpRequestParser', 'HttpResponseParser', + 'RawRequestMessage', 'RawResponseMessage') + +cdef object URL = _URL +cdef object URL_build = URL.build +cdef object CIMultiDict = _CIMultiDict +cdef object CIMultiDictProxy = _CIMultiDictProxy +cdef object HttpVersion = _HttpVersion +cdef object HttpVersion10 = _HttpVersion10 +cdef object HttpVersion11 = _HttpVersion11 +cdef object SEC_WEBSOCKET_KEY1 = hdrs.SEC_WEBSOCKET_KEY1 +cdef object CONTENT_ENCODING = hdrs.CONTENT_ENCODING +cdef object EMPTY_PAYLOAD = _EMPTY_PAYLOAD +cdef object StreamReader = _StreamReader +cdef object DeflateBuffer = _DeflateBuffer +cdef bytes EMPTY_BYTES = b"" + +cdef inline object extend(object buf, const char* at, size_t length): + cdef Py_ssize_t s + cdef char* ptr + s = PyByteArray_Size(buf) + PyByteArray_Resize(buf, s + length) + ptr = PyByteArray_AsString(buf) + memcpy(ptr + s, at, length) + + +DEF METHODS_COUNT = 46; + +cdef list _http_method = [] + +for i in range(METHODS_COUNT): + _http_method.append( + cparser.llhttp_method_name( i).decode('ascii')) + + +cdef inline str http_method_str(int i): + if i < METHODS_COUNT: + return _http_method[i] + else: + return "" + +cdef inline object find_header(bytes raw_header): + cdef Py_ssize_t size + cdef char *buf + cdef int idx + PyBytes_AsStringAndSize(raw_header, &buf, &size) + idx = _find_header.find_header(buf, size) + if idx == -1: + return raw_header.decode('utf-8', 'surrogateescape') + return headers[idx] + + +@cython.freelist(DEFAULT_FREELIST_SIZE) +cdef class RawRequestMessage: + cdef readonly str method + cdef readonly str path + cdef readonly object version # HttpVersion + cdef readonly object headers # CIMultiDict + cdef readonly object raw_headers # tuple + cdef readonly object should_close + cdef readonly object compression + cdef readonly object upgrade + cdef readonly object chunked + cdef readonly object url # yarl.URL + + def __init__(self, method, path, version, headers, raw_headers, + should_close, compression, upgrade, chunked, url): + self.method = method + self.path = path + self.version = version + self.headers = headers + self.raw_headers = raw_headers + self.should_close = should_close + self.compression = compression + self.upgrade = upgrade + self.chunked = chunked + self.url = url + + def __repr__(self): + info = [] + info.append(("method", self.method)) + info.append(("path", self.path)) + info.append(("version", self.version)) + info.append(("headers", self.headers)) + info.append(("raw_headers", self.raw_headers)) + info.append(("should_close", self.should_close)) + info.append(("compression", self.compression)) + info.append(("upgrade", self.upgrade)) + info.append(("chunked", self.chunked)) + info.append(("url", self.url)) + sinfo = ', '.join(name + '=' + repr(val) for name, val in info) + return '' + + def _replace(self, **dct): + cdef RawRequestMessage ret + ret = _new_request_message(self.method, + self.path, + self.version, + self.headers, + self.raw_headers, + self.should_close, + self.compression, + self.upgrade, + self.chunked, + self.url) + if "method" in dct: + ret.method = dct["method"] + if "path" in dct: + ret.path = dct["path"] + if "version" in dct: + ret.version = dct["version"] + if "headers" in dct: + ret.headers = dct["headers"] + if "raw_headers" in dct: + ret.raw_headers = dct["raw_headers"] + if "should_close" in dct: + ret.should_close = dct["should_close"] + if "compression" in dct: + ret.compression = dct["compression"] + if "upgrade" in dct: + ret.upgrade = dct["upgrade"] + if "chunked" in dct: + ret.chunked = dct["chunked"] + if "url" in dct: + ret.url = dct["url"] + return ret + +cdef _new_request_message(str method, + str path, + object version, + object headers, + object raw_headers, + bint should_close, + object compression, + bint upgrade, + bint chunked, + object url): + cdef RawRequestMessage ret + ret = RawRequestMessage.__new__(RawRequestMessage) + ret.method = method + ret.path = path + ret.version = version + ret.headers = headers + ret.raw_headers = raw_headers + ret.should_close = should_close + ret.compression = compression + ret.upgrade = upgrade + ret.chunked = chunked + ret.url = url + return ret + + +@cython.freelist(DEFAULT_FREELIST_SIZE) +cdef class RawResponseMessage: + cdef readonly object version # HttpVersion + cdef readonly int code + cdef readonly str reason + cdef readonly object headers # CIMultiDict + cdef readonly object raw_headers # tuple + cdef readonly object should_close + cdef readonly object compression + cdef readonly object upgrade + cdef readonly object chunked + + def __init__(self, version, code, reason, headers, raw_headers, + should_close, compression, upgrade, chunked): + self.version = version + self.code = code + self.reason = reason + self.headers = headers + self.raw_headers = raw_headers + self.should_close = should_close + self.compression = compression + self.upgrade = upgrade + self.chunked = chunked + + def __repr__(self): + info = [] + info.append(("version", self.version)) + info.append(("code", self.code)) + info.append(("reason", self.reason)) + info.append(("headers", self.headers)) + info.append(("raw_headers", self.raw_headers)) + info.append(("should_close", self.should_close)) + info.append(("compression", self.compression)) + info.append(("upgrade", self.upgrade)) + info.append(("chunked", self.chunked)) + sinfo = ', '.join(name + '=' + repr(val) for name, val in info) + return '' + + +cdef _new_response_message(object version, + int code, + str reason, + object headers, + object raw_headers, + bint should_close, + object compression, + bint upgrade, + bint chunked): + cdef RawResponseMessage ret + ret = RawResponseMessage.__new__(RawResponseMessage) + ret.version = version + ret.code = code + ret.reason = reason + ret.headers = headers + ret.raw_headers = raw_headers + ret.should_close = should_close + ret.compression = compression + ret.upgrade = upgrade + ret.chunked = chunked + return ret + + +@cython.internal +cdef class HttpParser: + + cdef: + cparser.llhttp_t* _cparser + cparser.llhttp_settings_t* _csettings + + bytes _raw_name + object _name + bytes _raw_value + bint _has_value + + object _protocol + object _loop + object _timer + + size_t _max_line_size + size_t _max_field_size + size_t _max_headers + bint _response_with_body + bint _read_until_eof + + bint _started + object _url + bytearray _buf + str _path + str _reason + list _headers + list _raw_headers + bint _upgraded + list _messages + object _payload + bint _payload_error + object _payload_exception + object _last_error + bint _auto_decompress + int _limit + + str _content_encoding + + Py_buffer py_buf + + def __cinit__(self): + self._cparser = \ + PyMem_Malloc(sizeof(cparser.llhttp_t)) + if self._cparser is NULL: + raise MemoryError() + + self._csettings = \ + PyMem_Malloc(sizeof(cparser.llhttp_settings_t)) + if self._csettings is NULL: + raise MemoryError() + + def __dealloc__(self): + PyMem_Free(self._cparser) + PyMem_Free(self._csettings) + + cdef _init( + self, cparser.llhttp_type mode, + object protocol, object loop, int limit, + object timer=None, + size_t max_line_size=8190, size_t max_headers=32768, + size_t max_field_size=8190, payload_exception=None, + bint response_with_body=True, bint read_until_eof=False, + bint auto_decompress=True, + ): + cparser.llhttp_settings_init(self._csettings) + cparser.llhttp_init(self._cparser, mode, self._csettings) + self._cparser.data = self + self._cparser.content_length = 0 + + self._protocol = protocol + self._loop = loop + self._timer = timer + + self._buf = bytearray() + self._payload = None + self._payload_error = 0 + self._payload_exception = payload_exception + self._messages = [] + + self._raw_name = EMPTY_BYTES + self._raw_value = EMPTY_BYTES + self._has_value = False + + self._max_line_size = max_line_size + self._max_headers = max_headers + self._max_field_size = max_field_size + self._response_with_body = response_with_body + self._read_until_eof = read_until_eof + self._upgraded = False + self._auto_decompress = auto_decompress + self._content_encoding = None + + self._csettings.on_url = cb_on_url + self._csettings.on_status = cb_on_status + self._csettings.on_header_field = cb_on_header_field + self._csettings.on_header_value = cb_on_header_value + self._csettings.on_headers_complete = cb_on_headers_complete + self._csettings.on_body = cb_on_body + self._csettings.on_message_begin = cb_on_message_begin + self._csettings.on_message_complete = cb_on_message_complete + self._csettings.on_chunk_header = cb_on_chunk_header + self._csettings.on_chunk_complete = cb_on_chunk_complete + + self._last_error = None + self._limit = limit + + cdef _process_header(self): + cdef str value + if self._raw_name is not EMPTY_BYTES: + name = find_header(self._raw_name) + value = self._raw_value.decode('utf-8', 'surrogateescape') + + self._headers.append((name, value)) + + if name is CONTENT_ENCODING: + self._content_encoding = value + + self._has_value = False + self._raw_headers.append((self._raw_name, self._raw_value)) + self._raw_name = EMPTY_BYTES + self._raw_value = EMPTY_BYTES + + cdef _on_header_field(self, char* at, size_t length): + if self._has_value: + self._process_header() + + if self._raw_name is EMPTY_BYTES: + self._raw_name = at[:length] + else: + self._raw_name += at[:length] + + cdef _on_header_value(self, char* at, size_t length): + if self._raw_value is EMPTY_BYTES: + self._raw_value = at[:length] + else: + self._raw_value += at[:length] + self._has_value = True + + cdef _on_headers_complete(self): + self._process_header() + + should_close = not cparser.llhttp_should_keep_alive(self._cparser) + upgrade = self._cparser.upgrade + chunked = self._cparser.flags & cparser.F_CHUNKED + + raw_headers = tuple(self._raw_headers) + headers = CIMultiDictProxy(CIMultiDict(self._headers)) + + if self._cparser.type == cparser.HTTP_REQUEST: + allowed = upgrade and headers.get("upgrade", "").lower() in ALLOWED_UPGRADES + if allowed or self._cparser.method == cparser.HTTP_CONNECT: + self._upgraded = True + else: + if upgrade and self._cparser.status_code == 101: + self._upgraded = True + + # do not support old websocket spec + if SEC_WEBSOCKET_KEY1 in headers: + raise InvalidHeader(SEC_WEBSOCKET_KEY1) + + encoding = None + enc = self._content_encoding + if enc is not None: + self._content_encoding = None + enc = enc.lower() + if enc in ('gzip', 'deflate', 'br'): + encoding = enc + + if self._cparser.type == cparser.HTTP_REQUEST: + method = http_method_str(self._cparser.method) + msg = _new_request_message( + method, self._path, + self.http_version(), headers, raw_headers, + should_close, encoding, upgrade, chunked, self._url) + else: + msg = _new_response_message( + self.http_version(), self._cparser.status_code, self._reason, + headers, raw_headers, should_close, encoding, + upgrade, chunked) + + if ( + ULLONG_MAX > self._cparser.content_length > 0 or chunked or + self._cparser.method == cparser.HTTP_CONNECT or + (self._cparser.status_code >= 199 and + self._cparser.content_length == 0 and + self._read_until_eof) + ): + payload = StreamReader( + self._protocol, timer=self._timer, loop=self._loop, + limit=self._limit) + else: + payload = EMPTY_PAYLOAD + + self._payload = payload + if encoding is not None and self._auto_decompress: + self._payload = DeflateBuffer(payload, encoding) + + if not self._response_with_body: + payload = EMPTY_PAYLOAD + + self._messages.append((msg, payload)) + + cdef _on_message_complete(self): + self._payload.feed_eof() + self._payload = None + + cdef _on_chunk_header(self): + self._payload.begin_http_chunk_receiving() + + cdef _on_chunk_complete(self): + self._payload.end_http_chunk_receiving() + + cdef object _on_status_complete(self): + pass + + cdef inline http_version(self): + cdef cparser.llhttp_t* parser = self._cparser + + if parser.http_major == 1: + if parser.http_minor == 0: + return HttpVersion10 + elif parser.http_minor == 1: + return HttpVersion11 + + return HttpVersion(parser.http_major, parser.http_minor) + + ### Public API ### + + def feed_eof(self): + cdef bytes desc + + if self._payload is not None: + if self._cparser.flags & cparser.F_CHUNKED: + raise TransferEncodingError( + "Not enough data to satisfy transfer length header.") + elif self._cparser.flags & cparser.F_CONTENT_LENGTH: + raise ContentLengthError( + "Not enough data to satisfy content length header.") + elif cparser.llhttp_get_errno(self._cparser) != cparser.HPE_OK: + desc = cparser.llhttp_get_error_reason(self._cparser) + raise PayloadEncodingError(desc.decode('latin-1')) + else: + self._payload.feed_eof() + elif self._started: + self._on_headers_complete() + if self._messages: + return self._messages[-1][0] + + def feed_data(self, data): + cdef: + size_t data_len + size_t nb + cdef cparser.llhttp_errno_t errno + + PyObject_GetBuffer(data, &self.py_buf, PyBUF_SIMPLE) + data_len = self.py_buf.len + + errno = cparser.llhttp_execute( + self._cparser, + self.py_buf.buf, + data_len) + + if errno is cparser.HPE_PAUSED_UPGRADE: + cparser.llhttp_resume_after_upgrade(self._cparser) + + nb = cparser.llhttp_get_error_pos(self._cparser) - self.py_buf.buf + + PyBuffer_Release(&self.py_buf) + + if errno not in (cparser.HPE_OK, cparser.HPE_PAUSED_UPGRADE): + if self._payload_error == 0: + if self._last_error is not None: + ex = self._last_error + self._last_error = None + else: + after = cparser.llhttp_get_error_pos(self._cparser) + before = data[:after - self.py_buf.buf] + after_b = after.split(b"\r\n", 1)[0] + before = before.rsplit(b"\r\n", 1)[-1] + data = before + after_b + pointer = " " * (len(repr(before))-1) + "^" + ex = parser_error_from_errno(self._cparser, data, pointer) + self._payload = None + raise ex + + if self._messages: + messages = self._messages + self._messages = [] + else: + messages = () + + if self._upgraded: + return messages, True, data[nb:] + else: + return messages, False, b"" + + def set_upgraded(self, val): + self._upgraded = val + + +cdef class HttpRequestParser(HttpParser): + + def __init__( + self, protocol, loop, int limit, timer=None, + size_t max_line_size=8190, size_t max_headers=32768, + size_t max_field_size=8190, payload_exception=None, + bint response_with_body=True, bint read_until_eof=False, + bint auto_decompress=True, + ): + self._init(cparser.HTTP_REQUEST, protocol, loop, limit, timer, + max_line_size, max_headers, max_field_size, + payload_exception, response_with_body, read_until_eof, + auto_decompress) + + cdef object _on_status_complete(self): + cdef int idx1, idx2 + if not self._buf: + return + self._path = self._buf.decode('utf-8', 'surrogateescape') + try: + idx3 = len(self._path) + if self._cparser.method == cparser.HTTP_CONNECT: + # authority-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3 + self._url = URL.build(authority=self._path, encoded=True) + elif idx3 > 1 and self._path[0] == '/': + # origin-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1 + idx1 = self._path.find("?") + if idx1 == -1: + query = "" + idx2 = self._path.find("#") + if idx2 == -1: + path = self._path + fragment = "" + else: + path = self._path[0: idx2] + fragment = self._path[idx2+1:] + + else: + path = self._path[0:idx1] + idx1 += 1 + idx2 = self._path.find("#", idx1+1) + if idx2 == -1: + query = self._path[idx1:] + fragment = "" + else: + query = self._path[idx1: idx2] + fragment = self._path[idx2+1:] + + self._url = URL.build( + path=path, + query_string=query, + fragment=fragment, + encoded=True, + ) + else: + # absolute-form for proxy maybe, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2 + self._url = URL(self._path, encoded=True) + finally: + PyByteArray_Resize(self._buf, 0) + + +cdef class HttpResponseParser(HttpParser): + + def __init__( + self, protocol, loop, int limit, timer=None, + size_t max_line_size=8190, size_t max_headers=32768, + size_t max_field_size=8190, payload_exception=None, + bint response_with_body=True, bint read_until_eof=False, + bint auto_decompress=True + ): + self._init(cparser.HTTP_RESPONSE, protocol, loop, limit, timer, + max_line_size, max_headers, max_field_size, + payload_exception, response_with_body, read_until_eof, + auto_decompress) + # Use strict parsing on dev mode, so users are warned about broken servers. + if not DEBUG: + cparser.llhttp_set_lenient_headers(self._cparser, 1) + cparser.llhttp_set_lenient_optional_cr_before_lf(self._cparser, 1) + cparser.llhttp_set_lenient_spaces_after_chunk_size(self._cparser, 1) + + cdef object _on_status_complete(self): + if self._buf: + self._reason = self._buf.decode('utf-8', 'surrogateescape') + PyByteArray_Resize(self._buf, 0) + else: + self._reason = self._reason or '' + +cdef int cb_on_message_begin(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + + pyparser._started = True + pyparser._headers = [] + pyparser._raw_headers = [] + PyByteArray_Resize(pyparser._buf, 0) + pyparser._path = None + pyparser._reason = None + return 0 + + +cdef int cb_on_url(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + try: + if length > pyparser._max_line_size: + raise LineTooLong( + 'Status line is too long', pyparser._max_line_size, length) + extend(pyparser._buf, at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_status(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef str reason + try: + if length > pyparser._max_line_size: + raise LineTooLong( + 'Status line is too long', pyparser._max_line_size, length) + extend(pyparser._buf, at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_header_field(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef Py_ssize_t size + try: + pyparser._on_status_complete() + size = len(pyparser._raw_name) + length + if size > pyparser._max_field_size: + raise LineTooLong( + 'Header name is too long', pyparser._max_field_size, size) + pyparser._on_header_field(at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_header_value(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef Py_ssize_t size + try: + size = len(pyparser._raw_value) + length + if size > pyparser._max_field_size: + raise LineTooLong( + 'Header value is too long', pyparser._max_field_size, size) + pyparser._on_header_value(at, length) + except BaseException as ex: + pyparser._last_error = ex + return -1 + else: + return 0 + + +cdef int cb_on_headers_complete(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._on_status_complete() + pyparser._on_headers_complete() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + if pyparser._upgraded or pyparser._cparser.method == cparser.HTTP_CONNECT: + return 2 + else: + return 0 + + +cdef int cb_on_body(cparser.llhttp_t* parser, + const char *at, size_t length) except -1: + cdef HttpParser pyparser = parser.data + cdef bytes body = at[:length] + try: + pyparser._payload.feed_data(body, length) + except BaseException as underlying_exc: + reraised_exc = underlying_exc + if pyparser._payload_exception is not None: + reraised_exc = pyparser._payload_exception(str(underlying_exc)) + + set_exception(pyparser._payload, reraised_exc, underlying_exc) + + pyparser._payload_error = 1 + return -1 + else: + return 0 + + +cdef int cb_on_message_complete(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._started = False + pyparser._on_message_complete() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + return 0 + + +cdef int cb_on_chunk_header(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._on_chunk_header() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + return 0 + + +cdef int cb_on_chunk_complete(cparser.llhttp_t* parser) except -1: + cdef HttpParser pyparser = parser.data + try: + pyparser._on_chunk_complete() + except BaseException as exc: + pyparser._last_error = exc + return -1 + else: + return 0 + + +cdef parser_error_from_errno(cparser.llhttp_t* parser, data, pointer): + cdef cparser.llhttp_errno_t errno = cparser.llhttp_get_errno(parser) + cdef bytes desc = cparser.llhttp_get_error_reason(parser) + + err_msg = "{}:\n\n {!r}\n {}".format(desc.decode("latin-1"), data, pointer) + + if errno in {cparser.HPE_CB_MESSAGE_BEGIN, + cparser.HPE_CB_HEADERS_COMPLETE, + cparser.HPE_CB_MESSAGE_COMPLETE, + cparser.HPE_CB_CHUNK_HEADER, + cparser.HPE_CB_CHUNK_COMPLETE, + cparser.HPE_INVALID_CONSTANT, + cparser.HPE_INVALID_HEADER_TOKEN, + cparser.HPE_INVALID_CONTENT_LENGTH, + cparser.HPE_INVALID_CHUNK_SIZE, + cparser.HPE_INVALID_EOF_STATE, + cparser.HPE_INVALID_TRANSFER_ENCODING}: + return BadHttpMessage(err_msg) + elif errno == cparser.HPE_INVALID_METHOD: + return BadHttpMethod(error=err_msg) + elif errno in {cparser.HPE_INVALID_STATUS, + cparser.HPE_INVALID_VERSION}: + return BadStatusLine(error=err_msg) + elif errno == cparser.HPE_INVALID_URL: + return InvalidURLError(err_msg) + + return BadHttpMessage(err_msg) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..59f64c524abb18f590988ebba0d188cb545ffc66 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_writer.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c610b11f2842e80563be0bd54a5ee9d09ea48b5113b546f9462f9f6b5723adf +size 511688 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_writer.pyx b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_writer.pyx new file mode 100644 index 0000000000000000000000000000000000000000..4a3ae1f9e682f7632e0234f2bf7e9a71823caca4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_http_writer.pyx @@ -0,0 +1,160 @@ +from cpython.bytes cimport PyBytes_FromStringAndSize +from cpython.exc cimport PyErr_NoMemory +from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc +from cpython.object cimport PyObject_Str +from libc.stdint cimport uint8_t, uint64_t +from libc.string cimport memcpy + +from multidict import istr + +DEF BUF_SIZE = 16 * 1024 # 16KiB +cdef char BUFFER[BUF_SIZE] + +cdef object _istr = istr + + +# ----------------- writer --------------------------- + +cdef struct Writer: + char *buf + Py_ssize_t size + Py_ssize_t pos + + +cdef inline void _init_writer(Writer* writer): + writer.buf = &BUFFER[0] + writer.size = BUF_SIZE + writer.pos = 0 + + +cdef inline void _release_writer(Writer* writer): + if writer.buf != BUFFER: + PyMem_Free(writer.buf) + + +cdef inline int _write_byte(Writer* writer, uint8_t ch): + cdef char * buf + cdef Py_ssize_t size + + if writer.pos == writer.size: + # reallocate + size = writer.size + BUF_SIZE + if writer.buf == BUFFER: + buf = PyMem_Malloc(size) + if buf == NULL: + PyErr_NoMemory() + return -1 + memcpy(buf, writer.buf, writer.size) + else: + buf = PyMem_Realloc(writer.buf, size) + if buf == NULL: + PyErr_NoMemory() + return -1 + writer.buf = buf + writer.size = size + writer.buf[writer.pos] = ch + writer.pos += 1 + return 0 + + +cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): + cdef uint64_t utf = symbol + + if utf < 0x80: + return _write_byte(writer, utf) + elif utf < 0x800: + if _write_byte(writer, (0xc0 | (utf >> 6))) < 0: + return -1 + return _write_byte(writer, (0x80 | (utf & 0x3f))) + elif 0xD800 <= utf <= 0xDFFF: + # surogate pair, ignored + return 0 + elif utf < 0x10000: + if _write_byte(writer, (0xe0 | (utf >> 12))) < 0: + return -1 + if _write_byte(writer, (0x80 | ((utf >> 6) & 0x3f))) < 0: + return -1 + return _write_byte(writer, (0x80 | (utf & 0x3f))) + elif utf > 0x10FFFF: + # symbol is too large + return 0 + else: + if _write_byte(writer, (0xf0 | (utf >> 18))) < 0: + return -1 + if _write_byte(writer, + (0x80 | ((utf >> 12) & 0x3f))) < 0: + return -1 + if _write_byte(writer, + (0x80 | ((utf >> 6) & 0x3f))) < 0: + return -1 + return _write_byte(writer, (0x80 | (utf & 0x3f))) + + +cdef inline int _write_str(Writer* writer, str s): + cdef Py_UCS4 ch + for ch in s: + if _write_utf8(writer, ch) < 0: + return -1 + + +cdef inline int _write_str_raise_on_nlcr(Writer* writer, object s): + cdef Py_UCS4 ch + cdef str out_str + if type(s) is str: + out_str = s + elif type(s) is _istr: + out_str = PyObject_Str(s) + elif not isinstance(s, str): + raise TypeError("Cannot serialize non-str key {!r}".format(s)) + else: + out_str = str(s) + + for ch in out_str: + if ch == 0x0D or ch == 0x0A: + raise ValueError( + "Newline or carriage return detected in headers. " + "Potential header injection attack." + ) + if _write_utf8(writer, ch) < 0: + return -1 + + +# --------------- _serialize_headers ---------------------- + +def _serialize_headers(str status_line, headers): + cdef Writer writer + cdef object key + cdef object val + + _init_writer(&writer) + + try: + if _write_str(&writer, status_line) < 0: + raise + if _write_byte(&writer, b'\r') < 0: + raise + if _write_byte(&writer, b'\n') < 0: + raise + + for key, val in headers.items(): + if _write_str_raise_on_nlcr(&writer, key) < 0: + raise + if _write_byte(&writer, b':') < 0: + raise + if _write_byte(&writer, b' ') < 0: + raise + if _write_str_raise_on_nlcr(&writer, val) < 0: + raise + if _write_byte(&writer, b'\r') < 0: + raise + if _write_byte(&writer, b'\n') < 0: + raise + + if _write_byte(&writer, b'\r') < 0: + raise + if _write_byte(&writer, b'\n') < 0: + raise + + return PyBytes_FromStringAndSize(writer.buf, writer.pos) + finally: + _release_writer(&writer) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9a79e8d37ba504e104813cbf31b6c64fab8faf08 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c848d4fcfb57710a61f15f768c8d8b2b01ab64e422e726d8ef22fa4beec51c0 +size 258728 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.pxd new file mode 100644 index 0000000000000000000000000000000000000000..90983de9ac7e59dfceb639c1e7b656abd5fbb305 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.pxd @@ -0,0 +1,3 @@ +"""Cython declarations for websocket masking.""" + +cpdef void _websocket_mask_cython(bytes mask, bytearray data) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.pyx b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.pyx new file mode 100644 index 0000000000000000000000000000000000000000..2d956c8899644d4c6bce042b928be1f23e51293a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/mask.pyx @@ -0,0 +1,48 @@ +from cpython cimport PyBytes_AsString + + +#from cpython cimport PyByteArray_AsString # cython still not exports that +cdef extern from "Python.h": + char* PyByteArray_AsString(bytearray ba) except NULL + +from libc.stdint cimport uint32_t, uint64_t, uintmax_t + + +cpdef void _websocket_mask_cython(bytes mask, bytearray data): + """Note, this function mutates its `data` argument + """ + cdef: + Py_ssize_t data_len, i + # bit operations on signed integers are implementation-specific + unsigned char * in_buf + const unsigned char * mask_buf + uint32_t uint32_msk + uint64_t uint64_msk + + assert len(mask) == 4 + + data_len = len(data) + in_buf = PyByteArray_AsString(data) + mask_buf = PyBytes_AsString(mask) + uint32_msk = (mask_buf)[0] + + # TODO: align in_data ptr to achieve even faster speeds + # does it need in python ?! malloc() always aligns to sizeof(long) bytes + + if sizeof(size_t) >= 8: + uint64_msk = uint32_msk + uint64_msk = (uint64_msk << 32) | uint32_msk + + while data_len >= 8: + (in_buf)[0] ^= uint64_msk + in_buf += 8 + data_len -= 8 + + + while data_len >= 4: + (in_buf)[0] ^= uint32_msk + in_buf += 4 + data_len -= 4 + + for i in range(0, data_len): + in_buf[i] ^= mask_buf[i] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/models.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/models.py new file mode 100644 index 0000000000000000000000000000000000000000..7e89b9652957e8f4e73916e18048368e8d75911e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/models.py @@ -0,0 +1,84 @@ +"""Models for WebSocket protocol versions 13 and 8.""" + +import json +from enum import IntEnum +from typing import Any, Callable, Final, NamedTuple, Optional, cast + +WS_DEFLATE_TRAILING: Final[bytes] = bytes([0x00, 0x00, 0xFF, 0xFF]) + + +class WSCloseCode(IntEnum): + OK = 1000 + GOING_AWAY = 1001 + PROTOCOL_ERROR = 1002 + UNSUPPORTED_DATA = 1003 + ABNORMAL_CLOSURE = 1006 + INVALID_TEXT = 1007 + POLICY_VIOLATION = 1008 + MESSAGE_TOO_BIG = 1009 + MANDATORY_EXTENSION = 1010 + INTERNAL_ERROR = 1011 + SERVICE_RESTART = 1012 + TRY_AGAIN_LATER = 1013 + BAD_GATEWAY = 1014 + + +class WSMsgType(IntEnum): + # websocket spec types + CONTINUATION = 0x0 + TEXT = 0x1 + BINARY = 0x2 + PING = 0x9 + PONG = 0xA + CLOSE = 0x8 + + # aiohttp specific types + CLOSING = 0x100 + CLOSED = 0x101 + ERROR = 0x102 + + text = TEXT + binary = BINARY + ping = PING + pong = PONG + close = CLOSE + closing = CLOSING + closed = CLOSED + error = ERROR + + +class WSMessage(NamedTuple): + type: WSMsgType + # To type correctly, this would need some kind of tagged union for each type. + data: Any + extra: Optional[str] + + def json(self, *, loads: Callable[[Any], Any] = json.loads) -> Any: + """Return parsed JSON data. + + .. versionadded:: 0.22 + """ + return loads(self.data) + + +# Constructing the tuple directly to avoid the overhead of +# the lambda and arg processing since NamedTuples are constructed +# with a run time built lambda +# https://github.com/python/cpython/blob/d83fcf8371f2f33c7797bc8f5423a8bca8c46e5c/Lib/collections/__init__.py#L441 +WS_CLOSED_MESSAGE = tuple.__new__(WSMessage, (WSMsgType.CLOSED, None, None)) +WS_CLOSING_MESSAGE = tuple.__new__(WSMessage, (WSMsgType.CLOSING, None, None)) + + +class WebSocketError(Exception): + """WebSocket protocol parser error.""" + + def __init__(self, code: int, message: str) -> None: + self.code = code + super().__init__(code, message) + + def __str__(self) -> str: + return cast(str, self.args[1]) + + +class WSHandshakeError(Exception): + """WebSocket protocol handshake error.""" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader.py new file mode 100644 index 0000000000000000000000000000000000000000..23f32265cfccbdc8c8fe2f1600accbfb6f816efa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader.py @@ -0,0 +1,31 @@ +"""Reader for WebSocket protocol versions 13 and 8.""" + +from typing import TYPE_CHECKING + +from ..helpers import NO_EXTENSIONS + +if TYPE_CHECKING or NO_EXTENSIONS: # pragma: no cover + from .reader_py import ( + WebSocketDataQueue as WebSocketDataQueuePython, + WebSocketReader as WebSocketReaderPython, + ) + + WebSocketReader = WebSocketReaderPython + WebSocketDataQueue = WebSocketDataQueuePython +else: + try: + from .reader_c import ( # type: ignore[import-not-found] + WebSocketDataQueue as WebSocketDataQueueCython, + WebSocketReader as WebSocketReaderCython, + ) + + WebSocketReader = WebSocketReaderCython + WebSocketDataQueue = WebSocketDataQueueCython + except ImportError: # pragma: no cover + from .reader_py import ( + WebSocketDataQueue as WebSocketDataQueuePython, + WebSocketReader as WebSocketReaderPython, + ) + + WebSocketReader = WebSocketReaderPython + WebSocketDataQueue = WebSocketDataQueuePython diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..75e301100dc9bb91611b50d2bbc2094af86ef37f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5640792bd557a3ecc2f5a69aee9df13b0493b3e3a0798b2a644db5b89d49778c +size 1818512 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a7620d8e87fddd189ed9dbb062e6ec34aa8d673e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_c.pxd @@ -0,0 +1,110 @@ +import cython + +from .mask cimport _websocket_mask_cython as websocket_mask + + +cdef unsigned int READ_HEADER +cdef unsigned int READ_PAYLOAD_LENGTH +cdef unsigned int READ_PAYLOAD_MASK +cdef unsigned int READ_PAYLOAD + +cdef int OP_CODE_NOT_SET +cdef int OP_CODE_CONTINUATION +cdef int OP_CODE_TEXT +cdef int OP_CODE_BINARY +cdef int OP_CODE_CLOSE +cdef int OP_CODE_PING +cdef int OP_CODE_PONG + +cdef int COMPRESSED_NOT_SET +cdef int COMPRESSED_FALSE +cdef int COMPRESSED_TRUE + +cdef object UNPACK_LEN3 +cdef object UNPACK_CLOSE_CODE +cdef object TUPLE_NEW + +cdef object WSMsgType +cdef object WSMessage + +cdef object WS_MSG_TYPE_TEXT +cdef object WS_MSG_TYPE_BINARY + +cdef set ALLOWED_CLOSE_CODES +cdef set MESSAGE_TYPES_WITH_CONTENT + +cdef tuple EMPTY_FRAME +cdef tuple EMPTY_FRAME_ERROR + +cdef class WebSocketDataQueue: + + cdef unsigned int _size + cdef public object _protocol + cdef unsigned int _limit + cdef object _loop + cdef bint _eof + cdef object _waiter + cdef object _exception + cdef public object _buffer + cdef object _get_buffer + cdef object _put_buffer + + cdef void _release_waiter(self) + + cpdef void feed_data(self, object data, unsigned int size) + + @cython.locals(size="unsigned int") + cdef _read_from_buffer(self) + +cdef class WebSocketReader: + + cdef WebSocketDataQueue queue + cdef unsigned int _max_msg_size + + cdef Exception _exc + cdef bytearray _partial + cdef unsigned int _state + + cdef int _opcode + cdef bint _frame_fin + cdef int _frame_opcode + cdef list _payload_fragments + cdef Py_ssize_t _frame_payload_len + + cdef bytes _tail + cdef bint _has_mask + cdef bytes _frame_mask + cdef Py_ssize_t _payload_bytes_to_read + cdef unsigned int _payload_len_flag + cdef int _compressed + cdef object _decompressobj + cdef bint _compress + + cpdef tuple feed_data(self, object data) + + @cython.locals( + is_continuation=bint, + fin=bint, + has_partial=bint, + payload_merged=bytes, + ) + cpdef void _handle_frame(self, bint fin, int opcode, object payload, int compressed) except * + + @cython.locals( + start_pos=Py_ssize_t, + data_len=Py_ssize_t, + length=Py_ssize_t, + chunk_size=Py_ssize_t, + chunk_len=Py_ssize_t, + data_len=Py_ssize_t, + data_cstr="const unsigned char *", + first_byte="unsigned char", + second_byte="unsigned char", + f_start_pos=Py_ssize_t, + f_end_pos=Py_ssize_t, + has_mask=bint, + fin=bint, + had_fragments=Py_ssize_t, + payload_bytearray=bytearray, + ) + cpdef void _feed_data(self, bytes data) except * diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_py.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_py.py new file mode 100644 index 0000000000000000000000000000000000000000..f966a1593c5bc534442d1bd1a1067b0998969b28 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/_websocket/reader_py.py @@ -0,0 +1,476 @@ +"""Reader for WebSocket protocol versions 13 and 8.""" + +import asyncio +import builtins +from collections import deque +from typing import Deque, Final, Optional, Set, Tuple, Union + +from ..base_protocol import BaseProtocol +from ..compression_utils import ZLibDecompressor +from ..helpers import _EXC_SENTINEL, set_exception +from ..streams import EofStream +from .helpers import UNPACK_CLOSE_CODE, UNPACK_LEN3, websocket_mask +from .models import ( + WS_DEFLATE_TRAILING, + WebSocketError, + WSCloseCode, + WSMessage, + WSMsgType, +) + +ALLOWED_CLOSE_CODES: Final[Set[int]] = {int(i) for i in WSCloseCode} + +# States for the reader, used to parse the WebSocket frame +# integer values are used so they can be cythonized +READ_HEADER = 1 +READ_PAYLOAD_LENGTH = 2 +READ_PAYLOAD_MASK = 3 +READ_PAYLOAD = 4 + +WS_MSG_TYPE_BINARY = WSMsgType.BINARY +WS_MSG_TYPE_TEXT = WSMsgType.TEXT + +# WSMsgType values unpacked so they can by cythonized to ints +OP_CODE_NOT_SET = -1 +OP_CODE_CONTINUATION = WSMsgType.CONTINUATION.value +OP_CODE_TEXT = WSMsgType.TEXT.value +OP_CODE_BINARY = WSMsgType.BINARY.value +OP_CODE_CLOSE = WSMsgType.CLOSE.value +OP_CODE_PING = WSMsgType.PING.value +OP_CODE_PONG = WSMsgType.PONG.value + +EMPTY_FRAME_ERROR = (True, b"") +EMPTY_FRAME = (False, b"") + +COMPRESSED_NOT_SET = -1 +COMPRESSED_FALSE = 0 +COMPRESSED_TRUE = 1 + +TUPLE_NEW = tuple.__new__ + +cython_int = int # Typed to int in Python, but cython with use a signed int in the pxd + + +class WebSocketDataQueue: + """WebSocketDataQueue resumes and pauses an underlying stream. + + It is a destination for WebSocket data. + """ + + def __init__( + self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop + ) -> None: + self._size = 0 + self._protocol = protocol + self._limit = limit * 2 + self._loop = loop + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._exception: Union[BaseException, None] = None + self._buffer: Deque[Tuple[WSMessage, int]] = deque() + self._get_buffer = self._buffer.popleft + self._put_buffer = self._buffer.append + + def is_eof(self) -> bool: + return self._eof + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: BaseException, + exc_cause: builtins.BaseException = _EXC_SENTINEL, + ) -> None: + self._eof = True + self._exception = exc + if (waiter := self._waiter) is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + def _release_waiter(self) -> None: + if (waiter := self._waiter) is None: + return + self._waiter = None + if not waiter.done(): + waiter.set_result(None) + + def feed_eof(self) -> None: + self._eof = True + self._release_waiter() + self._exception = None # Break cyclic references + + def feed_data(self, data: "WSMessage", size: "cython_int") -> None: + self._size += size + self._put_buffer((data, size)) + self._release_waiter() + if self._size > self._limit and not self._protocol._reading_paused: + self._protocol.pause_reading() + + async def read(self) -> WSMessage: + if not self._buffer and not self._eof: + assert not self._waiter + self._waiter = self._loop.create_future() + try: + await self._waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._waiter = None + raise + return self._read_from_buffer() + + def _read_from_buffer(self) -> WSMessage: + if self._buffer: + data, size = self._get_buffer() + self._size -= size + if self._size < self._limit and self._protocol._reading_paused: + self._protocol.resume_reading() + return data + if self._exception is not None: + raise self._exception + raise EofStream + + +class WebSocketReader: + def __init__( + self, queue: WebSocketDataQueue, max_msg_size: int, compress: bool = True + ) -> None: + self.queue = queue + self._max_msg_size = max_msg_size + + self._exc: Optional[Exception] = None + self._partial = bytearray() + self._state = READ_HEADER + + self._opcode: int = OP_CODE_NOT_SET + self._frame_fin = False + self._frame_opcode: int = OP_CODE_NOT_SET + self._payload_fragments: list[bytes] = [] + self._frame_payload_len = 0 + + self._tail: bytes = b"" + self._has_mask = False + self._frame_mask: Optional[bytes] = None + self._payload_bytes_to_read = 0 + self._payload_len_flag = 0 + self._compressed: int = COMPRESSED_NOT_SET + self._decompressobj: Optional[ZLibDecompressor] = None + self._compress = compress + + def feed_eof(self) -> None: + self.queue.feed_eof() + + # data can be bytearray on Windows because proactor event loop uses bytearray + # and asyncio types this to Union[bytes, bytearray, memoryview] so we need + # coerce data to bytes if it is not + def feed_data( + self, data: Union[bytes, bytearray, memoryview] + ) -> Tuple[bool, bytes]: + if type(data) is not bytes: + data = bytes(data) + + if self._exc is not None: + return True, data + + try: + self._feed_data(data) + except Exception as exc: + self._exc = exc + set_exception(self.queue, exc) + return EMPTY_FRAME_ERROR + + return EMPTY_FRAME + + def _handle_frame( + self, + fin: bool, + opcode: Union[int, cython_int], # Union intended: Cython pxd uses C int + payload: Union[bytes, bytearray], + compressed: Union[int, cython_int], # Union intended: Cython pxd uses C int + ) -> None: + msg: WSMessage + if opcode in {OP_CODE_TEXT, OP_CODE_BINARY, OP_CODE_CONTINUATION}: + # load text/binary + if not fin: + # got partial frame payload + if opcode != OP_CODE_CONTINUATION: + self._opcode = opcode + self._partial += payload + if self._max_msg_size and len(self._partial) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Message size {len(self._partial)} " + f"exceeds limit {self._max_msg_size}", + ) + return + + has_partial = bool(self._partial) + if opcode == OP_CODE_CONTINUATION: + if self._opcode == OP_CODE_NOT_SET: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Continuation frame for non started message", + ) + opcode = self._opcode + self._opcode = OP_CODE_NOT_SET + # previous frame was non finished + # we should get continuation opcode + elif has_partial: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "The opcode in non-fin frame is expected " + f"to be zero, got {opcode!r}", + ) + + assembled_payload: Union[bytes, bytearray] + if has_partial: + assembled_payload = self._partial + payload + self._partial.clear() + else: + assembled_payload = payload + + if self._max_msg_size and len(assembled_payload) >= self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Message size {len(assembled_payload)} " + f"exceeds limit {self._max_msg_size}", + ) + + # Decompress process must to be done after all packets + # received. + if compressed: + if not self._decompressobj: + self._decompressobj = ZLibDecompressor(suppress_deflate_header=True) + # XXX: It's possible that the zlib backend (isal is known to + # do this, maybe others too?) will return max_length bytes, + # but internally buffer more data such that the payload is + # >max_length, so we return one extra byte and if we're able + # to do that, then the message is too big. + payload_merged = self._decompressobj.decompress_sync( + assembled_payload + WS_DEFLATE_TRAILING, + ( + self._max_msg_size + 1 + if self._max_msg_size + else self._max_msg_size + ), + ) + if self._max_msg_size and len(payload_merged) > self._max_msg_size: + raise WebSocketError( + WSCloseCode.MESSAGE_TOO_BIG, + f"Decompressed message exceeds size limit {self._max_msg_size}", + ) + elif type(assembled_payload) is bytes: + payload_merged = assembled_payload + else: + payload_merged = bytes(assembled_payload) + + if opcode == OP_CODE_TEXT: + try: + text = payload_merged.decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + + # XXX: The Text and Binary messages here can be a performance + # bottleneck, so we use tuple.__new__ to improve performance. + # This is not type safe, but many tests should fail in + # test_client_ws_functional.py if this is wrong. + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_TEXT, text, "")), + len(payload_merged), + ) + else: + self.queue.feed_data( + TUPLE_NEW(WSMessage, (WS_MSG_TYPE_BINARY, payload_merged, "")), + len(payload_merged), + ) + elif opcode == OP_CODE_CLOSE: + if len(payload) >= 2: + close_code = UNPACK_CLOSE_CODE(payload[:2])[0] + if close_code < 3000 and close_code not in ALLOWED_CLOSE_CODES: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close code: {close_code}", + ) + try: + close_message = payload[2:].decode("utf-8") + except UnicodeDecodeError as exc: + raise WebSocketError( + WSCloseCode.INVALID_TEXT, "Invalid UTF-8 text message" + ) from exc + msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, close_code, close_message)) + elif payload: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + f"Invalid close frame: {fin} {opcode} {payload!r}", + ) + else: + msg = TUPLE_NEW(WSMessage, (WSMsgType.CLOSE, 0, "")) + + self.queue.feed_data(msg, 0) + elif opcode == OP_CODE_PING: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PING, payload, "")) + self.queue.feed_data(msg, len(payload)) + elif opcode == OP_CODE_PONG: + msg = TUPLE_NEW(WSMessage, (WSMsgType.PONG, payload, "")) + self.queue.feed_data(msg, len(payload)) + else: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, f"Unexpected opcode={opcode!r}" + ) + + def _feed_data(self, data: bytes) -> None: + """Return the next frame from the socket.""" + if self._tail: + data, self._tail = self._tail + data, b"" + + start_pos: int = 0 + data_len = len(data) + data_cstr = data + + while True: + # read header + if self._state == READ_HEADER: + if data_len - start_pos < 2: + break + first_byte = data_cstr[start_pos] + second_byte = data_cstr[start_pos + 1] + start_pos += 2 + + fin = (first_byte >> 7) & 1 + rsv1 = (first_byte >> 6) & 1 + rsv2 = (first_byte >> 5) & 1 + rsv3 = (first_byte >> 4) & 1 + opcode = first_byte & 0xF + + # frame-fin = %x0 ; more frames of this message follow + # / %x1 ; final frame of this message + # frame-rsv1 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv2 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # frame-rsv3 = %x0 ; + # 1 bit, MUST be 0 unless negotiated otherwise + # + # Remove rsv1 from this test for deflate development + if rsv2 or rsv3 or (rsv1 and not self._compress): + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + if opcode > 0x7 and fin == 0: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received fragmented control frame", + ) + + has_mask = (second_byte >> 7) & 1 + length = second_byte & 0x7F + + # Control frames MUST have a payload + # length of 125 bytes or less + if opcode > 0x7 and length > 125: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Control frame payload cannot be larger than 125 bytes", + ) + + # Set compress status if last package is FIN + # OR set compress status if this is first fragment + # Raise error if not first fragment with rsv1 = 0x1 + if self._frame_fin or self._compressed == COMPRESSED_NOT_SET: + self._compressed = COMPRESSED_TRUE if rsv1 else COMPRESSED_FALSE + elif rsv1: + raise WebSocketError( + WSCloseCode.PROTOCOL_ERROR, + "Received frame with non-zero reserved bits", + ) + + self._frame_fin = bool(fin) + self._frame_opcode = opcode + self._has_mask = bool(has_mask) + self._payload_len_flag = length + self._state = READ_PAYLOAD_LENGTH + + # read payload length + if self._state == READ_PAYLOAD_LENGTH: + len_flag = self._payload_len_flag + if len_flag == 126: + if data_len - start_pos < 2: + break + first_byte = data_cstr[start_pos] + second_byte = data_cstr[start_pos + 1] + start_pos += 2 + self._payload_bytes_to_read = first_byte << 8 | second_byte + elif len_flag > 126: + if data_len - start_pos < 8: + break + self._payload_bytes_to_read = UNPACK_LEN3(data, start_pos)[0] + start_pos += 8 + else: + self._payload_bytes_to_read = len_flag + + self._state = READ_PAYLOAD_MASK if self._has_mask else READ_PAYLOAD + + # read payload mask + if self._state == READ_PAYLOAD_MASK: + if data_len - start_pos < 4: + break + self._frame_mask = data_cstr[start_pos : start_pos + 4] + start_pos += 4 + self._state = READ_PAYLOAD + + if self._state == READ_PAYLOAD: + chunk_len = data_len - start_pos + if self._payload_bytes_to_read >= chunk_len: + f_end_pos = data_len + self._payload_bytes_to_read -= chunk_len + else: + f_end_pos = start_pos + self._payload_bytes_to_read + self._payload_bytes_to_read = 0 + + had_fragments = self._frame_payload_len + self._frame_payload_len += f_end_pos - start_pos + f_start_pos = start_pos + start_pos = f_end_pos + + if self._payload_bytes_to_read != 0: + # If we don't have a complete frame, we need to save the + # data for the next call to feed_data. + self._payload_fragments.append(data_cstr[f_start_pos:f_end_pos]) + break + + payload: Union[bytes, bytearray] + if had_fragments: + # We have to join the payload fragments get the payload + self._payload_fragments.append(data_cstr[f_start_pos:f_end_pos]) + if self._has_mask: + assert self._frame_mask is not None + payload_bytearray = bytearray(b"".join(self._payload_fragments)) + websocket_mask(self._frame_mask, payload_bytearray) + payload = payload_bytearray + else: + payload = b"".join(self._payload_fragments) + self._payload_fragments.clear() + elif self._has_mask: + assert self._frame_mask is not None + payload_bytearray = data_cstr[f_start_pos:f_end_pos] # type: ignore[assignment] + if type(payload_bytearray) is not bytearray: # pragma: no branch + # Cython will do the conversion for us + # but we need to do it for Python and we + # will always get here in Python + payload_bytearray = bytearray(payload_bytearray) + websocket_mask(self._frame_mask, payload_bytearray) + payload = payload_bytearray + else: + payload = data_cstr[f_start_pos:f_end_pos] + + self._handle_frame( + self._frame_fin, self._frame_opcode, payload, self._compressed + ) + self._frame_payload_len = 0 + self._state = READ_HEADER + + # XXX: Cython needs slices to be bounded, so we can't omit the slice end here. + self._tail = data_cstr[start_pos:data_len] if start_pos < data_len else b"" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/abc.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..2574ff936219593a5ea063302e23cca2c4b0a02c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/abc.py @@ -0,0 +1,268 @@ +import asyncio +import logging +import socket +from abc import ABC, abstractmethod +from collections.abc import Sized +from http.cookies import BaseCookie, Morsel +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Dict, + Generator, + Iterable, + List, + Optional, + Sequence, + Tuple, + TypedDict, + Union, +) + +from multidict import CIMultiDict +from yarl import URL + +from ._cookie_helpers import parse_set_cookie_headers +from .typedefs import LooseCookies + +if TYPE_CHECKING: + from .web_app import Application + from .web_exceptions import HTTPException + from .web_request import BaseRequest, Request + from .web_response import StreamResponse +else: + BaseRequest = Request = Application = StreamResponse = None + HTTPException = None + + +class AbstractRouter(ABC): + def __init__(self) -> None: + self._frozen = False + + def post_init(self, app: Application) -> None: + """Post init stage. + + Not an abstract method for sake of backward compatibility, + but if the router wants to be aware of the application + it can override this. + """ + + @property + def frozen(self) -> bool: + return self._frozen + + def freeze(self) -> None: + """Freeze router.""" + self._frozen = True + + @abstractmethod + async def resolve(self, request: Request) -> "AbstractMatchInfo": + """Return MATCH_INFO for given request""" + + +class AbstractMatchInfo(ABC): + + __slots__ = () + + @property # pragma: no branch + @abstractmethod + def handler(self) -> Callable[[Request], Awaitable[StreamResponse]]: + """Execute matched request handler""" + + @property + @abstractmethod + def expect_handler( + self, + ) -> Callable[[Request], Awaitable[Optional[StreamResponse]]]: + """Expect handler for 100-continue processing""" + + @property # pragma: no branch + @abstractmethod + def http_exception(self) -> Optional[HTTPException]: + """HTTPException instance raised on router's resolving, or None""" + + @abstractmethod # pragma: no branch + def get_info(self) -> Dict[str, Any]: + """Return a dict with additional info useful for introspection""" + + @property # pragma: no branch + @abstractmethod + def apps(self) -> Tuple[Application, ...]: + """Stack of nested applications. + + Top level application is left-most element. + + """ + + @abstractmethod + def add_app(self, app: Application) -> None: + """Add application to the nested apps stack.""" + + @abstractmethod + def freeze(self) -> None: + """Freeze the match info. + + The method is called after route resolution. + + After the call .add_app() is forbidden. + + """ + + +class AbstractView(ABC): + """Abstract class based view.""" + + def __init__(self, request: Request) -> None: + self._request = request + + @property + def request(self) -> Request: + """Request instance.""" + return self._request + + @abstractmethod + def __await__(self) -> Generator[Any, None, StreamResponse]: + """Execute the view handler.""" + + +class ResolveResult(TypedDict): + """Resolve result. + + This is the result returned from an AbstractResolver's + resolve method. + + :param hostname: The hostname that was provided. + :param host: The IP address that was resolved. + :param port: The port that was resolved. + :param family: The address family that was resolved. + :param proto: The protocol that was resolved. + :param flags: The flags that were resolved. + """ + + hostname: str + host: str + port: int + family: int + proto: int + flags: int + + +class AbstractResolver(ABC): + """Abstract DNS resolver.""" + + @abstractmethod + async def resolve( + self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET + ) -> List[ResolveResult]: + """Return IP address for given hostname""" + + @abstractmethod + async def close(self) -> None: + """Release resolver""" + + +if TYPE_CHECKING: + IterableBase = Iterable[Morsel[str]] +else: + IterableBase = Iterable + + +ClearCookiePredicate = Callable[["Morsel[str]"], bool] + + +class AbstractCookieJar(Sized, IterableBase): + """Abstract Cookie Jar.""" + + def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: + self._loop = loop or asyncio.get_running_loop() + + @property + @abstractmethod + def quote_cookie(self) -> bool: + """Return True if cookies should be quoted.""" + + @abstractmethod + def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: + """Clear all cookies if no predicate is passed.""" + + @abstractmethod + def clear_domain(self, domain: str) -> None: + """Clear all cookies for domain and all subdomains.""" + + @abstractmethod + def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: + """Update cookies.""" + + def update_cookies_from_headers( + self, headers: Sequence[str], response_url: URL + ) -> None: + """Update cookies from raw Set-Cookie headers.""" + if headers and (cookies_to_update := parse_set_cookie_headers(headers)): + self.update_cookies(cookies_to_update, response_url) + + @abstractmethod + def filter_cookies(self, request_url: URL) -> "BaseCookie[str]": + """Return the jar's cookies filtered by their attributes.""" + + +class AbstractStreamWriter(ABC): + """Abstract stream writer.""" + + buffer_size: int = 0 + output_size: int = 0 + length: Optional[int] = 0 + + @abstractmethod + async def write(self, chunk: Union[bytes, bytearray, memoryview]) -> None: + """Write chunk into stream.""" + + @abstractmethod + async def write_eof(self, chunk: bytes = b"") -> None: + """Write last chunk.""" + + @abstractmethod + async def drain(self) -> None: + """Flush the write buffer.""" + + @abstractmethod + def enable_compression( + self, encoding: str = "deflate", strategy: Optional[int] = None + ) -> None: + """Enable HTTP body compression""" + + @abstractmethod + def enable_chunking(self) -> None: + """Enable HTTP chunked mode""" + + @abstractmethod + async def write_headers( + self, status_line: str, headers: "CIMultiDict[str]" + ) -> None: + """Write HTTP headers""" + + def send_headers(self) -> None: + """Force sending buffered headers if not already sent. + + Required only if write_headers() buffers headers instead of sending immediately. + For backwards compatibility, this method does nothing by default. + """ + + +class AbstractAccessLogger(ABC): + """Abstract writer to access log.""" + + __slots__ = ("logger", "log_format") + + def __init__(self, logger: logging.Logger, log_format: str) -> None: + self.logger = logger + self.log_format = log_format + + @abstractmethod + def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: + """Emit log to logger.""" + + @property + def enabled(self) -> bool: + """Check if logger is enabled.""" + return True diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/base_protocol.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/base_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..b0a67ed6ff68ca5bc48be9ac472ee755369b2720 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/base_protocol.py @@ -0,0 +1,100 @@ +import asyncio +from typing import Optional, cast + +from .client_exceptions import ClientConnectionResetError +from .helpers import set_exception +from .tcp_helpers import tcp_nodelay + + +class BaseProtocol(asyncio.Protocol): + __slots__ = ( + "_loop", + "_paused", + "_drain_waiter", + "_connection_lost", + "_reading_paused", + "transport", + ) + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop: asyncio.AbstractEventLoop = loop + self._paused = False + self._drain_waiter: Optional[asyncio.Future[None]] = None + self._reading_paused = False + + self.transport: Optional[asyncio.Transport] = None + + @property + def connected(self) -> bool: + """Return True if the connection is open.""" + return self.transport is not None + + @property + def writing_paused(self) -> bool: + return self._paused + + def pause_writing(self) -> None: + assert not self._paused + self._paused = True + + def resume_writing(self) -> None: + assert self._paused + self._paused = False + + waiter = self._drain_waiter + if waiter is not None: + self._drain_waiter = None + if not waiter.done(): + waiter.set_result(None) + + def pause_reading(self) -> None: + if not self._reading_paused and self.transport is not None: + try: + self.transport.pause_reading() + except (AttributeError, NotImplementedError, RuntimeError): + pass + self._reading_paused = True + + def resume_reading(self) -> None: + if self._reading_paused and self.transport is not None: + try: + self.transport.resume_reading() + except (AttributeError, NotImplementedError, RuntimeError): + pass + self._reading_paused = False + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + tr = cast(asyncio.Transport, transport) + tcp_nodelay(tr, True) + self.transport = tr + + def connection_lost(self, exc: Optional[BaseException]) -> None: + # Wake up the writer if currently paused. + self.transport = None + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + return + self._drain_waiter = None + if waiter.done(): + return + if exc is None: + waiter.set_result(None) + else: + set_exception( + waiter, + ConnectionError("Connection lost"), + exc, + ) + + async def _drain_helper(self) -> None: + if self.transport is None: + raise ClientConnectionResetError("Connection lost") + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + waiter = self._loop.create_future() + self._drain_waiter = waiter + await asyncio.shield(waiter) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client.py new file mode 100644 index 0000000000000000000000000000000000000000..0c72d5948ce806d8e633f80da3d9a965aa86cf20 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client.py @@ -0,0 +1,1613 @@ +"""HTTP Client for asyncio.""" + +import asyncio +import base64 +import hashlib +import json +import os +import sys +import traceback +import warnings +from contextlib import suppress +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Coroutine, + Final, + FrozenSet, + Generator, + Generic, + Iterable, + List, + Mapping, + Optional, + Sequence, + Set, + Tuple, + Type, + TypedDict, + TypeVar, + Union, +) + +import attr +from multidict import CIMultiDict, MultiDict, MultiDictProxy, istr +from yarl import URL + +from . import hdrs, http, payload +from ._websocket.reader import WebSocketDataQueue +from .abc import AbstractCookieJar +from .client_exceptions import ( + ClientConnectionError, + ClientConnectionResetError, + ClientConnectorCertificateError, + ClientConnectorDNSError, + ClientConnectorError, + ClientConnectorSSLError, + ClientError, + ClientHttpProxyError, + ClientOSError, + ClientPayloadError, + ClientProxyConnectionError, + ClientResponseError, + ClientSSLError, + ConnectionTimeoutError, + ContentTypeError, + InvalidURL, + InvalidUrlClientError, + InvalidUrlRedirectClientError, + NonHttpUrlClientError, + NonHttpUrlRedirectClientError, + RedirectClientError, + ServerConnectionError, + ServerDisconnectedError, + ServerFingerprintMismatch, + ServerTimeoutError, + SocketTimeoutError, + TooManyRedirects, + WSMessageTypeError, + WSServerHandshakeError, +) +from .client_middlewares import ClientMiddlewareType, build_client_middlewares +from .client_reqrep import ( + ClientRequest as ClientRequest, + ClientResponse as ClientResponse, + Fingerprint as Fingerprint, + RequestInfo as RequestInfo, + _merge_ssl_params, +) +from .client_ws import ( + DEFAULT_WS_CLIENT_TIMEOUT, + ClientWebSocketResponse as ClientWebSocketResponse, + ClientWSTimeout as ClientWSTimeout, +) +from .connector import ( + HTTP_AND_EMPTY_SCHEMA_SET, + BaseConnector as BaseConnector, + NamedPipeConnector as NamedPipeConnector, + TCPConnector as TCPConnector, + UnixConnector as UnixConnector, +) +from .cookiejar import CookieJar +from .helpers import ( + _SENTINEL, + DEBUG, + EMPTY_BODY_METHODS, + BasicAuth, + TimeoutHandle, + get_env_proxy_for_url, + sentinel, + strip_auth_from_url, +) +from .http import WS_KEY, HttpVersion, WebSocketReader, WebSocketWriter +from .http_websocket import WSHandshakeError, ws_ext_gen, ws_ext_parse +from .tracing import Trace, TraceConfig +from .typedefs import JSONEncoder, LooseCookies, LooseHeaders, Query, StrOrURL + +__all__ = ( + # client_exceptions + "ClientConnectionError", + "ClientConnectionResetError", + "ClientConnectorCertificateError", + "ClientConnectorDNSError", + "ClientConnectorError", + "ClientConnectorSSLError", + "ClientError", + "ClientHttpProxyError", + "ClientOSError", + "ClientPayloadError", + "ClientProxyConnectionError", + "ClientResponseError", + "ClientSSLError", + "ConnectionTimeoutError", + "ContentTypeError", + "InvalidURL", + "InvalidUrlClientError", + "RedirectClientError", + "NonHttpUrlClientError", + "InvalidUrlRedirectClientError", + "NonHttpUrlRedirectClientError", + "ServerConnectionError", + "ServerDisconnectedError", + "ServerFingerprintMismatch", + "ServerTimeoutError", + "SocketTimeoutError", + "TooManyRedirects", + "WSServerHandshakeError", + # client_reqrep + "ClientRequest", + "ClientResponse", + "Fingerprint", + "RequestInfo", + # connector + "BaseConnector", + "TCPConnector", + "UnixConnector", + "NamedPipeConnector", + # client_ws + "ClientWebSocketResponse", + # client + "ClientSession", + "ClientTimeout", + "ClientWSTimeout", + "request", + "WSMessageTypeError", +) + + +if TYPE_CHECKING: + from ssl import SSLContext +else: + SSLContext = None + +if sys.version_info >= (3, 11) and TYPE_CHECKING: + from typing import Unpack + + +class _RequestOptions(TypedDict, total=False): + params: Query + data: Any + json: Any + cookies: Union[LooseCookies, None] + headers: Union[LooseHeaders, None] + skip_auto_headers: Union[Iterable[str], None] + auth: Union[BasicAuth, None] + allow_redirects: bool + max_redirects: int + compress: Union[str, bool, None] + chunked: Union[bool, None] + expect100: bool + raise_for_status: Union[None, bool, Callable[[ClientResponse], Awaitable[None]]] + read_until_eof: bool + proxy: Union[StrOrURL, None] + proxy_auth: Union[BasicAuth, None] + timeout: "Union[ClientTimeout, _SENTINEL, None]" + ssl: Union[SSLContext, bool, Fingerprint] + server_hostname: Union[str, None] + proxy_headers: Union[LooseHeaders, None] + trace_request_ctx: Union[Mapping[str, Any], None] + read_bufsize: Union[int, None] + auto_decompress: Union[bool, None] + max_line_size: Union[int, None] + max_field_size: Union[int, None] + middlewares: Optional[Sequence[ClientMiddlewareType]] + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ClientTimeout: + total: Optional[float] = None + connect: Optional[float] = None + sock_read: Optional[float] = None + sock_connect: Optional[float] = None + ceil_threshold: float = 5 + + # pool_queue_timeout: Optional[float] = None + # dns_resolution_timeout: Optional[float] = None + # socket_connect_timeout: Optional[float] = None + # connection_acquiring_timeout: Optional[float] = None + # new_connection_timeout: Optional[float] = None + # http_header_timeout: Optional[float] = None + # response_body_timeout: Optional[float] = None + + # to create a timeout specific for a single request, either + # - create a completely new one to overwrite the default + # - or use http://www.attrs.org/en/stable/api.html#attr.evolve + # to overwrite the defaults + + +# 5 Minute default read timeout +DEFAULT_TIMEOUT: Final[ClientTimeout] = ClientTimeout(total=5 * 60, sock_connect=30) + +# https://www.rfc-editor.org/rfc/rfc9110#section-9.2.2 +IDEMPOTENT_METHODS = frozenset({"GET", "HEAD", "OPTIONS", "TRACE", "PUT", "DELETE"}) + +_RetType = TypeVar("_RetType", ClientResponse, ClientWebSocketResponse) +_CharsetResolver = Callable[[ClientResponse, bytes], str] + + +class ClientSession: + """First-class interface for making HTTP requests.""" + + ATTRS = frozenset( + [ + "_base_url", + "_base_url_origin", + "_source_traceback", + "_connector", + "_loop", + "_cookie_jar", + "_connector_owner", + "_default_auth", + "_version", + "_json_serialize", + "_requote_redirect_url", + "_timeout", + "_raise_for_status", + "_auto_decompress", + "_trust_env", + "_default_headers", + "_skip_auto_headers", + "_request_class", + "_response_class", + "_ws_response_class", + "_trace_configs", + "_read_bufsize", + "_max_line_size", + "_max_field_size", + "_resolve_charset", + "_default_proxy", + "_default_proxy_auth", + "_retry_connection", + "_middlewares", + "requote_redirect_url", + ] + ) + + _source_traceback: Optional[traceback.StackSummary] = None + _connector: Optional[BaseConnector] = None + + def __init__( + self, + base_url: Optional[StrOrURL] = None, + *, + connector: Optional[BaseConnector] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + cookies: Optional[LooseCookies] = None, + headers: Optional[LooseHeaders] = None, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + skip_auto_headers: Optional[Iterable[str]] = None, + auth: Optional[BasicAuth] = None, + json_serialize: JSONEncoder = json.dumps, + request_class: Type[ClientRequest] = ClientRequest, + response_class: Type[ClientResponse] = ClientResponse, + ws_response_class: Type[ClientWebSocketResponse] = ClientWebSocketResponse, + version: HttpVersion = http.HttpVersion11, + cookie_jar: Optional[AbstractCookieJar] = None, + connector_owner: bool = True, + raise_for_status: Union[ + bool, Callable[[ClientResponse], Awaitable[None]] + ] = False, + read_timeout: Union[float, _SENTINEL] = sentinel, + conn_timeout: Optional[float] = None, + timeout: Union[object, ClientTimeout] = sentinel, + auto_decompress: bool = True, + trust_env: bool = False, + requote_redirect_url: bool = True, + trace_configs: Optional[List[TraceConfig]] = None, + read_bufsize: int = 2**16, + max_line_size: int = 8190, + max_field_size: int = 8190, + fallback_charset_resolver: _CharsetResolver = lambda r, b: "utf-8", + middlewares: Sequence[ClientMiddlewareType] = (), + ssl_shutdown_timeout: Union[_SENTINEL, None, float] = sentinel, + ) -> None: + # We initialise _connector to None immediately, as it's referenced in __del__() + # and could cause issues if an exception occurs during initialisation. + self._connector: Optional[BaseConnector] = None + + if loop is None: + if connector is not None: + loop = connector._loop + + loop = loop or asyncio.get_running_loop() + + if base_url is None or isinstance(base_url, URL): + self._base_url: Optional[URL] = base_url + self._base_url_origin = None if base_url is None else base_url.origin() + else: + self._base_url = URL(base_url) + self._base_url_origin = self._base_url.origin() + assert self._base_url.absolute, "Only absolute URLs are supported" + if self._base_url is not None and not self._base_url.path.endswith("/"): + raise ValueError("base_url must have a trailing '/'") + + if timeout is sentinel or timeout is None: + self._timeout = DEFAULT_TIMEOUT + if read_timeout is not sentinel: + warnings.warn( + "read_timeout is deprecated, use timeout argument instead", + DeprecationWarning, + stacklevel=2, + ) + self._timeout = attr.evolve(self._timeout, total=read_timeout) + if conn_timeout is not None: + self._timeout = attr.evolve(self._timeout, connect=conn_timeout) + warnings.warn( + "conn_timeout is deprecated, use timeout argument instead", + DeprecationWarning, + stacklevel=2, + ) + else: + if not isinstance(timeout, ClientTimeout): + raise ValueError( + f"timeout parameter cannot be of {type(timeout)} type, " + "please use 'timeout=ClientTimeout(...)'", + ) + self._timeout = timeout + if read_timeout is not sentinel: + raise ValueError( + "read_timeout and timeout parameters " + "conflict, please setup " + "timeout.read" + ) + if conn_timeout is not None: + raise ValueError( + "conn_timeout and timeout parameters " + "conflict, please setup " + "timeout.connect" + ) + + if ssl_shutdown_timeout is not sentinel: + warnings.warn( + "The ssl_shutdown_timeout parameter is deprecated and will be removed in aiohttp 4.0", + DeprecationWarning, + stacklevel=2, + ) + + if connector is None: + connector = TCPConnector( + loop=loop, ssl_shutdown_timeout=ssl_shutdown_timeout + ) + + if connector._loop is not loop: + raise RuntimeError("Session and connector has to use same event loop") + + self._loop = loop + + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + if cookie_jar is None: + cookie_jar = CookieJar(loop=loop) + self._cookie_jar = cookie_jar + + if cookies: + self._cookie_jar.update_cookies(cookies) + + self._connector = connector + self._connector_owner = connector_owner + self._default_auth = auth + self._version = version + self._json_serialize = json_serialize + self._raise_for_status = raise_for_status + self._auto_decompress = auto_decompress + self._trust_env = trust_env + self._requote_redirect_url = requote_redirect_url + self._read_bufsize = read_bufsize + self._max_line_size = max_line_size + self._max_field_size = max_field_size + + # Convert to list of tuples + if headers: + real_headers: CIMultiDict[str] = CIMultiDict(headers) + else: + real_headers = CIMultiDict() + self._default_headers: CIMultiDict[str] = real_headers + if skip_auto_headers is not None: + self._skip_auto_headers = frozenset(istr(i) for i in skip_auto_headers) + else: + self._skip_auto_headers = frozenset() + + self._request_class = request_class + self._response_class = response_class + self._ws_response_class = ws_response_class + + self._trace_configs = trace_configs or [] + for trace_config in self._trace_configs: + trace_config.freeze() + + self._resolve_charset = fallback_charset_resolver + + self._default_proxy = proxy + self._default_proxy_auth = proxy_auth + self._retry_connection: bool = True + self._middlewares = middlewares + + def __init_subclass__(cls: Type["ClientSession"]) -> None: + warnings.warn( + "Inheritance class {} from ClientSession " + "is discouraged".format(cls.__name__), + DeprecationWarning, + stacklevel=2, + ) + + if DEBUG: + + def __setattr__(self, name: str, val: Any) -> None: + if name not in self.ATTRS: + warnings.warn( + "Setting custom ClientSession.{} attribute " + "is discouraged".format(name), + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(name, val) + + def __del__(self, _warnings: Any = warnings) -> None: + if not self.closed: + kwargs = {"source": self} + _warnings.warn( + f"Unclosed client session {self!r}", ResourceWarning, **kwargs + ) + context = {"client_session": self, "message": "Unclosed client session"} + if self._source_traceback is not None: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + if sys.version_info >= (3, 11) and TYPE_CHECKING: + + def request( + self, + method: str, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + else: + + def request( + self, method: str, url: StrOrURL, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP request.""" + return _RequestContextManager(self._request(method, url, **kwargs)) + + def _build_url(self, str_or_url: StrOrURL) -> URL: + url = URL(str_or_url) + if self._base_url and not url.absolute: + return self._base_url.join(url) + return url + + async def _request( + self, + method: str, + str_or_url: StrOrURL, + *, + params: Query = None, + data: Any = None, + json: Any = None, + cookies: Optional[LooseCookies] = None, + headers: Optional[LooseHeaders] = None, + skip_auto_headers: Optional[Iterable[str]] = None, + auth: Optional[BasicAuth] = None, + allow_redirects: bool = True, + max_redirects: int = 10, + compress: Union[str, bool, None] = None, + chunked: Optional[bool] = None, + expect100: bool = False, + raise_for_status: Union[ + None, bool, Callable[[ClientResponse], Awaitable[None]] + ] = None, + read_until_eof: bool = True, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + timeout: Union[ClientTimeout, _SENTINEL] = sentinel, + verify_ssl: Optional[bool] = None, + fingerprint: Optional[bytes] = None, + ssl_context: Optional[SSLContext] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + server_hostname: Optional[str] = None, + proxy_headers: Optional[LooseHeaders] = None, + trace_request_ctx: Optional[Mapping[str, Any]] = None, + read_bufsize: Optional[int] = None, + auto_decompress: Optional[bool] = None, + max_line_size: Optional[int] = None, + max_field_size: Optional[int] = None, + middlewares: Optional[Sequence[ClientMiddlewareType]] = None, + ) -> ClientResponse: + + # NOTE: timeout clamps existing connect and read timeouts. We cannot + # set the default to None because we need to detect if the user wants + # to use the existing timeouts by setting timeout to None. + + if self.closed: + raise RuntimeError("Session is closed") + + ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) + + if data is not None and json is not None: + raise ValueError( + "data and json parameters can not be used at the same time" + ) + elif json is not None: + data = payload.JsonPayload(json, dumps=self._json_serialize) + + if not isinstance(chunked, bool) and chunked is not None: + warnings.warn("Chunk size is deprecated #1615", DeprecationWarning) + + redirects = 0 + history: List[ClientResponse] = [] + version = self._version + params = params or {} + + # Merge with default headers and transform to CIMultiDict + headers = self._prepare_headers(headers) + + try: + url = self._build_url(str_or_url) + except ValueError as e: + raise InvalidUrlClientError(str_or_url) from e + + assert self._connector is not None + if url.scheme not in self._connector.allowed_protocol_schema_set: + raise NonHttpUrlClientError(url) + + skip_headers: Optional[Iterable[istr]] + if skip_auto_headers is not None: + skip_headers = { + istr(i) for i in skip_auto_headers + } | self._skip_auto_headers + elif self._skip_auto_headers: + skip_headers = self._skip_auto_headers + else: + skip_headers = None + + if proxy is None: + proxy = self._default_proxy + if proxy_auth is None: + proxy_auth = self._default_proxy_auth + + if proxy is None: + proxy_headers = None + else: + proxy_headers = self._prepare_headers(proxy_headers) + try: + proxy = URL(proxy) + except ValueError as e: + raise InvalidURL(proxy) from e + + if timeout is sentinel: + real_timeout: ClientTimeout = self._timeout + else: + if not isinstance(timeout, ClientTimeout): + real_timeout = ClientTimeout(total=timeout) + else: + real_timeout = timeout + # timeout is cumulative for all request operations + # (request, redirects, responses, data consuming) + tm = TimeoutHandle( + self._loop, real_timeout.total, ceil_threshold=real_timeout.ceil_threshold + ) + handle = tm.start() + + if read_bufsize is None: + read_bufsize = self._read_bufsize + + if auto_decompress is None: + auto_decompress = self._auto_decompress + + if max_line_size is None: + max_line_size = self._max_line_size + + if max_field_size is None: + max_field_size = self._max_field_size + + traces = [ + Trace( + self, + trace_config, + trace_config.trace_config_ctx(trace_request_ctx=trace_request_ctx), + ) + for trace_config in self._trace_configs + ] + + for trace in traces: + await trace.send_request_start(method, url.update_query(params), headers) + + timer = tm.timer() + try: + with timer: + # https://www.rfc-editor.org/rfc/rfc9112.html#name-retrying-requests + retry_persistent_connection = ( + self._retry_connection and method in IDEMPOTENT_METHODS + ) + while True: + url, auth_from_url = strip_auth_from_url(url) + if not url.raw_host: + # NOTE: Bail early, otherwise, causes `InvalidURL` through + # NOTE: `self._request_class()` below. + err_exc_cls = ( + InvalidUrlRedirectClientError + if redirects + else InvalidUrlClientError + ) + raise err_exc_cls(url) + # If `auth` was passed for an already authenticated URL, + # disallow only if this is the initial URL; this is to avoid issues + # with sketchy redirects that are not the caller's responsibility + if not history and (auth and auth_from_url): + raise ValueError( + "Cannot combine AUTH argument with " + "credentials encoded in URL" + ) + + # Override the auth with the one from the URL only if we + # have no auth, or if we got an auth from a redirect URL + if auth is None or (history and auth_from_url is not None): + auth = auth_from_url + + if ( + auth is None + and self._default_auth + and ( + not self._base_url or self._base_url_origin == url.origin() + ) + ): + auth = self._default_auth + # It would be confusing if we support explicit + # Authorization header with auth argument + if ( + headers is not None + and auth is not None + and hdrs.AUTHORIZATION in headers + ): + raise ValueError( + "Cannot combine AUTHORIZATION header " + "with AUTH argument or credentials " + "encoded in URL" + ) + + all_cookies = self._cookie_jar.filter_cookies(url) + + if cookies is not None: + tmp_cookie_jar = CookieJar( + quote_cookie=self._cookie_jar.quote_cookie + ) + tmp_cookie_jar.update_cookies(cookies) + req_cookies = tmp_cookie_jar.filter_cookies(url) + if req_cookies: + all_cookies.load(req_cookies) + + proxy_: Optional[URL] = None + if proxy is not None: + proxy_ = URL(proxy) + elif self._trust_env: + with suppress(LookupError): + proxy_, proxy_auth = await asyncio.to_thread( + get_env_proxy_for_url, url + ) + + req = self._request_class( + method, + url, + params=params, + headers=headers, + skip_auto_headers=skip_headers, + data=data, + cookies=all_cookies, + auth=auth, + version=version, + compress=compress, + chunked=chunked, + expect100=expect100, + loop=self._loop, + response_class=self._response_class, + proxy=proxy_, + proxy_auth=proxy_auth, + timer=timer, + session=self, + ssl=ssl if ssl is not None else True, + server_hostname=server_hostname, + proxy_headers=proxy_headers, + traces=traces, + trust_env=self.trust_env, + ) + + async def _connect_and_send_request( + req: ClientRequest, + ) -> ClientResponse: + # connection timeout + assert self._connector is not None + try: + conn = await self._connector.connect( + req, traces=traces, timeout=real_timeout + ) + except asyncio.TimeoutError as exc: + raise ConnectionTimeoutError( + f"Connection timeout to host {req.url}" + ) from exc + + assert conn.protocol is not None + conn.protocol.set_response_params( + timer=timer, + skip_payload=req.method in EMPTY_BODY_METHODS, + read_until_eof=read_until_eof, + auto_decompress=auto_decompress, + read_timeout=real_timeout.sock_read, + read_bufsize=read_bufsize, + timeout_ceil_threshold=self._connector._timeout_ceil_threshold, + max_line_size=max_line_size, + max_field_size=max_field_size, + ) + try: + resp = await req.send(conn) + try: + await resp.start(conn) + except BaseException: + resp.close() + raise + except BaseException: + conn.close() + raise + return resp + + # Apply middleware (if any) - per-request middleware overrides session middleware + effective_middlewares = ( + self._middlewares if middlewares is None else middlewares + ) + + if effective_middlewares: + handler = build_client_middlewares( + _connect_and_send_request, effective_middlewares + ) + else: + handler = _connect_and_send_request + + try: + resp = await handler(req) + # Client connector errors should not be retried + except ( + ConnectionTimeoutError, + ClientConnectorError, + ClientConnectorCertificateError, + ClientConnectorSSLError, + ): + raise + except (ClientOSError, ServerDisconnectedError): + if retry_persistent_connection: + retry_persistent_connection = False + continue + raise + except ClientError: + raise + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise ClientOSError(*exc.args) from exc + + # Update cookies from raw headers to preserve duplicates + if resp._raw_cookie_headers: + self._cookie_jar.update_cookies_from_headers( + resp._raw_cookie_headers, resp.url + ) + + # redirects + if resp.status in (301, 302, 303, 307, 308) and allow_redirects: + + for trace in traces: + await trace.send_request_redirect( + method, url.update_query(params), headers, resp + ) + + redirects += 1 + history.append(resp) + if max_redirects and redirects >= max_redirects: + if req._body is not None: + await req._body.close() + resp.close() + raise TooManyRedirects( + history[0].request_info, tuple(history) + ) + + # For 301 and 302, mimic IE, now changed in RFC + # https://github.com/kennethreitz/requests/pull/269 + if (resp.status == 303 and resp.method != hdrs.METH_HEAD) or ( + resp.status in (301, 302) and resp.method == hdrs.METH_POST + ): + method = hdrs.METH_GET + data = None + if headers.get(hdrs.CONTENT_LENGTH): + headers.pop(hdrs.CONTENT_LENGTH) + else: + # For 307/308, always preserve the request body + # For 301/302 with non-POST methods, preserve the request body + # https://www.rfc-editor.org/rfc/rfc9110#section-15.4.3-3.1 + # Use the existing payload to avoid recreating it from a potentially consumed file + data = req._body + + r_url = resp.headers.get(hdrs.LOCATION) or resp.headers.get( + hdrs.URI + ) + if r_url is None: + # see github.com/aio-libs/aiohttp/issues/2022 + break + else: + # reading from correct redirection + # response is forbidden + resp.release() + + try: + parsed_redirect_url = URL( + r_url, encoded=not self._requote_redirect_url + ) + except ValueError as e: + if req._body is not None: + await req._body.close() + resp.close() + raise InvalidUrlRedirectClientError( + r_url, + "Server attempted redirecting to a location that does not look like a URL", + ) from e + + scheme = parsed_redirect_url.scheme + if scheme not in HTTP_AND_EMPTY_SCHEMA_SET: + if req._body is not None: + await req._body.close() + resp.close() + raise NonHttpUrlRedirectClientError(r_url) + elif not scheme: + parsed_redirect_url = url.join(parsed_redirect_url) + + try: + redirect_origin = parsed_redirect_url.origin() + except ValueError as origin_val_err: + if req._body is not None: + await req._body.close() + resp.close() + raise InvalidUrlRedirectClientError( + parsed_redirect_url, + "Invalid redirect URL origin", + ) from origin_val_err + + if url.origin() != redirect_origin: + auth = None + headers.pop(hdrs.AUTHORIZATION, None) + + url = parsed_redirect_url + params = {} + resp.release() + continue + + break + + if req._body is not None: + await req._body.close() + # check response status + if raise_for_status is None: + raise_for_status = self._raise_for_status + + if raise_for_status is None: + pass + elif callable(raise_for_status): + await raise_for_status(resp) + elif raise_for_status: + resp.raise_for_status() + + # register connection + if handle is not None: + if resp.connection is not None: + resp.connection.add_callback(handle.cancel) + else: + handle.cancel() + + resp._history = tuple(history) + + for trace in traces: + await trace.send_request_end( + method, url.update_query(params), headers, resp + ) + return resp + + except BaseException as e: + # cleanup timer + tm.close() + if handle: + handle.cancel() + handle = None + + for trace in traces: + await trace.send_request_exception( + method, url.update_query(params), headers, e + ) + raise + + def ws_connect( + self, + url: StrOrURL, + *, + method: str = hdrs.METH_GET, + protocols: Iterable[str] = (), + timeout: Union[ClientWSTimeout, _SENTINEL] = sentinel, + receive_timeout: Optional[float] = None, + autoclose: bool = True, + autoping: bool = True, + heartbeat: Optional[float] = None, + auth: Optional[BasicAuth] = None, + origin: Optional[str] = None, + params: Query = None, + headers: Optional[LooseHeaders] = None, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + verify_ssl: Optional[bool] = None, + fingerprint: Optional[bytes] = None, + ssl_context: Optional[SSLContext] = None, + server_hostname: Optional[str] = None, + proxy_headers: Optional[LooseHeaders] = None, + compress: int = 0, + max_msg_size: int = 4 * 1024 * 1024, + ) -> "_WSRequestContextManager": + """Initiate websocket connection.""" + return _WSRequestContextManager( + self._ws_connect( + url, + method=method, + protocols=protocols, + timeout=timeout, + receive_timeout=receive_timeout, + autoclose=autoclose, + autoping=autoping, + heartbeat=heartbeat, + auth=auth, + origin=origin, + params=params, + headers=headers, + proxy=proxy, + proxy_auth=proxy_auth, + ssl=ssl, + verify_ssl=verify_ssl, + fingerprint=fingerprint, + ssl_context=ssl_context, + server_hostname=server_hostname, + proxy_headers=proxy_headers, + compress=compress, + max_msg_size=max_msg_size, + ) + ) + + async def _ws_connect( + self, + url: StrOrURL, + *, + method: str = hdrs.METH_GET, + protocols: Iterable[str] = (), + timeout: Union[ClientWSTimeout, _SENTINEL] = sentinel, + receive_timeout: Optional[float] = None, + autoclose: bool = True, + autoping: bool = True, + heartbeat: Optional[float] = None, + auth: Optional[BasicAuth] = None, + origin: Optional[str] = None, + params: Query = None, + headers: Optional[LooseHeaders] = None, + proxy: Optional[StrOrURL] = None, + proxy_auth: Optional[BasicAuth] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + verify_ssl: Optional[bool] = None, + fingerprint: Optional[bytes] = None, + ssl_context: Optional[SSLContext] = None, + server_hostname: Optional[str] = None, + proxy_headers: Optional[LooseHeaders] = None, + compress: int = 0, + max_msg_size: int = 4 * 1024 * 1024, + ) -> ClientWebSocketResponse: + if timeout is not sentinel: + if isinstance(timeout, ClientWSTimeout): + ws_timeout = timeout + else: + warnings.warn( + "parameter 'timeout' of type 'float' " + "is deprecated, please use " + "'timeout=ClientWSTimeout(ws_close=...)'", + DeprecationWarning, + stacklevel=2, + ) + ws_timeout = ClientWSTimeout(ws_close=timeout) + else: + ws_timeout = DEFAULT_WS_CLIENT_TIMEOUT + if receive_timeout is not None: + warnings.warn( + "float parameter 'receive_timeout' " + "is deprecated, please use parameter " + "'timeout=ClientWSTimeout(ws_receive=...)'", + DeprecationWarning, + stacklevel=2, + ) + ws_timeout = attr.evolve(ws_timeout, ws_receive=receive_timeout) + + if headers is None: + real_headers: CIMultiDict[str] = CIMultiDict() + else: + real_headers = CIMultiDict(headers) + + default_headers = { + hdrs.UPGRADE: "websocket", + hdrs.CONNECTION: "Upgrade", + hdrs.SEC_WEBSOCKET_VERSION: "13", + } + + for key, value in default_headers.items(): + real_headers.setdefault(key, value) + + sec_key = base64.b64encode(os.urandom(16)) + real_headers[hdrs.SEC_WEBSOCKET_KEY] = sec_key.decode() + + if protocols: + real_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = ",".join(protocols) + if origin is not None: + real_headers[hdrs.ORIGIN] = origin + if compress: + extstr = ws_ext_gen(compress=compress) + real_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = extstr + + # For the sake of backward compatibility, if user passes in None, convert it to True + if ssl is None: + warnings.warn( + "ssl=None is deprecated, please use ssl=True", + DeprecationWarning, + stacklevel=2, + ) + ssl = True + ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) + + # send request + resp = await self.request( + method, + url, + params=params, + headers=real_headers, + read_until_eof=False, + auth=auth, + proxy=proxy, + proxy_auth=proxy_auth, + ssl=ssl, + server_hostname=server_hostname, + proxy_headers=proxy_headers, + ) + + try: + # check handshake + if resp.status != 101: + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid response status", + status=resp.status, + headers=resp.headers, + ) + + if resp.headers.get(hdrs.UPGRADE, "").lower() != "websocket": + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid upgrade header", + status=resp.status, + headers=resp.headers, + ) + + if resp.headers.get(hdrs.CONNECTION, "").lower() != "upgrade": + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid connection header", + status=resp.status, + headers=resp.headers, + ) + + # key calculation + r_key = resp.headers.get(hdrs.SEC_WEBSOCKET_ACCEPT, "") + match = base64.b64encode(hashlib.sha1(sec_key + WS_KEY).digest()).decode() + if r_key != match: + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message="Invalid challenge response", + status=resp.status, + headers=resp.headers, + ) + + # websocket protocol + protocol = None + if protocols and hdrs.SEC_WEBSOCKET_PROTOCOL in resp.headers: + resp_protocols = [ + proto.strip() + for proto in resp.headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",") + ] + + for proto in resp_protocols: + if proto in protocols: + protocol = proto + break + + # websocket compress + notakeover = False + if compress: + compress_hdrs = resp.headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS) + if compress_hdrs: + try: + compress, notakeover = ws_ext_parse(compress_hdrs) + except WSHandshakeError as exc: + raise WSServerHandshakeError( + resp.request_info, + resp.history, + message=exc.args[0], + status=resp.status, + headers=resp.headers, + ) from exc + else: + compress = 0 + notakeover = False + + conn = resp.connection + assert conn is not None + conn_proto = conn.protocol + assert conn_proto is not None + + # For WS connection the read_timeout must be either receive_timeout or greater + # None == no timeout, i.e. infinite timeout, so None is the max timeout possible + if ws_timeout.ws_receive is None: + # Reset regardless + conn_proto.read_timeout = None + elif conn_proto.read_timeout is not None: + conn_proto.read_timeout = max( + ws_timeout.ws_receive, conn_proto.read_timeout + ) + + transport = conn.transport + assert transport is not None + reader = WebSocketDataQueue(conn_proto, 2**16, loop=self._loop) + conn_proto.set_parser(WebSocketReader(reader, max_msg_size), reader) + writer = WebSocketWriter( + conn_proto, + transport, + use_mask=True, + compress=compress, + notakeover=notakeover, + ) + except BaseException: + resp.close() + raise + else: + return self._ws_response_class( + reader, + writer, + protocol, + resp, + ws_timeout, + autoclose, + autoping, + self._loop, + heartbeat=heartbeat, + compress=compress, + client_notakeover=notakeover, + ) + + def _prepare_headers(self, headers: Optional[LooseHeaders]) -> "CIMultiDict[str]": + """Add default headers and transform it to CIMultiDict""" + # Convert headers to MultiDict + result = CIMultiDict(self._default_headers) + if headers: + if not isinstance(headers, (MultiDictProxy, MultiDict)): + headers = CIMultiDict(headers) + added_names: Set[str] = set() + for key, value in headers.items(): + if key in added_names: + result.add(key, value) + else: + result[key] = value + added_names.add(key) + return result + + if sys.version_info >= (3, 11) and TYPE_CHECKING: + + def get( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def options( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def head( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def post( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def put( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def patch( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + def delete( + self, + url: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> "_RequestContextManager": ... + + else: + + def get( + self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP GET request.""" + return _RequestContextManager( + self._request( + hdrs.METH_GET, url, allow_redirects=allow_redirects, **kwargs + ) + ) + + def options( + self, url: StrOrURL, *, allow_redirects: bool = True, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP OPTIONS request.""" + return _RequestContextManager( + self._request( + hdrs.METH_OPTIONS, url, allow_redirects=allow_redirects, **kwargs + ) + ) + + def head( + self, url: StrOrURL, *, allow_redirects: bool = False, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP HEAD request.""" + return _RequestContextManager( + self._request( + hdrs.METH_HEAD, url, allow_redirects=allow_redirects, **kwargs + ) + ) + + def post( + self, url: StrOrURL, *, data: Any = None, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP POST request.""" + return _RequestContextManager( + self._request(hdrs.METH_POST, url, data=data, **kwargs) + ) + + def put( + self, url: StrOrURL, *, data: Any = None, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP PUT request.""" + return _RequestContextManager( + self._request(hdrs.METH_PUT, url, data=data, **kwargs) + ) + + def patch( + self, url: StrOrURL, *, data: Any = None, **kwargs: Any + ) -> "_RequestContextManager": + """Perform HTTP PATCH request.""" + return _RequestContextManager( + self._request(hdrs.METH_PATCH, url, data=data, **kwargs) + ) + + def delete(self, url: StrOrURL, **kwargs: Any) -> "_RequestContextManager": + """Perform HTTP DELETE request.""" + return _RequestContextManager( + self._request(hdrs.METH_DELETE, url, **kwargs) + ) + + async def close(self) -> None: + """Close underlying connector. + + Release all acquired resources. + """ + if not self.closed: + if self._connector is not None and self._connector_owner: + await self._connector.close() + self._connector = None + + @property + def closed(self) -> bool: + """Is client session closed. + + A readonly property. + """ + return self._connector is None or self._connector.closed + + @property + def connector(self) -> Optional[BaseConnector]: + """Connector instance used for the session.""" + return self._connector + + @property + def cookie_jar(self) -> AbstractCookieJar: + """The session cookies.""" + return self._cookie_jar + + @property + def version(self) -> Tuple[int, int]: + """The session HTTP protocol version.""" + return self._version + + @property + def requote_redirect_url(self) -> bool: + """Do URL requoting on redirection handling.""" + return self._requote_redirect_url + + @requote_redirect_url.setter + def requote_redirect_url(self, val: bool) -> None: + """Do URL requoting on redirection handling.""" + warnings.warn( + "session.requote_redirect_url modification is deprecated #2778", + DeprecationWarning, + stacklevel=2, + ) + self._requote_redirect_url = val + + @property + def loop(self) -> asyncio.AbstractEventLoop: + """Session's loop.""" + warnings.warn( + "client.loop property is deprecated", DeprecationWarning, stacklevel=2 + ) + return self._loop + + @property + def timeout(self) -> ClientTimeout: + """Timeout for the session.""" + return self._timeout + + @property + def headers(self) -> "CIMultiDict[str]": + """The default headers of the client session.""" + return self._default_headers + + @property + def skip_auto_headers(self) -> FrozenSet[istr]: + """Headers for which autogeneration should be skipped""" + return self._skip_auto_headers + + @property + def auth(self) -> Optional[BasicAuth]: + """An object that represents HTTP Basic Authorization""" + return self._default_auth + + @property + def json_serialize(self) -> JSONEncoder: + """Json serializer callable""" + return self._json_serialize + + @property + def connector_owner(self) -> bool: + """Should connector be closed on session closing""" + return self._connector_owner + + @property + def raise_for_status( + self, + ) -> Union[bool, Callable[[ClientResponse], Awaitable[None]]]: + """Should `ClientResponse.raise_for_status()` be called for each response.""" + return self._raise_for_status + + @property + def auto_decompress(self) -> bool: + """Should the body response be automatically decompressed.""" + return self._auto_decompress + + @property + def trust_env(self) -> bool: + """ + Should proxies information from environment or netrc be trusted. + + Information is from HTTP_PROXY / HTTPS_PROXY environment variables + or ~/.netrc file if present. + """ + return self._trust_env + + @property + def trace_configs(self) -> List[TraceConfig]: + """A list of TraceConfig instances used for client tracing""" + return self._trace_configs + + def detach(self) -> None: + """Detach connector from session without closing the former. + + Session is switched to closed state anyway. + """ + self._connector = None + + def __enter__(self) -> None: + raise TypeError("Use async with instead") + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + # __exit__ should exist in pair with __enter__ but never executed + pass # pragma: no cover + + async def __aenter__(self) -> "ClientSession": + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + await self.close() + + +class _BaseRequestContextManager(Coroutine[Any, Any, _RetType], Generic[_RetType]): + + __slots__ = ("_coro", "_resp") + + def __init__(self, coro: Coroutine["asyncio.Future[Any]", None, _RetType]) -> None: + self._coro: Coroutine["asyncio.Future[Any]", None, _RetType] = coro + + def send(self, arg: None) -> "asyncio.Future[Any]": + return self._coro.send(arg) + + def throw(self, *args: Any, **kwargs: Any) -> "asyncio.Future[Any]": + return self._coro.throw(*args, **kwargs) + + def close(self) -> None: + return self._coro.close() + + def __await__(self) -> Generator[Any, None, _RetType]: + ret = self._coro.__await__() + return ret + + def __iter__(self) -> Generator[Any, None, _RetType]: + return self.__await__() + + async def __aenter__(self) -> _RetType: + self._resp: _RetType = await self._coro + return await self._resp.__aenter__() + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + await self._resp.__aexit__(exc_type, exc, tb) + + +_RequestContextManager = _BaseRequestContextManager[ClientResponse] +_WSRequestContextManager = _BaseRequestContextManager[ClientWebSocketResponse] + + +class _SessionRequestContextManager: + + __slots__ = ("_coro", "_resp", "_session") + + def __init__( + self, + coro: Coroutine["asyncio.Future[Any]", None, ClientResponse], + session: ClientSession, + ) -> None: + self._coro = coro + self._resp: Optional[ClientResponse] = None + self._session = session + + async def __aenter__(self) -> ClientResponse: + try: + self._resp = await self._coro + except BaseException: + await self._session.close() + raise + else: + return self._resp + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + assert self._resp is not None + self._resp.close() + await self._session.close() + + +if sys.version_info >= (3, 11) and TYPE_CHECKING: + + def request( + method: str, + url: StrOrURL, + *, + version: HttpVersion = http.HttpVersion11, + connector: Optional[BaseConnector] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + **kwargs: Unpack[_RequestOptions], + ) -> _SessionRequestContextManager: ... + +else: + + def request( + method: str, + url: StrOrURL, + *, + version: HttpVersion = http.HttpVersion11, + connector: Optional[BaseConnector] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + **kwargs: Any, + ) -> _SessionRequestContextManager: + """Constructs and sends a request. + + Returns response object. + method - HTTP method + url - request url + params - (optional) Dictionary or bytes to be sent in the query + string of the new request + data - (optional) Dictionary, bytes, or file-like object to + send in the body of the request + json - (optional) Any json compatible python object + headers - (optional) Dictionary of HTTP Headers to send with + the request + cookies - (optional) Dict object to send with the request + auth - (optional) BasicAuth named tuple represent HTTP Basic Auth + auth - aiohttp.helpers.BasicAuth + allow_redirects - (optional) If set to False, do not follow + redirects + version - Request HTTP version. + compress - Set to True if request has to be compressed + with deflate encoding. + chunked - Set to chunk size for chunked transfer encoding. + expect100 - Expect 100-continue response from server. + connector - BaseConnector sub-class instance to support + connection pooling. + read_until_eof - Read response until eof if response + does not have Content-Length header. + loop - Optional event loop. + timeout - Optional ClientTimeout settings structure, 5min + total timeout by default. + Usage:: + >>> import aiohttp + >>> async with aiohttp.request('GET', 'http://python.org/') as resp: + ... print(resp) + ... data = await resp.read() + + """ + connector_owner = False + if connector is None: + connector_owner = True + connector = TCPConnector(loop=loop, force_close=True) + + session = ClientSession( + loop=loop, + cookies=kwargs.pop("cookies", None), + version=version, + timeout=kwargs.pop("timeout", sentinel), + connector=connector, + connector_owner=connector_owner, + ) + + return _SessionRequestContextManager( + session._request(method, url, **kwargs), + session, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_exceptions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..1d298e9a8cf663cdc8a85d3b7d1f9264ff5e03c9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_exceptions.py @@ -0,0 +1,421 @@ +"""HTTP related errors.""" + +import asyncio +import warnings +from typing import TYPE_CHECKING, Optional, Tuple, Union + +from multidict import MultiMapping + +from .typedefs import StrOrURL + +if TYPE_CHECKING: + import ssl + + SSLContext = ssl.SSLContext +else: + try: + import ssl + + SSLContext = ssl.SSLContext + except ImportError: # pragma: no cover + ssl = SSLContext = None # type: ignore[assignment] + +if TYPE_CHECKING: + from .client_reqrep import ClientResponse, ConnectionKey, Fingerprint, RequestInfo + from .http_parser import RawResponseMessage +else: + RequestInfo = ClientResponse = ConnectionKey = RawResponseMessage = None + +__all__ = ( + "ClientError", + "ClientConnectionError", + "ClientConnectionResetError", + "ClientOSError", + "ClientConnectorError", + "ClientProxyConnectionError", + "ClientSSLError", + "ClientConnectorDNSError", + "ClientConnectorSSLError", + "ClientConnectorCertificateError", + "ConnectionTimeoutError", + "SocketTimeoutError", + "ServerConnectionError", + "ServerTimeoutError", + "ServerDisconnectedError", + "ServerFingerprintMismatch", + "ClientResponseError", + "ClientHttpProxyError", + "WSServerHandshakeError", + "ContentTypeError", + "ClientPayloadError", + "InvalidURL", + "InvalidUrlClientError", + "RedirectClientError", + "NonHttpUrlClientError", + "InvalidUrlRedirectClientError", + "NonHttpUrlRedirectClientError", + "WSMessageTypeError", +) + + +class ClientError(Exception): + """Base class for client connection errors.""" + + +class ClientResponseError(ClientError): + """Base class for exceptions that occur after getting a response. + + request_info: An instance of RequestInfo. + history: A sequence of responses, if redirects occurred. + status: HTTP status code. + message: Error message. + headers: Response headers. + """ + + def __init__( + self, + request_info: RequestInfo, + history: Tuple[ClientResponse, ...], + *, + code: Optional[int] = None, + status: Optional[int] = None, + message: str = "", + headers: Optional[MultiMapping[str]] = None, + ) -> None: + self.request_info = request_info + if code is not None: + if status is not None: + raise ValueError( + "Both code and status arguments are provided; " + "code is deprecated, use status instead" + ) + warnings.warn( + "code argument is deprecated, use status instead", + DeprecationWarning, + stacklevel=2, + ) + if status is not None: + self.status = status + elif code is not None: + self.status = code + else: + self.status = 0 + self.message = message + self.headers = headers + self.history = history + self.args = (request_info, history) + + def __str__(self) -> str: + return "{}, message={!r}, url={!r}".format( + self.status, + self.message, + str(self.request_info.real_url), + ) + + def __repr__(self) -> str: + args = f"{self.request_info!r}, {self.history!r}" + if self.status != 0: + args += f", status={self.status!r}" + if self.message != "": + args += f", message={self.message!r}" + if self.headers is not None: + args += f", headers={self.headers!r}" + return f"{type(self).__name__}({args})" + + @property + def code(self) -> int: + warnings.warn( + "code property is deprecated, use status instead", + DeprecationWarning, + stacklevel=2, + ) + return self.status + + @code.setter + def code(self, value: int) -> None: + warnings.warn( + "code property is deprecated, use status instead", + DeprecationWarning, + stacklevel=2, + ) + self.status = value + + +class ContentTypeError(ClientResponseError): + """ContentType found is not valid.""" + + +class WSServerHandshakeError(ClientResponseError): + """websocket server handshake error.""" + + +class ClientHttpProxyError(ClientResponseError): + """HTTP proxy error. + + Raised in :class:`aiohttp.connector.TCPConnector` if + proxy responds with status other than ``200 OK`` + on ``CONNECT`` request. + """ + + +class TooManyRedirects(ClientResponseError): + """Client was redirected too many times.""" + + +class ClientConnectionError(ClientError): + """Base class for client socket errors.""" + + +class ClientConnectionResetError(ClientConnectionError, ConnectionResetError): + """ConnectionResetError""" + + +class ClientOSError(ClientConnectionError, OSError): + """OSError error.""" + + +class ClientConnectorError(ClientOSError): + """Client connector error. + + Raised in :class:`aiohttp.connector.TCPConnector` if + a connection can not be established. + """ + + def __init__(self, connection_key: ConnectionKey, os_error: OSError) -> None: + self._conn_key = connection_key + self._os_error = os_error + super().__init__(os_error.errno, os_error.strerror) + self.args = (connection_key, os_error) + + @property + def os_error(self) -> OSError: + return self._os_error + + @property + def host(self) -> str: + return self._conn_key.host + + @property + def port(self) -> Optional[int]: + return self._conn_key.port + + @property + def ssl(self) -> Union[SSLContext, bool, "Fingerprint"]: + return self._conn_key.ssl + + def __str__(self) -> str: + return "Cannot connect to host {0.host}:{0.port} ssl:{1} [{2}]".format( + self, "default" if self.ssl is True else self.ssl, self.strerror + ) + + # OSError.__reduce__ does too much black magick + __reduce__ = BaseException.__reduce__ + + +class ClientConnectorDNSError(ClientConnectorError): + """DNS resolution failed during client connection. + + Raised in :class:`aiohttp.connector.TCPConnector` if + DNS resolution fails. + """ + + +class ClientProxyConnectionError(ClientConnectorError): + """Proxy connection error. + + Raised in :class:`aiohttp.connector.TCPConnector` if + connection to proxy can not be established. + """ + + +class UnixClientConnectorError(ClientConnectorError): + """Unix connector error. + + Raised in :py:class:`aiohttp.connector.UnixConnector` + if connection to unix socket can not be established. + """ + + def __init__( + self, path: str, connection_key: ConnectionKey, os_error: OSError + ) -> None: + self._path = path + super().__init__(connection_key, os_error) + + @property + def path(self) -> str: + return self._path + + def __str__(self) -> str: + return "Cannot connect to unix socket {0.path} ssl:{1} [{2}]".format( + self, "default" if self.ssl is True else self.ssl, self.strerror + ) + + +class ServerConnectionError(ClientConnectionError): + """Server connection errors.""" + + +class ServerDisconnectedError(ServerConnectionError): + """Server disconnected.""" + + def __init__(self, message: Union[RawResponseMessage, str, None] = None) -> None: + if message is None: + message = "Server disconnected" + + self.args = (message,) + self.message = message + + +class ServerTimeoutError(ServerConnectionError, asyncio.TimeoutError): + """Server timeout error.""" + + +class ConnectionTimeoutError(ServerTimeoutError): + """Connection timeout error.""" + + +class SocketTimeoutError(ServerTimeoutError): + """Socket timeout error.""" + + +class ServerFingerprintMismatch(ServerConnectionError): + """SSL certificate does not match expected fingerprint.""" + + def __init__(self, expected: bytes, got: bytes, host: str, port: int) -> None: + self.expected = expected + self.got = got + self.host = host + self.port = port + self.args = (expected, got, host, port) + + def __repr__(self) -> str: + return "<{} expected={!r} got={!r} host={!r} port={!r}>".format( + self.__class__.__name__, self.expected, self.got, self.host, self.port + ) + + +class ClientPayloadError(ClientError): + """Response payload error.""" + + +class InvalidURL(ClientError, ValueError): + """Invalid URL. + + URL used for fetching is malformed, e.g. it doesn't contains host + part. + """ + + # Derive from ValueError for backward compatibility + + def __init__(self, url: StrOrURL, description: Union[str, None] = None) -> None: + # The type of url is not yarl.URL because the exception can be raised + # on URL(url) call + self._url = url + self._description = description + + if description: + super().__init__(url, description) + else: + super().__init__(url) + + @property + def url(self) -> StrOrURL: + return self._url + + @property + def description(self) -> "str | None": + return self._description + + def __repr__(self) -> str: + return f"<{self.__class__.__name__} {self}>" + + def __str__(self) -> str: + if self._description: + return f"{self._url} - {self._description}" + return str(self._url) + + +class InvalidUrlClientError(InvalidURL): + """Invalid URL client error.""" + + +class RedirectClientError(ClientError): + """Client redirect error.""" + + +class NonHttpUrlClientError(ClientError): + """Non http URL client error.""" + + +class InvalidUrlRedirectClientError(InvalidUrlClientError, RedirectClientError): + """Invalid URL redirect client error.""" + + +class NonHttpUrlRedirectClientError(NonHttpUrlClientError, RedirectClientError): + """Non http URL redirect client error.""" + + +class ClientSSLError(ClientConnectorError): + """Base error for ssl.*Errors.""" + + +if ssl is not None: + cert_errors = (ssl.CertificateError,) + cert_errors_bases = ( + ClientSSLError, + ssl.CertificateError, + ) + + ssl_errors = (ssl.SSLError,) + ssl_error_bases = (ClientSSLError, ssl.SSLError) +else: # pragma: no cover + cert_errors = tuple() + cert_errors_bases = ( + ClientSSLError, + ValueError, + ) + + ssl_errors = tuple() + ssl_error_bases = (ClientSSLError,) + + +class ClientConnectorSSLError(*ssl_error_bases): # type: ignore[misc] + """Response ssl error.""" + + +class ClientConnectorCertificateError(*cert_errors_bases): # type: ignore[misc] + """Response certificate error.""" + + def __init__( + self, connection_key: ConnectionKey, certificate_error: Exception + ) -> None: + self._conn_key = connection_key + self._certificate_error = certificate_error + self.args = (connection_key, certificate_error) + + @property + def certificate_error(self) -> Exception: + return self._certificate_error + + @property + def host(self) -> str: + return self._conn_key.host + + @property + def port(self) -> Optional[int]: + return self._conn_key.port + + @property + def ssl(self) -> bool: + return self._conn_key.is_ssl + + def __str__(self) -> str: + return ( + "Cannot connect to host {0.host}:{0.port} ssl:{0.ssl} " + "[{0.certificate_error.__class__.__name__}: " + "{0.certificate_error.args}]".format(self) + ) + + +class WSMessageTypeError(TypeError): + """WebSocket message type is not valid.""" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_middleware_digest_auth.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_middleware_digest_auth.py new file mode 100644 index 0000000000000000000000000000000000000000..35f462f180be54030066b4e73dcadf02a882bc7e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_middleware_digest_auth.py @@ -0,0 +1,474 @@ +""" +Digest authentication middleware for aiohttp client. + +This middleware implements HTTP Digest Authentication according to RFC 7616, +providing a more secure alternative to Basic Authentication. It supports all +standard hash algorithms including MD5, SHA, SHA-256, SHA-512 and their session +variants, as well as both 'auth' and 'auth-int' quality of protection (qop) options. +""" + +import hashlib +import os +import re +import time +from typing import ( + Callable, + Dict, + Final, + FrozenSet, + List, + Literal, + Tuple, + TypedDict, + Union, +) + +from yarl import URL + +from . import hdrs +from .client_exceptions import ClientError +from .client_middlewares import ClientHandlerType +from .client_reqrep import ClientRequest, ClientResponse +from .payload import Payload + + +class DigestAuthChallenge(TypedDict, total=False): + realm: str + nonce: str + qop: str + algorithm: str + opaque: str + domain: str + stale: str + + +DigestFunctions: Dict[str, Callable[[bytes], "hashlib._Hash"]] = { + "MD5": hashlib.md5, + "MD5-SESS": hashlib.md5, + "SHA": hashlib.sha1, + "SHA-SESS": hashlib.sha1, + "SHA256": hashlib.sha256, + "SHA256-SESS": hashlib.sha256, + "SHA-256": hashlib.sha256, + "SHA-256-SESS": hashlib.sha256, + "SHA512": hashlib.sha512, + "SHA512-SESS": hashlib.sha512, + "SHA-512": hashlib.sha512, + "SHA-512-SESS": hashlib.sha512, +} + + +# Compile the regex pattern once at module level for performance +_HEADER_PAIRS_PATTERN = re.compile( + r'(\w+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))' + # | | | | | | | | | || | + # +----|--|-|-|--|----|------|----|--||-----|--> alphanumeric key + # +--|-|-|--|----|------|----|--||-----|--> maybe whitespace + # | | | | | | | || | + # +-|-|--|----|------|----|--||-----|--> = (delimiter) + # +-|--|----|------|----|--||-----|--> maybe whitespace + # | | | | | || | + # +--|----|------|----|--||-----|--> group quoted or unquoted + # | | | | || | + # +----|------|----|--||-----|--> if quoted... + # +------|----|--||-----|--> anything but " or \ + # +----|--||-----|--> escaped characters allowed + # +--||-----|--> or can be empty string + # || | + # +|-----|--> if unquoted... + # +-----|--> anything but , or + # +--> at least one char req'd +) + + +# RFC 7616: Challenge parameters to extract +CHALLENGE_FIELDS: Final[ + Tuple[ + Literal["realm", "nonce", "qop", "algorithm", "opaque", "domain", "stale"], ... + ] +] = ( + "realm", + "nonce", + "qop", + "algorithm", + "opaque", + "domain", + "stale", +) + +# Supported digest authentication algorithms +# Use a tuple of sorted keys for predictable documentation and error messages +SUPPORTED_ALGORITHMS: Final[Tuple[str, ...]] = tuple(sorted(DigestFunctions.keys())) + +# RFC 7616: Fields that require quoting in the Digest auth header +# These fields must be enclosed in double quotes in the Authorization header. +# Algorithm, qop, and nc are never quoted per RFC specifications. +# This frozen set is used by the template-based header construction to +# automatically determine which fields need quotes. +QUOTED_AUTH_FIELDS: Final[FrozenSet[str]] = frozenset( + {"username", "realm", "nonce", "uri", "response", "opaque", "cnonce"} +) + + +def escape_quotes(value: str) -> str: + """Escape double quotes for HTTP header values.""" + return value.replace('"', '\\"') + + +def unescape_quotes(value: str) -> str: + """Unescape double quotes in HTTP header values.""" + return value.replace('\\"', '"') + + +def parse_header_pairs(header: str) -> Dict[str, str]: + """ + Parse key-value pairs from WWW-Authenticate or similar HTTP headers. + + This function handles the complex format of WWW-Authenticate header values, + supporting both quoted and unquoted values, proper handling of commas in + quoted values, and whitespace variations per RFC 7616. + + Examples of supported formats: + - key1="value1", key2=value2 + - key1 = "value1" , key2="value, with, commas" + - key1=value1,key2="value2" + - realm="example.com", nonce="12345", qop="auth" + + Args: + header: The header value string to parse + + Returns: + Dictionary mapping parameter names to their values + """ + return { + stripped_key: unescape_quotes(quoted_val) if quoted_val else unquoted_val + for key, quoted_val, unquoted_val in _HEADER_PAIRS_PATTERN.findall(header) + if (stripped_key := key.strip()) + } + + +class DigestAuthMiddleware: + """ + HTTP digest authentication middleware for aiohttp client. + + This middleware intercepts 401 Unauthorized responses containing a Digest + authentication challenge, calculates the appropriate digest credentials, + and automatically retries the request with the proper Authorization header. + + Features: + - Handles all aspects of Digest authentication handshake automatically + - Supports all standard hash algorithms: + - MD5, MD5-SESS + - SHA, SHA-SESS + - SHA256, SHA256-SESS, SHA-256, SHA-256-SESS + - SHA512, SHA512-SESS, SHA-512, SHA-512-SESS + - Supports 'auth' and 'auth-int' quality of protection modes + - Properly handles quoted strings and parameter parsing + - Includes replay attack protection with client nonce count tracking + - Supports preemptive authentication per RFC 7616 Section 3.6 + + Standards compliance: + - RFC 7616: HTTP Digest Access Authentication (primary reference) + - RFC 2617: HTTP Authentication (deprecated by RFC 7616) + - RFC 1945: Section 11.1 (username restrictions) + + Implementation notes: + The core digest calculation is inspired by the implementation in + https://github.com/requests/requests/blob/v2.18.4/requests/auth.py + with added support for modern digest auth features and error handling. + """ + + def __init__( + self, + login: str, + password: str, + preemptive: bool = True, + ) -> None: + if login is None: + raise ValueError("None is not allowed as login value") + + if password is None: + raise ValueError("None is not allowed as password value") + + if ":" in login: + raise ValueError('A ":" is not allowed in username (RFC 1945#section-11.1)') + + self._login_str: Final[str] = login + self._login_bytes: Final[bytes] = login.encode("utf-8") + self._password_bytes: Final[bytes] = password.encode("utf-8") + + self._last_nonce_bytes = b"" + self._nonce_count = 0 + self._challenge: DigestAuthChallenge = {} + self._preemptive: bool = preemptive + # Set of URLs defining the protection space + self._protection_space: List[str] = [] + + async def _encode( + self, method: str, url: URL, body: Union[Payload, Literal[b""]] + ) -> str: + """ + Build digest authorization header for the current challenge. + + Args: + method: The HTTP method (GET, POST, etc.) + url: The request URL + body: The request body (used for qop=auth-int) + + Returns: + A fully formatted Digest authorization header string + + Raises: + ClientError: If the challenge is missing required parameters or + contains unsupported values + + """ + challenge = self._challenge + if "realm" not in challenge: + raise ClientError( + "Malformed Digest auth challenge: Missing 'realm' parameter" + ) + + if "nonce" not in challenge: + raise ClientError( + "Malformed Digest auth challenge: Missing 'nonce' parameter" + ) + + # Empty realm values are allowed per RFC 7616 (SHOULD, not MUST, contain host name) + realm = challenge["realm"] + nonce = challenge["nonce"] + + # Empty nonce values are not allowed as they are security-critical for replay protection + if not nonce: + raise ClientError( + "Security issue: Digest auth challenge contains empty 'nonce' value" + ) + + qop_raw = challenge.get("qop", "") + algorithm = challenge.get("algorithm", "MD5").upper() + opaque = challenge.get("opaque", "") + + # Convert string values to bytes once + nonce_bytes = nonce.encode("utf-8") + realm_bytes = realm.encode("utf-8") + path = URL(url).path_qs + + # Process QoP + qop = "" + qop_bytes = b"" + if qop_raw: + valid_qops = {"auth", "auth-int"}.intersection( + {q.strip() for q in qop_raw.split(",") if q.strip()} + ) + if not valid_qops: + raise ClientError( + f"Digest auth error: Unsupported Quality of Protection (qop) value(s): {qop_raw}" + ) + + qop = "auth-int" if "auth-int" in valid_qops else "auth" + qop_bytes = qop.encode("utf-8") + + if algorithm not in DigestFunctions: + raise ClientError( + f"Digest auth error: Unsupported hash algorithm: {algorithm}. " + f"Supported algorithms: {', '.join(SUPPORTED_ALGORITHMS)}" + ) + hash_fn: Final = DigestFunctions[algorithm] + + def H(x: bytes) -> bytes: + """RFC 7616 Section 3: Hash function H(data) = hex(hash(data)).""" + return hash_fn(x).hexdigest().encode() + + def KD(s: bytes, d: bytes) -> bytes: + """RFC 7616 Section 3: KD(secret, data) = H(concat(secret, ":", data)).""" + return H(b":".join((s, d))) + + # Calculate A1 and A2 + A1 = b":".join((self._login_bytes, realm_bytes, self._password_bytes)) + A2 = f"{method.upper()}:{path}".encode() + if qop == "auth-int": + if isinstance(body, Payload): # will always be empty bytes unless Payload + entity_bytes = await body.as_bytes() # Get bytes from Payload + else: + entity_bytes = body + entity_hash = H(entity_bytes) + A2 = b":".join((A2, entity_hash)) + + HA1 = H(A1) + HA2 = H(A2) + + # Nonce count handling + if nonce_bytes == self._last_nonce_bytes: + self._nonce_count += 1 + else: + self._nonce_count = 1 + + self._last_nonce_bytes = nonce_bytes + ncvalue = f"{self._nonce_count:08x}" + ncvalue_bytes = ncvalue.encode("utf-8") + + # Generate client nonce + cnonce = hashlib.sha1( + b"".join( + [ + str(self._nonce_count).encode("utf-8"), + nonce_bytes, + time.ctime().encode("utf-8"), + os.urandom(8), + ] + ) + ).hexdigest()[:16] + cnonce_bytes = cnonce.encode("utf-8") + + # Special handling for session-based algorithms + if algorithm.upper().endswith("-SESS"): + HA1 = H(b":".join((HA1, nonce_bytes, cnonce_bytes))) + + # Calculate the response digest + if qop: + noncebit = b":".join( + (nonce_bytes, ncvalue_bytes, cnonce_bytes, qop_bytes, HA2) + ) + response_digest = KD(HA1, noncebit) + else: + response_digest = KD(HA1, b":".join((nonce_bytes, HA2))) + + # Define a dict mapping of header fields to their values + # Group fields into always-present, optional, and qop-dependent + header_fields = { + # Always present fields + "username": escape_quotes(self._login_str), + "realm": escape_quotes(realm), + "nonce": escape_quotes(nonce), + "uri": path, + "response": response_digest.decode(), + "algorithm": algorithm, + } + + # Optional fields + if opaque: + header_fields["opaque"] = escape_quotes(opaque) + + # QoP-dependent fields + if qop: + header_fields["qop"] = qop + header_fields["nc"] = ncvalue + header_fields["cnonce"] = cnonce + + # Build header using templates for each field type + pairs: List[str] = [] + for field, value in header_fields.items(): + if field in QUOTED_AUTH_FIELDS: + pairs.append(f'{field}="{value}"') + else: + pairs.append(f"{field}={value}") + + return f"Digest {', '.join(pairs)}" + + def _in_protection_space(self, url: URL) -> bool: + """ + Check if the given URL is within the current protection space. + + According to RFC 7616, a URI is in the protection space if any URI + in the protection space is a prefix of it (after both have been made absolute). + """ + request_str = str(url) + for space_str in self._protection_space: + # Check if request starts with space URL + if not request_str.startswith(space_str): + continue + # Exact match or space ends with / (proper directory prefix) + if len(request_str) == len(space_str) or space_str[-1] == "/": + return True + # Check next char is / to ensure proper path boundary + if request_str[len(space_str)] == "/": + return True + return False + + def _authenticate(self, response: ClientResponse) -> bool: + """ + Takes the given response and tries digest-auth, if needed. + + Returns true if the original request must be resent. + """ + if response.status != 401: + return False + + auth_header = response.headers.get("www-authenticate", "") + if not auth_header: + return False # No authentication header present + + method, sep, headers = auth_header.partition(" ") + if not sep: + # No space found in www-authenticate header + return False # Malformed auth header, missing scheme separator + + if method.lower() != "digest": + # Not a digest auth challenge (could be Basic, Bearer, etc.) + return False + + if not headers: + # We have a digest scheme but no parameters + return False # Malformed digest header, missing parameters + + # We have a digest auth header with content + if not (header_pairs := parse_header_pairs(headers)): + # Failed to parse any key-value pairs + return False # Malformed digest header, no valid parameters + + # Extract challenge parameters + self._challenge = {} + for field in CHALLENGE_FIELDS: + if value := header_pairs.get(field): + self._challenge[field] = value + + # Update protection space based on domain parameter or default to origin + origin = response.url.origin() + + if domain := self._challenge.get("domain"): + # Parse space-separated list of URIs + self._protection_space = [] + for uri in domain.split(): + # Remove quotes if present + uri = uri.strip('"') + if uri.startswith("/"): + # Path-absolute, relative to origin + self._protection_space.append(str(origin.join(URL(uri)))) + else: + # Absolute URI + self._protection_space.append(str(URL(uri))) + else: + # No domain specified, protection space is entire origin + self._protection_space = [str(origin)] + + # Return True only if we found at least one challenge parameter + return bool(self._challenge) + + async def __call__( + self, request: ClientRequest, handler: ClientHandlerType + ) -> ClientResponse: + """Run the digest auth middleware.""" + response = None + for retry_count in range(2): + # Apply authorization header if: + # 1. This is a retry after 401 (retry_count > 0), OR + # 2. Preemptive auth is enabled AND we have a challenge AND the URL is in protection space + if retry_count > 0 or ( + self._preemptive + and self._challenge + and self._in_protection_space(request.url) + ): + request.headers[hdrs.AUTHORIZATION] = await self._encode( + request.method, request.url, request.body + ) + + # Send the request + response = await handler(request) + + # Check if we need to authenticate + if not self._authenticate(response): + break + + # At this point, response is guaranteed to be defined + assert response is not None + return response diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_middlewares.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_middlewares.py new file mode 100644 index 0000000000000000000000000000000000000000..3ca2cb202ad93963369f2a10fd1d118a194c4405 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_middlewares.py @@ -0,0 +1,55 @@ +"""Client middleware support.""" + +from collections.abc import Awaitable, Callable, Sequence + +from .client_reqrep import ClientRequest, ClientResponse + +__all__ = ("ClientMiddlewareType", "ClientHandlerType", "build_client_middlewares") + +# Type alias for client request handlers - functions that process requests and return responses +ClientHandlerType = Callable[[ClientRequest], Awaitable[ClientResponse]] + +# Type for client middleware - similar to server but uses ClientRequest/ClientResponse +ClientMiddlewareType = Callable[ + [ClientRequest, ClientHandlerType], Awaitable[ClientResponse] +] + + +def build_client_middlewares( + handler: ClientHandlerType, + middlewares: Sequence[ClientMiddlewareType], +) -> ClientHandlerType: + """ + Apply middlewares to request handler. + + The middlewares are applied in reverse order, so the first middleware + in the list wraps all subsequent middlewares and the handler. + + This implementation avoids using partial/update_wrapper to minimize overhead + and doesn't cache to avoid holding references to stateful middleware. + """ + # Optimize for single middleware case + if len(middlewares) == 1: + middleware = middlewares[0] + + async def single_middleware_handler(req: ClientRequest) -> ClientResponse: + return await middleware(req, handler) + + return single_middleware_handler + + # Build the chain for multiple middlewares + current_handler = handler + + for middleware in reversed(middlewares): + # Create a new closure that captures the current state + def make_wrapper( + mw: ClientMiddlewareType, next_h: ClientHandlerType + ) -> ClientHandlerType: + async def wrapped(req: ClientRequest) -> ClientResponse: + return await mw(req, next_h) + + return wrapped + + current_handler = make_wrapper(middleware, current_handler) + + return current_handler diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_proto.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_proto.py new file mode 100644 index 0000000000000000000000000000000000000000..e2fb1ce64cb6a39f5a72aecfd5840536defba519 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_proto.py @@ -0,0 +1,359 @@ +import asyncio +from contextlib import suppress +from typing import Any, Optional, Tuple, Union + +from .base_protocol import BaseProtocol +from .client_exceptions import ( + ClientConnectionError, + ClientOSError, + ClientPayloadError, + ServerDisconnectedError, + SocketTimeoutError, +) +from .helpers import ( + _EXC_SENTINEL, + EMPTY_BODY_STATUS_CODES, + BaseTimerContext, + set_exception, + set_result, +) +from .http import HttpResponseParser, RawResponseMessage +from .http_exceptions import HttpProcessingError +from .streams import EMPTY_PAYLOAD, DataQueue, StreamReader + + +class ResponseHandler(BaseProtocol, DataQueue[Tuple[RawResponseMessage, StreamReader]]): + """Helper class to adapt between Protocol and StreamReader.""" + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + BaseProtocol.__init__(self, loop=loop) + DataQueue.__init__(self, loop) + + self._should_close = False + + self._payload: Optional[StreamReader] = None + self._skip_payload = False + self._payload_parser = None + + self._timer = None + + self._tail = b"" + self._upgraded = False + self._parser: Optional[HttpResponseParser] = None + + self._read_timeout: Optional[float] = None + self._read_timeout_handle: Optional[asyncio.TimerHandle] = None + + self._timeout_ceil_threshold: Optional[float] = 5 + + self._closed: Union[None, asyncio.Future[None]] = None + self._connection_lost_called = False + + @property + def closed(self) -> Union[None, asyncio.Future[None]]: + """Future that is set when the connection is closed. + + This property returns a Future that will be completed when the connection + is closed. The Future is created lazily on first access to avoid creating + futures that will never be awaited. + + Returns: + - A Future[None] if the connection is still open or was closed after + this property was accessed + - None if connection_lost() was already called before this property + was ever accessed (indicating no one is waiting for the closure) + """ + if self._closed is None and not self._connection_lost_called: + self._closed = self._loop.create_future() + return self._closed + + @property + def upgraded(self) -> bool: + return self._upgraded + + @property + def should_close(self) -> bool: + return bool( + self._should_close + or (self._payload is not None and not self._payload.is_eof()) + or self._upgraded + or self._exception is not None + or self._payload_parser is not None + or self._buffer + or self._tail + ) + + def force_close(self) -> None: + self._should_close = True + + def close(self) -> None: + self._exception = None # Break cyclic references + transport = self.transport + if transport is not None: + transport.close() + self.transport = None + self._payload = None + self._drop_timeout() + + def abort(self) -> None: + self._exception = None # Break cyclic references + transport = self.transport + if transport is not None: + transport.abort() + self.transport = None + self._payload = None + self._drop_timeout() + + def is_connected(self) -> bool: + return self.transport is not None and not self.transport.is_closing() + + def connection_lost(self, exc: Optional[BaseException]) -> None: + self._connection_lost_called = True + self._drop_timeout() + + original_connection_error = exc + reraised_exc = original_connection_error + + connection_closed_cleanly = original_connection_error is None + + if self._closed is not None: + # If someone is waiting for the closed future, + # we should set it to None or an exception. If + # self._closed is None, it means that + # connection_lost() was called already + # or nobody is waiting for it. + if connection_closed_cleanly: + set_result(self._closed, None) + else: + assert original_connection_error is not None + set_exception( + self._closed, + ClientConnectionError( + f"Connection lost: {original_connection_error !s}", + ), + original_connection_error, + ) + + if self._payload_parser is not None: + with suppress(Exception): # FIXME: log this somehow? + self._payload_parser.feed_eof() + + uncompleted = None + if self._parser is not None: + try: + uncompleted = self._parser.feed_eof() + except Exception as underlying_exc: + if self._payload is not None: + client_payload_exc_msg = ( + f"Response payload is not completed: {underlying_exc !r}" + ) + if not connection_closed_cleanly: + client_payload_exc_msg = ( + f"{client_payload_exc_msg !s}. " + f"{original_connection_error !r}" + ) + set_exception( + self._payload, + ClientPayloadError(client_payload_exc_msg), + underlying_exc, + ) + + if not self.is_eof(): + if isinstance(original_connection_error, OSError): + reraised_exc = ClientOSError(*original_connection_error.args) + if connection_closed_cleanly: + reraised_exc = ServerDisconnectedError(uncompleted) + # assigns self._should_close to True as side effect, + # we do it anyway below + underlying_non_eof_exc = ( + _EXC_SENTINEL + if connection_closed_cleanly + else original_connection_error + ) + assert underlying_non_eof_exc is not None + assert reraised_exc is not None + self.set_exception(reraised_exc, underlying_non_eof_exc) + + self._should_close = True + self._parser = None + self._payload = None + self._payload_parser = None + self._reading_paused = False + + super().connection_lost(reraised_exc) + + def eof_received(self) -> None: + # should call parser.feed_eof() most likely + self._drop_timeout() + + def pause_reading(self) -> None: + super().pause_reading() + self._drop_timeout() + + def resume_reading(self) -> None: + super().resume_reading() + self._reschedule_timeout() + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + self._should_close = True + self._drop_timeout() + super().set_exception(exc, exc_cause) + + def set_parser(self, parser: Any, payload: Any) -> None: + # TODO: actual types are: + # parser: WebSocketReader + # payload: WebSocketDataQueue + # but they are not generi enough + # Need an ABC for both types + self._payload = payload + self._payload_parser = parser + + self._drop_timeout() + + if self._tail: + data, self._tail = self._tail, b"" + self.data_received(data) + + def set_response_params( + self, + *, + timer: Optional[BaseTimerContext] = None, + skip_payload: bool = False, + read_until_eof: bool = False, + auto_decompress: bool = True, + read_timeout: Optional[float] = None, + read_bufsize: int = 2**16, + timeout_ceil_threshold: float = 5, + max_line_size: int = 8190, + max_field_size: int = 8190, + ) -> None: + self._skip_payload = skip_payload + + self._read_timeout = read_timeout + + self._timeout_ceil_threshold = timeout_ceil_threshold + + self._parser = HttpResponseParser( + self, + self._loop, + read_bufsize, + timer=timer, + payload_exception=ClientPayloadError, + response_with_body=not skip_payload, + read_until_eof=read_until_eof, + auto_decompress=auto_decompress, + max_line_size=max_line_size, + max_field_size=max_field_size, + ) + + if self._tail: + data, self._tail = self._tail, b"" + self.data_received(data) + + def _drop_timeout(self) -> None: + if self._read_timeout_handle is not None: + self._read_timeout_handle.cancel() + self._read_timeout_handle = None + + def _reschedule_timeout(self) -> None: + timeout = self._read_timeout + if self._read_timeout_handle is not None: + self._read_timeout_handle.cancel() + + if timeout: + self._read_timeout_handle = self._loop.call_later( + timeout, self._on_read_timeout + ) + else: + self._read_timeout_handle = None + + def start_timeout(self) -> None: + self._reschedule_timeout() + + @property + def read_timeout(self) -> Optional[float]: + return self._read_timeout + + @read_timeout.setter + def read_timeout(self, read_timeout: Optional[float]) -> None: + self._read_timeout = read_timeout + + def _on_read_timeout(self) -> None: + exc = SocketTimeoutError("Timeout on reading data from socket") + self.set_exception(exc) + if self._payload is not None: + set_exception(self._payload, exc) + + def data_received(self, data: bytes) -> None: + self._reschedule_timeout() + + if not data: + return + + # custom payload parser - currently always WebSocketReader + if self._payload_parser is not None: + eof, tail = self._payload_parser.feed_data(data) + if eof: + self._payload = None + self._payload_parser = None + + if tail: + self.data_received(tail) + return + + if self._upgraded or self._parser is None: + # i.e. websocket connection, websocket parser is not set yet + self._tail += data + return + + # parse http messages + try: + messages, upgraded, tail = self._parser.feed_data(data) + except BaseException as underlying_exc: + if self.transport is not None: + # connection.release() could be called BEFORE + # data_received(), the transport is already + # closed in this case + self.transport.close() + # should_close is True after the call + if isinstance(underlying_exc, HttpProcessingError): + exc = HttpProcessingError( + code=underlying_exc.code, + message=underlying_exc.message, + headers=underlying_exc.headers, + ) + else: + exc = HttpProcessingError() + self.set_exception(exc, underlying_exc) + return + + self._upgraded = upgraded + + payload: Optional[StreamReader] = None + for message, payload in messages: + if message.should_close: + self._should_close = True + + self._payload = payload + + if self._skip_payload or message.code in EMPTY_BODY_STATUS_CODES: + self.feed_data((message, EMPTY_PAYLOAD), 0) + else: + self.feed_data((message, payload), 0) + + if payload is not None: + # new message(s) was processed + # register timeout handler unsubscribing + # either on end-of-stream or immediately for + # EMPTY_PAYLOAD + if payload is not EMPTY_PAYLOAD: + payload.on_eof(self._drop_timeout) + else: + self._drop_timeout() + + if upgraded and tail: + self.data_received(tail) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_reqrep.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_reqrep.py new file mode 100644 index 0000000000000000000000000000000000000000..3209440b53d7ab7b113f18d16645198720490f25 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_reqrep.py @@ -0,0 +1,1533 @@ +import asyncio +import codecs +import contextlib +import functools +import io +import re +import sys +import traceback +import warnings +from collections.abc import Mapping +from hashlib import md5, sha1, sha256 +from http.cookies import Morsel, SimpleCookie +from types import MappingProxyType, TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + List, + Literal, + NamedTuple, + Optional, + Tuple, + Type, + Union, +) + +import attr +from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy +from yarl import URL + +from . import hdrs, helpers, http, multipart, payload +from ._cookie_helpers import ( + parse_cookie_header, + parse_set_cookie_headers, + preserve_morsel_with_coded_value, +) +from .abc import AbstractStreamWriter +from .client_exceptions import ( + ClientConnectionError, + ClientOSError, + ClientResponseError, + ContentTypeError, + InvalidURL, + ServerFingerprintMismatch, +) +from .compression_utils import HAS_BROTLI +from .formdata import FormData +from .helpers import ( + _SENTINEL, + BaseTimerContext, + BasicAuth, + HeadersMixin, + TimerNoop, + basicauth_from_netrc, + netrc_from_env, + noop, + reify, + set_exception, + set_result, +) +from .http import ( + SERVER_SOFTWARE, + HttpVersion, + HttpVersion10, + HttpVersion11, + StreamWriter, +) +from .streams import StreamReader +from .typedefs import ( + DEFAULT_JSON_DECODER, + JSONDecoder, + LooseCookies, + LooseHeaders, + Query, + RawHeaders, +) + +if TYPE_CHECKING: + import ssl + from ssl import SSLContext +else: + try: + import ssl + from ssl import SSLContext + except ImportError: # pragma: no cover + ssl = None # type: ignore[assignment] + SSLContext = object # type: ignore[misc,assignment] + + +__all__ = ("ClientRequest", "ClientResponse", "RequestInfo", "Fingerprint") + + +if TYPE_CHECKING: + from .client import ClientSession + from .connector import Connection + from .tracing import Trace + + +_CONNECTION_CLOSED_EXCEPTION = ClientConnectionError("Connection closed") +_CONTAINS_CONTROL_CHAR_RE = re.compile(r"[^-!#$%&'*+.^_`|~0-9a-zA-Z]") +json_re = re.compile(r"^application/(?:[\w.+-]+?\+)?json") + + +def _gen_default_accept_encoding() -> str: + return "gzip, deflate, br" if HAS_BROTLI else "gzip, deflate" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ContentDisposition: + type: Optional[str] + parameters: "MappingProxyType[str, str]" + filename: Optional[str] + + +class _RequestInfo(NamedTuple): + url: URL + method: str + headers: "CIMultiDictProxy[str]" + real_url: URL + + +class RequestInfo(_RequestInfo): + + def __new__( + cls, + url: URL, + method: str, + headers: "CIMultiDictProxy[str]", + real_url: URL = _SENTINEL, # type: ignore[assignment] + ) -> "RequestInfo": + """Create a new RequestInfo instance. + + For backwards compatibility, the real_url parameter is optional. + """ + return tuple.__new__( + cls, (url, method, headers, url if real_url is _SENTINEL else real_url) + ) + + +class Fingerprint: + HASHFUNC_BY_DIGESTLEN = { + 16: md5, + 20: sha1, + 32: sha256, + } + + def __init__(self, fingerprint: bytes) -> None: + digestlen = len(fingerprint) + hashfunc = self.HASHFUNC_BY_DIGESTLEN.get(digestlen) + if not hashfunc: + raise ValueError("fingerprint has invalid length") + elif hashfunc is md5 or hashfunc is sha1: + raise ValueError("md5 and sha1 are insecure and not supported. Use sha256.") + self._hashfunc = hashfunc + self._fingerprint = fingerprint + + @property + def fingerprint(self) -> bytes: + return self._fingerprint + + def check(self, transport: asyncio.Transport) -> None: + if not transport.get_extra_info("sslcontext"): + return + sslobj = transport.get_extra_info("ssl_object") + cert = sslobj.getpeercert(binary_form=True) + got = self._hashfunc(cert).digest() + if got != self._fingerprint: + host, port, *_ = transport.get_extra_info("peername") + raise ServerFingerprintMismatch(self._fingerprint, got, host, port) + + +if ssl is not None: + SSL_ALLOWED_TYPES = (ssl.SSLContext, bool, Fingerprint, type(None)) +else: # pragma: no cover + SSL_ALLOWED_TYPES = (bool, type(None)) + + +def _merge_ssl_params( + ssl: Union["SSLContext", bool, Fingerprint], + verify_ssl: Optional[bool], + ssl_context: Optional["SSLContext"], + fingerprint: Optional[bytes], +) -> Union["SSLContext", bool, Fingerprint]: + if ssl is None: + ssl = True # Double check for backwards compatibility + if verify_ssl is not None and not verify_ssl: + warnings.warn( + "verify_ssl is deprecated, use ssl=False instead", + DeprecationWarning, + stacklevel=3, + ) + if ssl is not True: + raise ValueError( + "verify_ssl, ssl_context, fingerprint and ssl " + "parameters are mutually exclusive" + ) + else: + ssl = False + if ssl_context is not None: + warnings.warn( + "ssl_context is deprecated, use ssl=context instead", + DeprecationWarning, + stacklevel=3, + ) + if ssl is not True: + raise ValueError( + "verify_ssl, ssl_context, fingerprint and ssl " + "parameters are mutually exclusive" + ) + else: + ssl = ssl_context + if fingerprint is not None: + warnings.warn( + "fingerprint is deprecated, use ssl=Fingerprint(fingerprint) instead", + DeprecationWarning, + stacklevel=3, + ) + if ssl is not True: + raise ValueError( + "verify_ssl, ssl_context, fingerprint and ssl " + "parameters are mutually exclusive" + ) + else: + ssl = Fingerprint(fingerprint) + if not isinstance(ssl, SSL_ALLOWED_TYPES): + raise TypeError( + "ssl should be SSLContext, bool, Fingerprint or None, " + "got {!r} instead.".format(ssl) + ) + return ssl + + +_SSL_SCHEMES = frozenset(("https", "wss")) + + +# ConnectionKey is a NamedTuple because it is used as a key in a dict +# and a set in the connector. Since a NamedTuple is a tuple it uses +# the fast native tuple __hash__ and __eq__ implementation in CPython. +class ConnectionKey(NamedTuple): + # the key should contain an information about used proxy / TLS + # to prevent reusing wrong connections from a pool + host: str + port: Optional[int] + is_ssl: bool + ssl: Union[SSLContext, bool, Fingerprint] + proxy: Optional[URL] + proxy_auth: Optional[BasicAuth] + proxy_headers_hash: Optional[int] # hash(CIMultiDict) + + +def _is_expected_content_type( + response_content_type: str, expected_content_type: str +) -> bool: + if expected_content_type == "application/json": + return json_re.match(response_content_type) is not None + return expected_content_type in response_content_type + + +def _warn_if_unclosed_payload(payload: payload.Payload, stacklevel: int = 2) -> None: + """Warn if the payload is not closed. + + Callers must check that the body is a Payload before calling this method. + + Args: + payload: The payload to check + stacklevel: Stack level for the warning (default 2 for direct callers) + """ + if not payload.autoclose and not payload.consumed: + warnings.warn( + "The previous request body contains unclosed resources. " + "Use await request.update_body() instead of setting request.body " + "directly to properly close resources and avoid leaks.", + ResourceWarning, + stacklevel=stacklevel, + ) + + +class ClientResponse(HeadersMixin): + + # Some of these attributes are None when created, + # but will be set by the start() method. + # As the end user will likely never see the None values, we cheat the types below. + # from the Status-Line of the response + version: Optional[HttpVersion] = None # HTTP-Version + status: int = None # type: ignore[assignment] # Status-Code + reason: Optional[str] = None # Reason-Phrase + + content: StreamReader = None # type: ignore[assignment] # Payload stream + _body: Optional[bytes] = None + _headers: CIMultiDictProxy[str] = None # type: ignore[assignment] + _history: Tuple["ClientResponse", ...] = () + _raw_headers: RawHeaders = None # type: ignore[assignment] + + _connection: Optional["Connection"] = None # current connection + _cookies: Optional[SimpleCookie] = None + _raw_cookie_headers: Optional[Tuple[str, ...]] = None + _continue: Optional["asyncio.Future[bool]"] = None + _source_traceback: Optional[traceback.StackSummary] = None + _session: Optional["ClientSession"] = None + # set up by ClientRequest after ClientResponse object creation + # post-init stage allows to not change ctor signature + _closed = True # to allow __del__ for non-initialized properly response + _released = False + _in_context = False + + _resolve_charset: Callable[["ClientResponse", bytes], str] = lambda *_: "utf-8" + + __writer: Optional["asyncio.Task[None]"] = None + + def __init__( + self, + method: str, + url: URL, + *, + writer: "Optional[asyncio.Task[None]]", + continue100: Optional["asyncio.Future[bool]"], + timer: BaseTimerContext, + request_info: RequestInfo, + traces: List["Trace"], + loop: asyncio.AbstractEventLoop, + session: "ClientSession", + ) -> None: + # URL forbids subclasses, so a simple type check is enough. + assert type(url) is URL + + self.method = method + + self._real_url = url + self._url = url.with_fragment(None) if url.raw_fragment else url + if writer is not None: + self._writer = writer + if continue100 is not None: + self._continue = continue100 + self._request_info = request_info + self._timer = timer if timer is not None else TimerNoop() + self._cache: Dict[str, Any] = {} + self._traces = traces + self._loop = loop + # Save reference to _resolve_charset, so that get_encoding() will still + # work after the response has finished reading the body. + # TODO: Fix session=None in tests (see ClientRequest.__init__). + if session is not None: + # store a reference to session #1985 + self._session = session + self._resolve_charset = session._resolve_charset + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + def __reset_writer(self, _: object = None) -> None: + self.__writer = None + + @property + def _writer(self) -> Optional["asyncio.Task[None]"]: + """The writer task for streaming data. + + _writer is only provided for backwards compatibility + for subclasses that may need to access it. + """ + return self.__writer + + @_writer.setter + def _writer(self, writer: Optional["asyncio.Task[None]"]) -> None: + """Set the writer task for streaming data.""" + if self.__writer is not None: + self.__writer.remove_done_callback(self.__reset_writer) + self.__writer = writer + if writer is None: + return + if writer.done(): + # The writer is already done, so we can clear it immediately. + self.__writer = None + else: + writer.add_done_callback(self.__reset_writer) + + @property + def cookies(self) -> SimpleCookie: + if self._cookies is None: + if self._raw_cookie_headers is not None: + # Parse cookies for response.cookies (SimpleCookie for backward compatibility) + cookies = SimpleCookie() + # Use parse_set_cookie_headers for more lenient parsing that handles + # malformed cookies better than SimpleCookie.load + cookies.update(parse_set_cookie_headers(self._raw_cookie_headers)) + self._cookies = cookies + else: + self._cookies = SimpleCookie() + return self._cookies + + @cookies.setter + def cookies(self, cookies: SimpleCookie) -> None: + self._cookies = cookies + # Generate raw cookie headers from the SimpleCookie + if cookies: + self._raw_cookie_headers = tuple( + morsel.OutputString() for morsel in cookies.values() + ) + else: + self._raw_cookie_headers = None + + @reify + def url(self) -> URL: + return self._url + + @reify + def url_obj(self) -> URL: + warnings.warn("Deprecated, use .url #1654", DeprecationWarning, stacklevel=2) + return self._url + + @reify + def real_url(self) -> URL: + return self._real_url + + @reify + def host(self) -> str: + assert self._url.host is not None + return self._url.host + + @reify + def headers(self) -> "CIMultiDictProxy[str]": + return self._headers + + @reify + def raw_headers(self) -> RawHeaders: + return self._raw_headers + + @reify + def request_info(self) -> RequestInfo: + return self._request_info + + @reify + def content_disposition(self) -> Optional[ContentDisposition]: + raw = self._headers.get(hdrs.CONTENT_DISPOSITION) + if raw is None: + return None + disposition_type, params_dct = multipart.parse_content_disposition(raw) + params = MappingProxyType(params_dct) + filename = multipart.content_disposition_filename(params) + return ContentDisposition(disposition_type, params, filename) + + def __del__(self, _warnings: Any = warnings) -> None: + if self._closed: + return + + if self._connection is not None: + self._connection.release() + self._cleanup_writer() + + if self._loop.get_debug(): + kwargs = {"source": self} + _warnings.warn(f"Unclosed response {self!r}", ResourceWarning, **kwargs) + context = {"client_response": self, "message": "Unclosed response"} + if self._source_traceback: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + def __repr__(self) -> str: + out = io.StringIO() + ascii_encodable_url = str(self.url) + if self.reason: + ascii_encodable_reason = self.reason.encode( + "ascii", "backslashreplace" + ).decode("ascii") + else: + ascii_encodable_reason = "None" + print( + "".format( + ascii_encodable_url, self.status, ascii_encodable_reason + ), + file=out, + ) + print(self.headers, file=out) + return out.getvalue() + + @property + def connection(self) -> Optional["Connection"]: + return self._connection + + @reify + def history(self) -> Tuple["ClientResponse", ...]: + """A sequence of of responses, if redirects occurred.""" + return self._history + + @reify + def links(self) -> "MultiDictProxy[MultiDictProxy[Union[str, URL]]]": + links_str = ", ".join(self.headers.getall("link", [])) + + if not links_str: + return MultiDictProxy(MultiDict()) + + links: MultiDict[MultiDictProxy[Union[str, URL]]] = MultiDict() + + for val in re.split(r",(?=\s*<)", links_str): + match = re.match(r"\s*<(.*)>(.*)", val) + if match is None: # pragma: no cover + # the check exists to suppress mypy error + continue + url, params_str = match.groups() + params = params_str.split(";")[1:] + + link: MultiDict[Union[str, URL]] = MultiDict() + + for param in params: + match = re.match(r"^\s*(\S*)\s*=\s*(['\"]?)(.*?)(\2)\s*$", param, re.M) + if match is None: # pragma: no cover + # the check exists to suppress mypy error + continue + key, _, value, _ = match.groups() + + link.add(key, value) + + key = link.get("rel", url) + + link.add("url", self.url.join(URL(url))) + + links.add(str(key), MultiDictProxy(link)) + + return MultiDictProxy(links) + + async def start(self, connection: "Connection") -> "ClientResponse": + """Start response processing.""" + self._closed = False + self._protocol = connection.protocol + self._connection = connection + + with self._timer: + while True: + # read response + try: + protocol = self._protocol + message, payload = await protocol.read() # type: ignore[union-attr] + except http.HttpProcessingError as exc: + raise ClientResponseError( + self.request_info, + self.history, + status=exc.code, + message=exc.message, + headers=exc.headers, + ) from exc + + if message.code < 100 or message.code > 199 or message.code == 101: + break + + if self._continue is not None: + set_result(self._continue, True) + self._continue = None + + # payload eof handler + payload.on_eof(self._response_eof) + + # response status + self.version = message.version + self.status = message.code + self.reason = message.reason + + # headers + self._headers = message.headers # type is CIMultiDictProxy + self._raw_headers = message.raw_headers # type is Tuple[bytes, bytes] + + # payload + self.content = payload + + # cookies + if cookie_hdrs := self.headers.getall(hdrs.SET_COOKIE, ()): + # Store raw cookie headers for CookieJar + self._raw_cookie_headers = tuple(cookie_hdrs) + return self + + def _response_eof(self) -> None: + if self._closed: + return + + # protocol could be None because connection could be detached + protocol = self._connection and self._connection.protocol + if protocol is not None and protocol.upgraded: + return + + self._closed = True + self._cleanup_writer() + self._release_connection() + + @property + def closed(self) -> bool: + return self._closed + + def close(self) -> None: + if not self._released: + self._notify_content() + + self._closed = True + if self._loop is None or self._loop.is_closed(): + return + + self._cleanup_writer() + if self._connection is not None: + self._connection.close() + self._connection = None + + def release(self) -> Any: + if not self._released: + self._notify_content() + + self._closed = True + + self._cleanup_writer() + self._release_connection() + return noop() + + @property + def ok(self) -> bool: + """Returns ``True`` if ``status`` is less than ``400``, ``False`` if not. + + This is **not** a check for ``200 OK`` but a check that the response + status is under 400. + """ + return 400 > self.status + + def raise_for_status(self) -> None: + if not self.ok: + # reason should always be not None for a started response + assert self.reason is not None + + # If we're in a context we can rely on __aexit__() to release as the + # exception propagates. + if not self._in_context: + self.release() + + raise ClientResponseError( + self.request_info, + self.history, + status=self.status, + message=self.reason, + headers=self.headers, + ) + + def _release_connection(self) -> None: + if self._connection is not None: + if self.__writer is None: + self._connection.release() + self._connection = None + else: + self.__writer.add_done_callback(lambda f: self._release_connection()) + + async def _wait_released(self) -> None: + if self.__writer is not None: + try: + await self.__writer + except asyncio.CancelledError: + if ( + sys.version_info >= (3, 11) + and (task := asyncio.current_task()) + and task.cancelling() + ): + raise + self._release_connection() + + def _cleanup_writer(self) -> None: + if self.__writer is not None: + self.__writer.cancel() + self._session = None + + def _notify_content(self) -> None: + content = self.content + if content and content.exception() is None: + set_exception(content, _CONNECTION_CLOSED_EXCEPTION) + self._released = True + + async def wait_for_close(self) -> None: + if self.__writer is not None: + try: + await self.__writer + except asyncio.CancelledError: + if ( + sys.version_info >= (3, 11) + and (task := asyncio.current_task()) + and task.cancelling() + ): + raise + self.release() + + async def read(self) -> bytes: + """Read response payload.""" + if self._body is None: + try: + self._body = await self.content.read() + for trace in self._traces: + await trace.send_response_chunk_received( + self.method, self.url, self._body + ) + except BaseException: + self.close() + raise + elif self._released: # Response explicitly released + raise ClientConnectionError("Connection closed") + + protocol = self._connection and self._connection.protocol + if protocol is None or not protocol.upgraded: + await self._wait_released() # Underlying connection released + return self._body + + def get_encoding(self) -> str: + ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower() + mimetype = helpers.parse_mimetype(ctype) + + encoding = mimetype.parameters.get("charset") + if encoding: + with contextlib.suppress(LookupError, ValueError): + return codecs.lookup(encoding).name + + if mimetype.type == "application" and ( + mimetype.subtype == "json" or mimetype.subtype == "rdap" + ): + # RFC 7159 states that the default encoding is UTF-8. + # RFC 7483 defines application/rdap+json + return "utf-8" + + if self._body is None: + raise RuntimeError( + "Cannot compute fallback encoding of a not yet read body" + ) + + return self._resolve_charset(self, self._body) + + async def text(self, encoding: Optional[str] = None, errors: str = "strict") -> str: + """Read response payload and decode.""" + if self._body is None: + await self.read() + + if encoding is None: + encoding = self.get_encoding() + + return self._body.decode(encoding, errors=errors) # type: ignore[union-attr] + + async def json( + self, + *, + encoding: Optional[str] = None, + loads: JSONDecoder = DEFAULT_JSON_DECODER, + content_type: Optional[str] = "application/json", + ) -> Any: + """Read and decodes JSON response.""" + if self._body is None: + await self.read() + + if content_type: + ctype = self.headers.get(hdrs.CONTENT_TYPE, "").lower() + if not _is_expected_content_type(ctype, content_type): + raise ContentTypeError( + self.request_info, + self.history, + status=self.status, + message=( + "Attempt to decode JSON with unexpected mimetype: %s" % ctype + ), + headers=self.headers, + ) + + stripped = self._body.strip() # type: ignore[union-attr] + if not stripped: + return None + + if encoding is None: + encoding = self.get_encoding() + + return loads(stripped.decode(encoding)) + + async def __aenter__(self) -> "ClientResponse": + self._in_context = True + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + self._in_context = False + # similar to _RequestContextManager, we do not need to check + # for exceptions, response object can close connection + # if state is broken + self.release() + await self.wait_for_close() + + +class ClientRequest: + GET_METHODS = { + hdrs.METH_GET, + hdrs.METH_HEAD, + hdrs.METH_OPTIONS, + hdrs.METH_TRACE, + } + POST_METHODS = {hdrs.METH_PATCH, hdrs.METH_POST, hdrs.METH_PUT} + ALL_METHODS = GET_METHODS.union(POST_METHODS).union({hdrs.METH_DELETE}) + + DEFAULT_HEADERS = { + hdrs.ACCEPT: "*/*", + hdrs.ACCEPT_ENCODING: _gen_default_accept_encoding(), + } + + # Type of body depends on PAYLOAD_REGISTRY, which is dynamic. + _body: Union[None, payload.Payload] = None + auth = None + response = None + + __writer: Optional["asyncio.Task[None]"] = None # async task for streaming data + + # These class defaults help create_autospec() work correctly. + # If autospec is improved in future, maybe these can be removed. + url = URL() + method = "GET" + + _continue = None # waiter future for '100 Continue' response + + _skip_auto_headers: Optional["CIMultiDict[None]"] = None + + # N.B. + # Adding __del__ method with self._writer closing doesn't make sense + # because _writer is instance method, thus it keeps a reference to self. + # Until writer has finished finalizer will not be called. + + def __init__( + self, + method: str, + url: URL, + *, + params: Query = None, + headers: Optional[LooseHeaders] = None, + skip_auto_headers: Optional[Iterable[str]] = None, + data: Any = None, + cookies: Optional[LooseCookies] = None, + auth: Optional[BasicAuth] = None, + version: http.HttpVersion = http.HttpVersion11, + compress: Union[str, bool, None] = None, + chunked: Optional[bool] = None, + expect100: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + response_class: Optional[Type["ClientResponse"]] = None, + proxy: Optional[URL] = None, + proxy_auth: Optional[BasicAuth] = None, + timer: Optional[BaseTimerContext] = None, + session: Optional["ClientSession"] = None, + ssl: Union[SSLContext, bool, Fingerprint] = True, + proxy_headers: Optional[LooseHeaders] = None, + traces: Optional[List["Trace"]] = None, + trust_env: bool = False, + server_hostname: Optional[str] = None, + ): + if loop is None: + loop = asyncio.get_event_loop() + if match := _CONTAINS_CONTROL_CHAR_RE.search(method): + raise ValueError( + f"Method cannot contain non-token characters {method!r} " + f"(found at least {match.group()!r})" + ) + # URL forbids subclasses, so a simple type check is enough. + assert type(url) is URL, url + if proxy is not None: + assert type(proxy) is URL, proxy + # FIXME: session is None in tests only, need to fix tests + # assert session is not None + if TYPE_CHECKING: + assert session is not None + self._session = session + if params: + url = url.extend_query(params) + self.original_url = url + self.url = url.with_fragment(None) if url.raw_fragment else url + self.method = method.upper() + self.chunked = chunked + self.compress = compress + self.loop = loop + self.length = None + if response_class is None: + real_response_class = ClientResponse + else: + real_response_class = response_class + self.response_class: Type[ClientResponse] = real_response_class + self._timer = timer if timer is not None else TimerNoop() + self._ssl = ssl if ssl is not None else True + self.server_hostname = server_hostname + + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + self.update_version(version) + self.update_host(url) + self.update_headers(headers) + self.update_auto_headers(skip_auto_headers) + self.update_cookies(cookies) + self.update_content_encoding(data) + self.update_auth(auth, trust_env) + self.update_proxy(proxy, proxy_auth, proxy_headers) + + self.update_body_from_data(data) + if data is not None or self.method not in self.GET_METHODS: + self.update_transfer_encoding() + self.update_expect_continue(expect100) + self._traces = [] if traces is None else traces + + def __reset_writer(self, _: object = None) -> None: + self.__writer = None + + def _get_content_length(self) -> Optional[int]: + """Extract and validate Content-Length header value. + + Returns parsed Content-Length value or None if not set. + Raises ValueError if header exists but cannot be parsed as an integer. + """ + if hdrs.CONTENT_LENGTH not in self.headers: + return None + + content_length_hdr = self.headers[hdrs.CONTENT_LENGTH] + try: + return int(content_length_hdr) + except ValueError: + raise ValueError( + f"Invalid Content-Length header: {content_length_hdr}" + ) from None + + @property + def skip_auto_headers(self) -> CIMultiDict[None]: + return self._skip_auto_headers or CIMultiDict() + + @property + def _writer(self) -> Optional["asyncio.Task[None]"]: + return self.__writer + + @_writer.setter + def _writer(self, writer: "asyncio.Task[None]") -> None: + if self.__writer is not None: + self.__writer.remove_done_callback(self.__reset_writer) + self.__writer = writer + writer.add_done_callback(self.__reset_writer) + + def is_ssl(self) -> bool: + return self.url.scheme in _SSL_SCHEMES + + @property + def ssl(self) -> Union["SSLContext", bool, Fingerprint]: + return self._ssl + + @property + def connection_key(self) -> ConnectionKey: + if proxy_headers := self.proxy_headers: + h: Optional[int] = hash(tuple(proxy_headers.items())) + else: + h = None + url = self.url + return tuple.__new__( + ConnectionKey, + ( + url.raw_host or "", + url.port, + url.scheme in _SSL_SCHEMES, + self._ssl, + self.proxy, + self.proxy_auth, + h, + ), + ) + + @property + def host(self) -> str: + ret = self.url.raw_host + assert ret is not None + return ret + + @property + def port(self) -> Optional[int]: + return self.url.port + + @property + def body(self) -> Union[payload.Payload, Literal[b""]]: + """Request body.""" + # empty body is represented as bytes for backwards compatibility + return self._body or b"" + + @body.setter + def body(self, value: Any) -> None: + """Set request body with warning for non-autoclose payloads. + + WARNING: This setter must be called from within an event loop and is not + thread-safe. Setting body outside of an event loop may raise RuntimeError + when closing file-based payloads. + + DEPRECATED: Direct assignment to body is deprecated and will be removed + in a future version. Use await update_body() instead for proper resource + management. + """ + # Close existing payload if present + if self._body is not None: + # Warn if the payload needs manual closing + # stacklevel=3: user code -> body setter -> _warn_if_unclosed_payload + _warn_if_unclosed_payload(self._body, stacklevel=3) + # NOTE: In the future, when we remove sync close support, + # this setter will need to be removed and only the async + # update_body() method will be available. For now, we call + # _close() for backwards compatibility. + self._body._close() + self._update_body(value) + + @property + def request_info(self) -> RequestInfo: + headers: CIMultiDictProxy[str] = CIMultiDictProxy(self.headers) + # These are created on every request, so we use a NamedTuple + # for performance reasons. We don't use the RequestInfo.__new__ + # method because it has a different signature which is provided + # for backwards compatibility only. + return tuple.__new__( + RequestInfo, (self.url, self.method, headers, self.original_url) + ) + + @property + def session(self) -> "ClientSession": + """Return the ClientSession instance. + + This property provides access to the ClientSession that initiated + this request, allowing middleware to make additional requests + using the same session. + """ + return self._session + + def update_host(self, url: URL) -> None: + """Update destination host, port and connection type (ssl).""" + # get host/port + if not url.raw_host: + raise InvalidURL(url) + + # basic auth info + if url.raw_user or url.raw_password: + self.auth = helpers.BasicAuth(url.user or "", url.password or "") + + def update_version(self, version: Union[http.HttpVersion, str]) -> None: + """Convert request version to two elements tuple. + + parser HTTP version '1.1' => (1, 1) + """ + if isinstance(version, str): + v = [part.strip() for part in version.split(".", 1)] + try: + version = http.HttpVersion(int(v[0]), int(v[1])) + except ValueError: + raise ValueError( + f"Can not parse http version number: {version}" + ) from None + self.version = version + + def update_headers(self, headers: Optional[LooseHeaders]) -> None: + """Update request headers.""" + self.headers: CIMultiDict[str] = CIMultiDict() + + # Build the host header + host = self.url.host_port_subcomponent + + # host_port_subcomponent is None when the URL is a relative URL. + # but we know we do not have a relative URL here. + assert host is not None + self.headers[hdrs.HOST] = host + + if not headers: + return + + if isinstance(headers, (dict, MultiDictProxy, MultiDict)): + headers = headers.items() + + for key, value in headers: # type: ignore[misc] + # A special case for Host header + if key in hdrs.HOST_ALL: + self.headers[key] = value + else: + self.headers.add(key, value) + + def update_auto_headers(self, skip_auto_headers: Optional[Iterable[str]]) -> None: + if skip_auto_headers is not None: + self._skip_auto_headers = CIMultiDict( + (hdr, None) for hdr in sorted(skip_auto_headers) + ) + used_headers = self.headers.copy() + used_headers.extend(self._skip_auto_headers) # type: ignore[arg-type] + else: + # Fast path when there are no headers to skip + # which is the most common case. + used_headers = self.headers + + for hdr, val in self.DEFAULT_HEADERS.items(): + if hdr not in used_headers: + self.headers[hdr] = val + + if hdrs.USER_AGENT not in used_headers: + self.headers[hdrs.USER_AGENT] = SERVER_SOFTWARE + + def update_cookies(self, cookies: Optional[LooseCookies]) -> None: + """Update request cookies header.""" + if not cookies: + return + + c = SimpleCookie() + if hdrs.COOKIE in self.headers: + # parse_cookie_header for RFC 6265 compliant Cookie header parsing + c.update(parse_cookie_header(self.headers.get(hdrs.COOKIE, ""))) + del self.headers[hdrs.COOKIE] + + if isinstance(cookies, Mapping): + iter_cookies = cookies.items() + else: + iter_cookies = cookies # type: ignore[assignment] + for name, value in iter_cookies: + if isinstance(value, Morsel): + # Use helper to preserve coded_value exactly as sent by server + c[name] = preserve_morsel_with_coded_value(value) + else: + c[name] = value # type: ignore[assignment] + + self.headers[hdrs.COOKIE] = c.output(header="", sep=";").strip() + + def update_content_encoding(self, data: Any) -> None: + """Set request content encoding.""" + if not data: + # Don't compress an empty body. + self.compress = None + return + + if self.headers.get(hdrs.CONTENT_ENCODING): + if self.compress: + raise ValueError( + "compress can not be set if Content-Encoding header is set" + ) + elif self.compress: + if not isinstance(self.compress, str): + self.compress = "deflate" + self.headers[hdrs.CONTENT_ENCODING] = self.compress + self.chunked = True # enable chunked, no need to deal with length + + def update_transfer_encoding(self) -> None: + """Analyze transfer-encoding header.""" + te = self.headers.get(hdrs.TRANSFER_ENCODING, "").lower() + + if "chunked" in te: + if self.chunked: + raise ValueError( + "chunked can not be set " + 'if "Transfer-Encoding: chunked" header is set' + ) + + elif self.chunked: + if hdrs.CONTENT_LENGTH in self.headers: + raise ValueError( + "chunked can not be set if Content-Length header is set" + ) + + self.headers[hdrs.TRANSFER_ENCODING] = "chunked" + + def update_auth(self, auth: Optional[BasicAuth], trust_env: bool = False) -> None: + """Set basic auth.""" + if auth is None: + auth = self.auth + if auth is None and trust_env and self.url.host is not None: + netrc_obj = netrc_from_env() + with contextlib.suppress(LookupError): + auth = basicauth_from_netrc(netrc_obj, self.url.host) + if auth is None: + return + + if not isinstance(auth, helpers.BasicAuth): + raise TypeError("BasicAuth() tuple is required instead") + + self.headers[hdrs.AUTHORIZATION] = auth.encode() + + def update_body_from_data(self, body: Any, _stacklevel: int = 3) -> None: + """Update request body from data.""" + if self._body is not None: + _warn_if_unclosed_payload(self._body, stacklevel=_stacklevel) + + if body is None: + self._body = None + # Set Content-Length to 0 when body is None for methods that expect a body + if ( + self.method not in self.GET_METHODS + and not self.chunked + and hdrs.CONTENT_LENGTH not in self.headers + ): + self.headers[hdrs.CONTENT_LENGTH] = "0" + return + + # FormData + maybe_payload = body() if isinstance(body, FormData) else body + + try: + body_payload = payload.PAYLOAD_REGISTRY.get(maybe_payload, disposition=None) + except payload.LookupError: + body_payload = FormData(maybe_payload)() # type: ignore[arg-type] + + self._body = body_payload + # enable chunked encoding if needed + if not self.chunked and hdrs.CONTENT_LENGTH not in self.headers: + if (size := body_payload.size) is not None: + self.headers[hdrs.CONTENT_LENGTH] = str(size) + else: + self.chunked = True + + # copy payload headers + assert body_payload.headers + headers = self.headers + skip_headers = self._skip_auto_headers + for key, value in body_payload.headers.items(): + if key in headers or (skip_headers is not None and key in skip_headers): + continue + headers[key] = value + + def _update_body(self, body: Any) -> None: + """Update request body after its already been set.""" + # Remove existing Content-Length header since body is changing + if hdrs.CONTENT_LENGTH in self.headers: + del self.headers[hdrs.CONTENT_LENGTH] + + # Remove existing Transfer-Encoding header to avoid conflicts + if self.chunked and hdrs.TRANSFER_ENCODING in self.headers: + del self.headers[hdrs.TRANSFER_ENCODING] + + # Now update the body using the existing method + # Called from _update_body, add 1 to stacklevel from caller + self.update_body_from_data(body, _stacklevel=4) + + # Update transfer encoding headers if needed (same logic as __init__) + if body is not None or self.method not in self.GET_METHODS: + self.update_transfer_encoding() + + async def update_body(self, body: Any) -> None: + """ + Update request body and close previous payload if needed. + + This method safely updates the request body by first closing any existing + payload to prevent resource leaks, then setting the new body. + + IMPORTANT: Always use this method instead of setting request.body directly. + Direct assignment to request.body will leak resources if the previous body + contains file handles, streams, or other resources that need cleanup. + + Args: + body: The new body content. Can be: + - bytes/bytearray: Raw binary data + - str: Text data (will be encoded using charset from Content-Type) + - FormData: Form data that will be encoded as multipart/form-data + - Payload: A pre-configured payload object + - AsyncIterable: An async iterable of bytes chunks + - File-like object: Will be read and sent as binary data + - None: Clears the body + + Usage: + # CORRECT: Use update_body + await request.update_body(b"new request data") + + # WRONG: Don't set body directly + # request.body = b"new request data" # This will leak resources! + + # Update with form data + form_data = FormData() + form_data.add_field('field', 'value') + await request.update_body(form_data) + + # Clear body + await request.update_body(None) + + Note: + This method is async because it may need to close file handles or + other resources associated with the previous payload. Always await + this method to ensure proper cleanup. + + Warning: + Setting request.body directly is highly discouraged and can lead to: + - Resource leaks (unclosed file handles, streams) + - Memory leaks (unreleased buffers) + - Unexpected behavior with streaming payloads + + It is not recommended to change the payload type in middleware. If the + body was already set (e.g., as bytes), it's best to keep the same type + rather than converting it (e.g., to str) as this may result in unexpected + behavior. + + See Also: + - update_body_from_data: Synchronous body update without cleanup + - body property: Direct body access (STRONGLY DISCOURAGED) + + """ + # Close existing payload if it exists and needs closing + if self._body is not None: + await self._body.close() + self._update_body(body) + + def update_expect_continue(self, expect: bool = False) -> None: + if expect: + self.headers[hdrs.EXPECT] = "100-continue" + elif ( + hdrs.EXPECT in self.headers + and self.headers[hdrs.EXPECT].lower() == "100-continue" + ): + expect = True + + if expect: + self._continue = self.loop.create_future() + + def update_proxy( + self, + proxy: Optional[URL], + proxy_auth: Optional[BasicAuth], + proxy_headers: Optional[LooseHeaders], + ) -> None: + self.proxy = proxy + if proxy is None: + self.proxy_auth = None + self.proxy_headers = None + return + + if proxy_auth and not isinstance(proxy_auth, helpers.BasicAuth): + raise ValueError("proxy_auth must be None or BasicAuth() tuple") + self.proxy_auth = proxy_auth + + if proxy_headers is not None and not isinstance( + proxy_headers, (MultiDict, MultiDictProxy) + ): + proxy_headers = CIMultiDict(proxy_headers) + self.proxy_headers = proxy_headers + + async def write_bytes( + self, + writer: AbstractStreamWriter, + conn: "Connection", + content_length: Optional[int], + ) -> None: + """ + Write the request body to the connection stream. + + This method handles writing different types of request bodies: + 1. Payload objects (using their specialized write_with_length method) + 2. Bytes/bytearray objects + 3. Iterable body content + + Args: + writer: The stream writer to write the body to + conn: The connection being used for this request + content_length: Optional maximum number of bytes to write from the body + (None means write the entire body) + + The method properly handles: + - Waiting for 100-Continue responses if required + - Content length constraints for chunked encoding + - Error handling for network issues, cancellation, and other exceptions + - Signaling EOF and timeout management + + Raises: + ClientOSError: When there's an OS-level error writing the body + ClientConnectionError: When there's a general connection error + asyncio.CancelledError: When the operation is cancelled + + """ + # 100 response + if self._continue is not None: + # Force headers to be sent before waiting for 100-continue + writer.send_headers() + await writer.drain() + await self._continue + + protocol = conn.protocol + assert protocol is not None + try: + # This should be a rare case but the + # self._body can be set to None while + # the task is being started or we wait above + # for the 100-continue response. + # The more likely case is we have an empty + # payload, but 100-continue is still expected. + if self._body is not None: + await self._body.write_with_length(writer, content_length) + except OSError as underlying_exc: + reraised_exc = underlying_exc + + # Distinguish between timeout and other OS errors for better error reporting + exc_is_not_timeout = underlying_exc.errno is not None or not isinstance( + underlying_exc, asyncio.TimeoutError + ) + if exc_is_not_timeout: + reraised_exc = ClientOSError( + underlying_exc.errno, + f"Can not write request body for {self.url !s}", + ) + + set_exception(protocol, reraised_exc, underlying_exc) + except asyncio.CancelledError: + # Body hasn't been fully sent, so connection can't be reused + conn.close() + raise + except Exception as underlying_exc: + set_exception( + protocol, + ClientConnectionError( + "Failed to send bytes into the underlying connection " + f"{conn !s}: {underlying_exc!r}", + ), + underlying_exc, + ) + else: + # Successfully wrote the body, signal EOF and start response timeout + await writer.write_eof() + protocol.start_timeout() + + async def send(self, conn: "Connection") -> "ClientResponse": + # Specify request target: + # - CONNECT request must send authority form URI + # - not CONNECT proxy must send absolute form URI + # - most common is origin form URI + if self.method == hdrs.METH_CONNECT: + connect_host = self.url.host_subcomponent + assert connect_host is not None + path = f"{connect_host}:{self.url.port}" + elif self.proxy and not self.is_ssl(): + path = str(self.url) + else: + path = self.url.raw_path_qs + + protocol = conn.protocol + assert protocol is not None + writer = StreamWriter( + protocol, + self.loop, + on_chunk_sent=( + functools.partial(self._on_chunk_request_sent, self.method, self.url) + if self._traces + else None + ), + on_headers_sent=( + functools.partial(self._on_headers_request_sent, self.method, self.url) + if self._traces + else None + ), + ) + + if self.compress: + writer.enable_compression(self.compress) # type: ignore[arg-type] + + if self.chunked is not None: + writer.enable_chunking() + + # set default content-type + if ( + self.method in self.POST_METHODS + and ( + self._skip_auto_headers is None + or hdrs.CONTENT_TYPE not in self._skip_auto_headers + ) + and hdrs.CONTENT_TYPE not in self.headers + ): + self.headers[hdrs.CONTENT_TYPE] = "application/octet-stream" + + v = self.version + if hdrs.CONNECTION not in self.headers: + if conn._connector.force_close: + if v == HttpVersion11: + self.headers[hdrs.CONNECTION] = "close" + elif v == HttpVersion10: + self.headers[hdrs.CONNECTION] = "keep-alive" + + # status + headers + status_line = f"{self.method} {path} HTTP/{v.major}.{v.minor}" + + # Buffer headers for potential coalescing with body + await writer.write_headers(status_line, self.headers) + + task: Optional["asyncio.Task[None]"] + if self._body or self._continue is not None or protocol.writing_paused: + coro = self.write_bytes(writer, conn, self._get_content_length()) + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to write + # bytes immediately to avoid having to schedule + # the task on the event loop. + task = asyncio.Task(coro, loop=self.loop, eager_start=True) + else: + task = self.loop.create_task(coro) + if task.done(): + task = None + else: + self._writer = task + else: + # We have nothing to write because + # - there is no body + # - the protocol does not have writing paused + # - we are not waiting for a 100-continue response + protocol.start_timeout() + writer.set_eof() + task = None + response_class = self.response_class + assert response_class is not None + self.response = response_class( + self.method, + self.original_url, + writer=task, + continue100=self._continue, + timer=self._timer, + request_info=self.request_info, + traces=self._traces, + loop=self.loop, + session=self._session, + ) + return self.response + + async def close(self) -> None: + if self.__writer is not None: + try: + await self.__writer + except asyncio.CancelledError: + if ( + sys.version_info >= (3, 11) + and (task := asyncio.current_task()) + and task.cancelling() + ): + raise + + def terminate(self) -> None: + if self.__writer is not None: + if not self.loop.is_closed(): + self.__writer.cancel() + self.__writer.remove_done_callback(self.__reset_writer) + self.__writer = None + + async def _on_chunk_request_sent(self, method: str, url: URL, chunk: bytes) -> None: + for trace in self._traces: + await trace.send_request_chunk_sent(method, url, chunk) + + async def _on_headers_request_sent( + self, method: str, url: URL, headers: "CIMultiDict[str]" + ) -> None: + for trace in self._traces: + await trace.send_request_headers(method, url, headers) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_ws.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_ws.py new file mode 100644 index 0000000000000000000000000000000000000000..daa57d1930b1b0cfc03594aaae62bd93da5da165 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/client_ws.py @@ -0,0 +1,428 @@ +"""WebSocket client for asyncio.""" + +import asyncio +import sys +from types import TracebackType +from typing import Any, Optional, Type, cast + +import attr + +from ._websocket.reader import WebSocketDataQueue +from .client_exceptions import ClientError, ServerTimeoutError, WSMessageTypeError +from .client_reqrep import ClientResponse +from .helpers import calculate_timeout_when, set_result +from .http import ( + WS_CLOSED_MESSAGE, + WS_CLOSING_MESSAGE, + WebSocketError, + WSCloseCode, + WSMessage, + WSMsgType, +) +from .http_websocket import _INTERNAL_RECEIVE_TYPES, WebSocketWriter +from .streams import EofStream +from .typedefs import ( + DEFAULT_JSON_DECODER, + DEFAULT_JSON_ENCODER, + JSONDecoder, + JSONEncoder, +) + +if sys.version_info >= (3, 11): + import asyncio as async_timeout +else: + import async_timeout + + +@attr.s(frozen=True, slots=True) +class ClientWSTimeout: + ws_receive = attr.ib(type=Optional[float], default=None) + ws_close = attr.ib(type=Optional[float], default=None) + + +DEFAULT_WS_CLIENT_TIMEOUT = ClientWSTimeout(ws_receive=None, ws_close=10.0) + + +class ClientWebSocketResponse: + def __init__( + self, + reader: WebSocketDataQueue, + writer: WebSocketWriter, + protocol: Optional[str], + response: ClientResponse, + timeout: ClientWSTimeout, + autoclose: bool, + autoping: bool, + loop: asyncio.AbstractEventLoop, + *, + heartbeat: Optional[float] = None, + compress: int = 0, + client_notakeover: bool = False, + ) -> None: + self._response = response + self._conn = response.connection + + self._writer = writer + self._reader = reader + self._protocol = protocol + self._closed = False + self._closing = False + self._close_code: Optional[int] = None + self._timeout = timeout + self._autoclose = autoclose + self._autoping = autoping + self._heartbeat = heartbeat + self._heartbeat_cb: Optional[asyncio.TimerHandle] = None + self._heartbeat_when: float = 0.0 + if heartbeat is not None: + self._pong_heartbeat = heartbeat / 2.0 + self._pong_response_cb: Optional[asyncio.TimerHandle] = None + self._loop = loop + self._waiting: bool = False + self._close_wait: Optional[asyncio.Future[None]] = None + self._exception: Optional[BaseException] = None + self._compress = compress + self._client_notakeover = client_notakeover + self._ping_task: Optional[asyncio.Task[None]] = None + + self._reset_heartbeat() + + def _cancel_heartbeat(self) -> None: + self._cancel_pong_response_cb() + if self._heartbeat_cb is not None: + self._heartbeat_cb.cancel() + self._heartbeat_cb = None + if self._ping_task is not None: + self._ping_task.cancel() + self._ping_task = None + + def _cancel_pong_response_cb(self) -> None: + if self._pong_response_cb is not None: + self._pong_response_cb.cancel() + self._pong_response_cb = None + + def _reset_heartbeat(self) -> None: + if self._heartbeat is None: + return + self._cancel_pong_response_cb() + loop = self._loop + assert loop is not None + conn = self._conn + timeout_ceil_threshold = ( + conn._connector._timeout_ceil_threshold if conn is not None else 5 + ) + now = loop.time() + when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold) + self._heartbeat_when = when + if self._heartbeat_cb is None: + # We do not cancel the previous heartbeat_cb here because + # it generates a significant amount of TimerHandle churn + # which causes asyncio to rebuild the heap frequently. + # Instead _send_heartbeat() will reschedule the next + # heartbeat if it fires too early. + self._heartbeat_cb = loop.call_at(when, self._send_heartbeat) + + def _send_heartbeat(self) -> None: + self._heartbeat_cb = None + loop = self._loop + now = loop.time() + if now < self._heartbeat_when: + # Heartbeat fired too early, reschedule + self._heartbeat_cb = loop.call_at( + self._heartbeat_when, self._send_heartbeat + ) + return + + conn = self._conn + timeout_ceil_threshold = ( + conn._connector._timeout_ceil_threshold if conn is not None else 5 + ) + when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold) + self._cancel_pong_response_cb() + self._pong_response_cb = loop.call_at(when, self._pong_not_received) + + coro = self._writer.send_frame(b"", WSMsgType.PING) + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to send the ping + # immediately to avoid having to schedule + # the task on the event loop. + ping_task = asyncio.Task(coro, loop=loop, eager_start=True) + else: + ping_task = loop.create_task(coro) + + if not ping_task.done(): + self._ping_task = ping_task + ping_task.add_done_callback(self._ping_task_done) + else: + self._ping_task_done(ping_task) + + def _ping_task_done(self, task: "asyncio.Task[None]") -> None: + """Callback for when the ping task completes.""" + if not task.cancelled() and (exc := task.exception()): + self._handle_ping_pong_exception(exc) + self._ping_task = None + + def _pong_not_received(self) -> None: + self._handle_ping_pong_exception( + ServerTimeoutError(f"No PONG received after {self._pong_heartbeat} seconds") + ) + + def _handle_ping_pong_exception(self, exc: BaseException) -> None: + """Handle exceptions raised during ping/pong processing.""" + if self._closed: + return + self._set_closed() + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._exception = exc + self._response.close() + if self._waiting and not self._closing: + self._reader.feed_data(WSMessage(WSMsgType.ERROR, exc, None), 0) + + def _set_closed(self) -> None: + """Set the connection to closed. + + Cancel any heartbeat timers and set the closed flag. + """ + self._closed = True + self._cancel_heartbeat() + + def _set_closing(self) -> None: + """Set the connection to closing. + + Cancel any heartbeat timers and set the closing flag. + """ + self._closing = True + self._cancel_heartbeat() + + @property + def closed(self) -> bool: + return self._closed + + @property + def close_code(self) -> Optional[int]: + return self._close_code + + @property + def protocol(self) -> Optional[str]: + return self._protocol + + @property + def compress(self) -> int: + return self._compress + + @property + def client_notakeover(self) -> bool: + return self._client_notakeover + + def get_extra_info(self, name: str, default: Any = None) -> Any: + """extra info from connection transport""" + conn = self._response.connection + if conn is None: + return default + transport = conn.transport + if transport is None: + return default + return transport.get_extra_info(name, default) + + def exception(self) -> Optional[BaseException]: + return self._exception + + async def ping(self, message: bytes = b"") -> None: + await self._writer.send_frame(message, WSMsgType.PING) + + async def pong(self, message: bytes = b"") -> None: + await self._writer.send_frame(message, WSMsgType.PONG) + + async def send_frame( + self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None + ) -> None: + """Send a frame over the websocket.""" + await self._writer.send_frame(message, opcode, compress) + + async def send_str(self, data: str, compress: Optional[int] = None) -> None: + if not isinstance(data, str): + raise TypeError("data argument must be str (%r)" % type(data)) + await self._writer.send_frame( + data.encode("utf-8"), WSMsgType.TEXT, compress=compress + ) + + async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None: + if not isinstance(data, (bytes, bytearray, memoryview)): + raise TypeError("data argument must be byte-ish (%r)" % type(data)) + await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress) + + async def send_json( + self, + data: Any, + compress: Optional[int] = None, + *, + dumps: JSONEncoder = DEFAULT_JSON_ENCODER, + ) -> None: + await self.send_str(dumps(data), compress=compress) + + async def close(self, *, code: int = WSCloseCode.OK, message: bytes = b"") -> bool: + # we need to break `receive()` cycle first, + # `close()` may be called from different task + if self._waiting and not self._closing: + assert self._loop is not None + self._close_wait = self._loop.create_future() + self._set_closing() + self._reader.feed_data(WS_CLOSING_MESSAGE, 0) + await self._close_wait + + if self._closed: + return False + + self._set_closed() + try: + await self._writer.close(code, message) + except asyncio.CancelledError: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._response.close() + raise + except Exception as exc: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._exception = exc + self._response.close() + return True + + if self._close_code: + self._response.close() + return True + + while True: + try: + async with async_timeout.timeout(self._timeout.ws_close): + msg = await self._reader.read() + except asyncio.CancelledError: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._response.close() + raise + except Exception as exc: + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + self._exception = exc + self._response.close() + return True + + if msg.type is WSMsgType.CLOSE: + self._close_code = msg.data + self._response.close() + return True + + async def receive(self, timeout: Optional[float] = None) -> WSMessage: + receive_timeout = timeout or self._timeout.ws_receive + + while True: + if self._waiting: + raise RuntimeError("Concurrent call to receive() is not allowed") + + if self._closed: + return WS_CLOSED_MESSAGE + elif self._closing: + await self.close() + return WS_CLOSED_MESSAGE + + try: + self._waiting = True + try: + if receive_timeout: + # Entering the context manager and creating + # Timeout() object can take almost 50% of the + # run time in this loop so we avoid it if + # there is no read timeout. + async with async_timeout.timeout(receive_timeout): + msg = await self._reader.read() + else: + msg = await self._reader.read() + self._reset_heartbeat() + finally: + self._waiting = False + if self._close_wait: + set_result(self._close_wait, None) + except (asyncio.CancelledError, asyncio.TimeoutError): + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + raise + except EofStream: + self._close_code = WSCloseCode.OK + await self.close() + return WSMessage(WSMsgType.CLOSED, None, None) + except ClientError: + # Likely ServerDisconnectedError when connection is lost + self._set_closed() + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + return WS_CLOSED_MESSAGE + except WebSocketError as exc: + self._close_code = exc.code + await self.close(code=exc.code) + return WSMessage(WSMsgType.ERROR, exc, None) + except Exception as exc: + self._exception = exc + self._set_closing() + self._close_code = WSCloseCode.ABNORMAL_CLOSURE + await self.close() + return WSMessage(WSMsgType.ERROR, exc, None) + + if msg.type not in _INTERNAL_RECEIVE_TYPES: + # If its not a close/closing/ping/pong message + # we can return it immediately + return msg + + if msg.type is WSMsgType.CLOSE: + self._set_closing() + self._close_code = msg.data + if not self._closed and self._autoclose: + await self.close() + elif msg.type is WSMsgType.CLOSING: + self._set_closing() + elif msg.type is WSMsgType.PING and self._autoping: + await self.pong(msg.data) + continue + elif msg.type is WSMsgType.PONG and self._autoping: + continue + + return msg + + async def receive_str(self, *, timeout: Optional[float] = None) -> str: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.TEXT: + raise WSMessageTypeError( + f"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT" + ) + return cast(str, msg.data) + + async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.BINARY: + raise WSMessageTypeError( + f"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY" + ) + return cast(bytes, msg.data) + + async def receive_json( + self, + *, + loads: JSONDecoder = DEFAULT_JSON_DECODER, + timeout: Optional[float] = None, + ) -> Any: + data = await self.receive_str(timeout=timeout) + return loads(data) + + def __aiter__(self) -> "ClientWebSocketResponse": + return self + + async def __anext__(self) -> WSMessage: + msg = await self.receive() + if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED): + raise StopAsyncIteration + return msg + + async def __aenter__(self) -> "ClientWebSocketResponse": + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + await self.close() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/compression_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/compression_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f08c3d9cdff0c9ee27e006b0f028a648f93a6955 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/compression_utils.py @@ -0,0 +1,278 @@ +import asyncio +import sys +import zlib +from concurrent.futures import Executor +from typing import Any, Final, Optional, Protocol, TypedDict, cast + +if sys.version_info >= (3, 12): + from collections.abc import Buffer +else: + from typing import Union + + Buffer = Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"] + +try: + try: + import brotlicffi as brotli + except ImportError: + import brotli + + HAS_BROTLI = True +except ImportError: # pragma: no cover + HAS_BROTLI = False + +MAX_SYNC_CHUNK_SIZE = 1024 + + +class ZLibCompressObjProtocol(Protocol): + def compress(self, data: Buffer) -> bytes: ... + def flush(self, mode: int = ..., /) -> bytes: ... + + +class ZLibDecompressObjProtocol(Protocol): + def decompress(self, data: Buffer, max_length: int = ...) -> bytes: ... + def flush(self, length: int = ..., /) -> bytes: ... + + @property + def eof(self) -> bool: ... + + +class ZLibBackendProtocol(Protocol): + MAX_WBITS: int + Z_FULL_FLUSH: int + Z_SYNC_FLUSH: int + Z_BEST_SPEED: int + Z_FINISH: int + + def compressobj( + self, + level: int = ..., + method: int = ..., + wbits: int = ..., + memLevel: int = ..., + strategy: int = ..., + zdict: Optional[Buffer] = ..., + ) -> ZLibCompressObjProtocol: ... + def decompressobj( + self, wbits: int = ..., zdict: Buffer = ... + ) -> ZLibDecompressObjProtocol: ... + + def compress( + self, data: Buffer, /, level: int = ..., wbits: int = ... + ) -> bytes: ... + def decompress( + self, data: Buffer, /, wbits: int = ..., bufsize: int = ... + ) -> bytes: ... + + +class CompressObjArgs(TypedDict, total=False): + wbits: int + strategy: int + level: int + + +class ZLibBackendWrapper: + def __init__(self, _zlib_backend: ZLibBackendProtocol): + self._zlib_backend: ZLibBackendProtocol = _zlib_backend + + @property + def name(self) -> str: + return getattr(self._zlib_backend, "__name__", "undefined") + + @property + def MAX_WBITS(self) -> int: + return self._zlib_backend.MAX_WBITS + + @property + def Z_FULL_FLUSH(self) -> int: + return self._zlib_backend.Z_FULL_FLUSH + + @property + def Z_SYNC_FLUSH(self) -> int: + return self._zlib_backend.Z_SYNC_FLUSH + + @property + def Z_BEST_SPEED(self) -> int: + return self._zlib_backend.Z_BEST_SPEED + + @property + def Z_FINISH(self) -> int: + return self._zlib_backend.Z_FINISH + + def compressobj(self, *args: Any, **kwargs: Any) -> ZLibCompressObjProtocol: + return self._zlib_backend.compressobj(*args, **kwargs) + + def decompressobj(self, *args: Any, **kwargs: Any) -> ZLibDecompressObjProtocol: + return self._zlib_backend.decompressobj(*args, **kwargs) + + def compress(self, data: Buffer, *args: Any, **kwargs: Any) -> bytes: + return self._zlib_backend.compress(data, *args, **kwargs) + + def decompress(self, data: Buffer, *args: Any, **kwargs: Any) -> bytes: + return self._zlib_backend.decompress(data, *args, **kwargs) + + # Everything not explicitly listed in the Protocol we just pass through + def __getattr__(self, attrname: str) -> Any: + return getattr(self._zlib_backend, attrname) + + +ZLibBackend: ZLibBackendWrapper = ZLibBackendWrapper(zlib) + + +def set_zlib_backend(new_zlib_backend: ZLibBackendProtocol) -> None: + ZLibBackend._zlib_backend = new_zlib_backend + + +def encoding_to_mode( + encoding: Optional[str] = None, + suppress_deflate_header: bool = False, +) -> int: + if encoding == "gzip": + return 16 + ZLibBackend.MAX_WBITS + + return -ZLibBackend.MAX_WBITS if suppress_deflate_header else ZLibBackend.MAX_WBITS + + +class ZlibBaseHandler: + def __init__( + self, + mode: int, + executor: Optional[Executor] = None, + max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE, + ): + self._mode = mode + self._executor = executor + self._max_sync_chunk_size = max_sync_chunk_size + + +class ZLibCompressor(ZlibBaseHandler): + def __init__( + self, + encoding: Optional[str] = None, + suppress_deflate_header: bool = False, + level: Optional[int] = None, + wbits: Optional[int] = None, + strategy: Optional[int] = None, + executor: Optional[Executor] = None, + max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE, + ): + super().__init__( + mode=( + encoding_to_mode(encoding, suppress_deflate_header) + if wbits is None + else wbits + ), + executor=executor, + max_sync_chunk_size=max_sync_chunk_size, + ) + self._zlib_backend: Final = ZLibBackendWrapper(ZLibBackend._zlib_backend) + + kwargs: CompressObjArgs = {} + kwargs["wbits"] = self._mode + if strategy is not None: + kwargs["strategy"] = strategy + if level is not None: + kwargs["level"] = level + self._compressor = self._zlib_backend.compressobj(**kwargs) + self._compress_lock = asyncio.Lock() + + def compress_sync(self, data: bytes) -> bytes: + return self._compressor.compress(data) + + async def compress(self, data: bytes) -> bytes: + """Compress the data and returned the compressed bytes. + + Note that flush() must be called after the last call to compress() + + If the data size is large than the max_sync_chunk_size, the compression + will be done in the executor. Otherwise, the compression will be done + in the event loop. + """ + async with self._compress_lock: + # To ensure the stream is consistent in the event + # there are multiple writers, we need to lock + # the compressor so that only one writer can + # compress at a time. + if ( + self._max_sync_chunk_size is not None + and len(data) > self._max_sync_chunk_size + ): + return await asyncio.get_running_loop().run_in_executor( + self._executor, self._compressor.compress, data + ) + return self.compress_sync(data) + + def flush(self, mode: Optional[int] = None) -> bytes: + return self._compressor.flush( + mode if mode is not None else self._zlib_backend.Z_FINISH + ) + + +class ZLibDecompressor(ZlibBaseHandler): + def __init__( + self, + encoding: Optional[str] = None, + suppress_deflate_header: bool = False, + executor: Optional[Executor] = None, + max_sync_chunk_size: Optional[int] = MAX_SYNC_CHUNK_SIZE, + ): + super().__init__( + mode=encoding_to_mode(encoding, suppress_deflate_header), + executor=executor, + max_sync_chunk_size=max_sync_chunk_size, + ) + self._zlib_backend: Final = ZLibBackendWrapper(ZLibBackend._zlib_backend) + self._decompressor = self._zlib_backend.decompressobj(wbits=self._mode) + + def decompress_sync(self, data: bytes, max_length: int = 0) -> bytes: + return self._decompressor.decompress(data, max_length) + + async def decompress(self, data: bytes, max_length: int = 0) -> bytes: + """Decompress the data and return the decompressed bytes. + + If the data size is large than the max_sync_chunk_size, the decompression + will be done in the executor. Otherwise, the decompression will be done + in the event loop. + """ + if ( + self._max_sync_chunk_size is not None + and len(data) > self._max_sync_chunk_size + ): + return await asyncio.get_running_loop().run_in_executor( + self._executor, self._decompressor.decompress, data, max_length + ) + return self.decompress_sync(data, max_length) + + def flush(self, length: int = 0) -> bytes: + return ( + self._decompressor.flush(length) + if length > 0 + else self._decompressor.flush() + ) + + @property + def eof(self) -> bool: + return self._decompressor.eof + + +class BrotliDecompressor: + # Supports both 'brotlipy' and 'Brotli' packages + # since they share an import name. The top branches + # are for 'brotlipy' and bottom branches for 'Brotli' + def __init__(self) -> None: + if not HAS_BROTLI: + raise RuntimeError( + "The brotli decompression is not available. " + "Please install `Brotli` module" + ) + self._obj = brotli.Decompressor() + + def decompress_sync(self, data: bytes) -> bytes: + if hasattr(self._obj, "decompress"): + return cast(bytes, self._obj.decompress(data)) + return cast(bytes, self._obj.process(data)) + + def flush(self) -> bytes: + if hasattr(self._obj, "flush"): + return cast(bytes, self._obj.flush()) + return b"" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/connector.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/connector.py new file mode 100644 index 0000000000000000000000000000000000000000..0fbacde3b42f232d2ddc2b6c3967a184ba22c252 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/connector.py @@ -0,0 +1,1834 @@ +import asyncio +import functools +import random +import socket +import sys +import traceback +import warnings +from collections import OrderedDict, defaultdict, deque +from contextlib import suppress +from http import HTTPStatus +from itertools import chain, cycle, islice +from time import monotonic +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + DefaultDict, + Deque, + Dict, + Iterator, + List, + Literal, + Optional, + Sequence, + Set, + Tuple, + Type, + Union, + cast, +) + +import aiohappyeyeballs +from aiohappyeyeballs import AddrInfoType, SocketFactoryType + +from . import hdrs, helpers +from .abc import AbstractResolver, ResolveResult +from .client_exceptions import ( + ClientConnectionError, + ClientConnectorCertificateError, + ClientConnectorDNSError, + ClientConnectorError, + ClientConnectorSSLError, + ClientHttpProxyError, + ClientProxyConnectionError, + ServerFingerprintMismatch, + UnixClientConnectorError, + cert_errors, + ssl_errors, +) +from .client_proto import ResponseHandler +from .client_reqrep import ClientRequest, Fingerprint, _merge_ssl_params +from .helpers import ( + _SENTINEL, + ceil_timeout, + is_ip_address, + noop, + sentinel, + set_exception, + set_result, +) +from .log import client_logger +from .resolver import DefaultResolver + +if sys.version_info >= (3, 12): + from collections.abc import Buffer +else: + Buffer = Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"] + +if TYPE_CHECKING: + import ssl + + SSLContext = ssl.SSLContext +else: + try: + import ssl + + SSLContext = ssl.SSLContext + except ImportError: # pragma: no cover + ssl = None # type: ignore[assignment] + SSLContext = object # type: ignore[misc,assignment] + +EMPTY_SCHEMA_SET = frozenset({""}) +HTTP_SCHEMA_SET = frozenset({"http", "https"}) +WS_SCHEMA_SET = frozenset({"ws", "wss"}) + +HTTP_AND_EMPTY_SCHEMA_SET = HTTP_SCHEMA_SET | EMPTY_SCHEMA_SET +HIGH_LEVEL_SCHEMA_SET = HTTP_AND_EMPTY_SCHEMA_SET | WS_SCHEMA_SET + +NEEDS_CLEANUP_CLOSED = (3, 13, 0) <= sys.version_info < ( + 3, + 13, + 1, +) or sys.version_info < (3, 12, 7) +# Cleanup closed is no longer needed after https://github.com/python/cpython/pull/118960 +# which first appeared in Python 3.12.7 and 3.13.1 + + +__all__ = ( + "BaseConnector", + "TCPConnector", + "UnixConnector", + "NamedPipeConnector", + "AddrInfoType", + "SocketFactoryType", +) + + +if TYPE_CHECKING: + from .client import ClientTimeout + from .client_reqrep import ConnectionKey + from .tracing import Trace + + +class _DeprecationWaiter: + __slots__ = ("_awaitable", "_awaited") + + def __init__(self, awaitable: Awaitable[Any]) -> None: + self._awaitable = awaitable + self._awaited = False + + def __await__(self) -> Any: + self._awaited = True + return self._awaitable.__await__() + + def __del__(self) -> None: + if not self._awaited: + warnings.warn( + "Connector.close() is a coroutine, " + "please use await connector.close()", + DeprecationWarning, + ) + + +async def _wait_for_close(waiters: List[Awaitable[object]]) -> None: + """Wait for all waiters to finish closing.""" + results = await asyncio.gather(*waiters, return_exceptions=True) + for res in results: + if isinstance(res, Exception): + client_logger.debug("Error while closing connector: %r", res) + + +class Connection: + + _source_traceback = None + + def __init__( + self, + connector: "BaseConnector", + key: "ConnectionKey", + protocol: ResponseHandler, + loop: asyncio.AbstractEventLoop, + ) -> None: + self._key = key + self._connector = connector + self._loop = loop + self._protocol: Optional[ResponseHandler] = protocol + self._callbacks: List[Callable[[], None]] = [] + + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + def __repr__(self) -> str: + return f"Connection<{self._key}>" + + def __del__(self, _warnings: Any = warnings) -> None: + if self._protocol is not None: + kwargs = {"source": self} + _warnings.warn(f"Unclosed connection {self!r}", ResourceWarning, **kwargs) + if self._loop.is_closed(): + return + + self._connector._release(self._key, self._protocol, should_close=True) + + context = {"client_connection": self, "message": "Unclosed connection"} + if self._source_traceback is not None: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + def __bool__(self) -> Literal[True]: + """Force subclasses to not be falsy, to make checks simpler.""" + return True + + @property + def loop(self) -> asyncio.AbstractEventLoop: + warnings.warn( + "connector.loop property is deprecated", DeprecationWarning, stacklevel=2 + ) + return self._loop + + @property + def transport(self) -> Optional[asyncio.Transport]: + if self._protocol is None: + return None + return self._protocol.transport + + @property + def protocol(self) -> Optional[ResponseHandler]: + return self._protocol + + def add_callback(self, callback: Callable[[], None]) -> None: + if callback is not None: + self._callbacks.append(callback) + + def _notify_release(self) -> None: + callbacks, self._callbacks = self._callbacks[:], [] + + for cb in callbacks: + with suppress(Exception): + cb() + + def close(self) -> None: + self._notify_release() + + if self._protocol is not None: + self._connector._release(self._key, self._protocol, should_close=True) + self._protocol = None + + def release(self) -> None: + self._notify_release() + + if self._protocol is not None: + self._connector._release(self._key, self._protocol) + self._protocol = None + + @property + def closed(self) -> bool: + return self._protocol is None or not self._protocol.is_connected() + + +class _ConnectTunnelConnection(Connection): + """Special connection wrapper for CONNECT tunnels that must never be pooled. + + This connection wraps the proxy connection that will be upgraded with TLS. + It must never be released to the pool because: + 1. Its 'closed' future will never complete, causing session.close() to hang + 2. It represents an intermediate state, not a reusable connection + 3. The real connection (with TLS) will be created separately + """ + + def release(self) -> None: + """Do nothing - don't pool or close the connection. + + These connections are an intermediate state during the CONNECT tunnel + setup and will be cleaned up naturally after the TLS upgrade. If they + were to be pooled, they would never be properly closed, causing + session.close() to wait forever for their 'closed' future. + """ + + +class _TransportPlaceholder: + """placeholder for BaseConnector.connect function""" + + __slots__ = ("closed", "transport") + + def __init__(self, closed_future: asyncio.Future[Optional[Exception]]) -> None: + """Initialize a placeholder for a transport.""" + self.closed = closed_future + self.transport = None + + def close(self) -> None: + """Close the placeholder.""" + + def abort(self) -> None: + """Abort the placeholder (does nothing).""" + + +class BaseConnector: + """Base connector class. + + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + enable_cleanup_closed - Enables clean-up closed ssl transports. + Disabled by default. + timeout_ceil_threshold - Trigger ceiling of timeout values when + it's above timeout_ceil_threshold. + loop - Optional event loop. + """ + + _closed = True # prevent AttributeError in __del__ if ctor was failed + _source_traceback = None + + # abort transport after 2 seconds (cleanup broken connections) + _cleanup_closed_period = 2.0 + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET + + def __init__( + self, + *, + keepalive_timeout: Union[object, None, float] = sentinel, + force_close: bool = False, + limit: int = 100, + limit_per_host: int = 0, + enable_cleanup_closed: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + timeout_ceil_threshold: float = 5, + ) -> None: + + if force_close: + if keepalive_timeout is not None and keepalive_timeout is not sentinel: + raise ValueError( + "keepalive_timeout cannot be set if force_close is True" + ) + else: + if keepalive_timeout is sentinel: + keepalive_timeout = 15.0 + + loop = loop or asyncio.get_running_loop() + self._timeout_ceil_threshold = timeout_ceil_threshold + + self._closed = False + if loop.get_debug(): + self._source_traceback = traceback.extract_stack(sys._getframe(1)) + + # Connection pool of reusable connections. + # We use a deque to store connections because it has O(1) popleft() + # and O(1) append() operations to implement a FIFO queue. + self._conns: DefaultDict[ + ConnectionKey, Deque[Tuple[ResponseHandler, float]] + ] = defaultdict(deque) + self._limit = limit + self._limit_per_host = limit_per_host + self._acquired: Set[ResponseHandler] = set() + self._acquired_per_host: DefaultDict[ConnectionKey, Set[ResponseHandler]] = ( + defaultdict(set) + ) + self._keepalive_timeout = cast(float, keepalive_timeout) + self._force_close = force_close + + # {host_key: FIFO list of waiters} + # The FIFO is implemented with an OrderedDict with None keys because + # python does not have an ordered set. + self._waiters: DefaultDict[ + ConnectionKey, OrderedDict[asyncio.Future[None], None] + ] = defaultdict(OrderedDict) + + self._loop = loop + self._factory = functools.partial(ResponseHandler, loop=loop) + + # start keep-alive connection cleanup task + self._cleanup_handle: Optional[asyncio.TimerHandle] = None + + # start cleanup closed transports task + self._cleanup_closed_handle: Optional[asyncio.TimerHandle] = None + + if enable_cleanup_closed and not NEEDS_CLEANUP_CLOSED: + warnings.warn( + "enable_cleanup_closed ignored because " + "https://github.com/python/cpython/pull/118960 is fixed " + f"in Python version {sys.version_info}", + DeprecationWarning, + stacklevel=2, + ) + enable_cleanup_closed = False + + self._cleanup_closed_disabled = not enable_cleanup_closed + self._cleanup_closed_transports: List[Optional[asyncio.Transport]] = [] + self._placeholder_future: asyncio.Future[Optional[Exception]] = ( + loop.create_future() + ) + self._placeholder_future.set_result(None) + self._cleanup_closed() + + def __del__(self, _warnings: Any = warnings) -> None: + if self._closed: + return + if not self._conns: + return + + conns = [repr(c) for c in self._conns.values()] + + self._close() + + kwargs = {"source": self} + _warnings.warn(f"Unclosed connector {self!r}", ResourceWarning, **kwargs) + context = { + "connector": self, + "connections": conns, + "message": "Unclosed connector", + } + if self._source_traceback is not None: + context["source_traceback"] = self._source_traceback + self._loop.call_exception_handler(context) + + def __enter__(self) -> "BaseConnector": + warnings.warn( + '"with Connector():" is deprecated, ' + 'use "async with Connector():" instead', + DeprecationWarning, + ) + return self + + def __exit__(self, *exc: Any) -> None: + self._close() + + async def __aenter__(self) -> "BaseConnector": + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + exc_traceback: Optional[TracebackType] = None, + ) -> None: + await self.close() + + @property + def force_close(self) -> bool: + """Ultimately close connection on releasing if True.""" + return self._force_close + + @property + def limit(self) -> int: + """The total number for simultaneous connections. + + If limit is 0 the connector has no limit. + The default limit size is 100. + """ + return self._limit + + @property + def limit_per_host(self) -> int: + """The limit for simultaneous connections to the same endpoint. + + Endpoints are the same if they are have equal + (host, port, is_ssl) triple. + """ + return self._limit_per_host + + def _cleanup(self) -> None: + """Cleanup unused transports.""" + if self._cleanup_handle: + self._cleanup_handle.cancel() + # _cleanup_handle should be unset, otherwise _release() will not + # recreate it ever! + self._cleanup_handle = None + + now = monotonic() + timeout = self._keepalive_timeout + + if self._conns: + connections = defaultdict(deque) + deadline = now - timeout + for key, conns in self._conns.items(): + alive: Deque[Tuple[ResponseHandler, float]] = deque() + for proto, use_time in conns: + if proto.is_connected() and use_time - deadline >= 0: + alive.append((proto, use_time)) + continue + transport = proto.transport + proto.close() + if not self._cleanup_closed_disabled and key.is_ssl: + self._cleanup_closed_transports.append(transport) + + if alive: + connections[key] = alive + + self._conns = connections + + if self._conns: + self._cleanup_handle = helpers.weakref_handle( + self, + "_cleanup", + timeout, + self._loop, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + + def _cleanup_closed(self) -> None: + """Double confirmation for transport close. + + Some broken ssl servers may leave socket open without proper close. + """ + if self._cleanup_closed_handle: + self._cleanup_closed_handle.cancel() + + for transport in self._cleanup_closed_transports: + if transport is not None: + transport.abort() + + self._cleanup_closed_transports = [] + + if not self._cleanup_closed_disabled: + self._cleanup_closed_handle = helpers.weakref_handle( + self, + "_cleanup_closed", + self._cleanup_closed_period, + self._loop, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + + def close(self, *, abort_ssl: bool = False) -> Awaitable[None]: + """Close all opened transports. + + :param abort_ssl: If True, SSL connections will be aborted immediately + without performing the shutdown handshake. This provides + faster cleanup at the cost of less graceful disconnection. + """ + if not (waiters := self._close(abort_ssl=abort_ssl)): + # If there are no connections to close, we can return a noop + # awaitable to avoid scheduling a task on the event loop. + return _DeprecationWaiter(noop()) + coro = _wait_for_close(waiters) + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to close connections + # immediately to avoid having to schedule the task on the event loop. + task = asyncio.Task(coro, loop=self._loop, eager_start=True) + else: + task = self._loop.create_task(coro) + return _DeprecationWaiter(task) + + def _close(self, *, abort_ssl: bool = False) -> List[Awaitable[object]]: + waiters: List[Awaitable[object]] = [] + + if self._closed: + return waiters + + self._closed = True + + try: + if self._loop.is_closed(): + return waiters + + # cancel cleanup task + if self._cleanup_handle: + self._cleanup_handle.cancel() + + # cancel cleanup close task + if self._cleanup_closed_handle: + self._cleanup_closed_handle.cancel() + + for data in self._conns.values(): + for proto, _ in data: + if ( + abort_ssl + and proto.transport + and proto.transport.get_extra_info("sslcontext") is not None + ): + proto.abort() + else: + proto.close() + if closed := proto.closed: + waiters.append(closed) + + for proto in self._acquired: + if ( + abort_ssl + and proto.transport + and proto.transport.get_extra_info("sslcontext") is not None + ): + proto.abort() + else: + proto.close() + if closed := proto.closed: + waiters.append(closed) + + for transport in self._cleanup_closed_transports: + if transport is not None: + transport.abort() + + return waiters + + finally: + self._conns.clear() + self._acquired.clear() + for keyed_waiters in self._waiters.values(): + for keyed_waiter in keyed_waiters: + keyed_waiter.cancel() + self._waiters.clear() + self._cleanup_handle = None + self._cleanup_closed_transports.clear() + self._cleanup_closed_handle = None + + @property + def closed(self) -> bool: + """Is connector closed. + + A readonly property. + """ + return self._closed + + def _available_connections(self, key: "ConnectionKey") -> int: + """ + Return number of available connections. + + The limit, limit_per_host and the connection key are taken into account. + + If it returns less than 1 means that there are no connections + available. + """ + # check total available connections + # If there are no limits, this will always return 1 + total_remain = 1 + + if self._limit and (total_remain := self._limit - len(self._acquired)) <= 0: + return total_remain + + # check limit per host + if host_remain := self._limit_per_host: + if acquired := self._acquired_per_host.get(key): + host_remain -= len(acquired) + if total_remain > host_remain: + return host_remain + + return total_remain + + async def connect( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> Connection: + """Get from pool or create new connection.""" + key = req.connection_key + if (conn := await self._get(key, traces)) is not None: + # If we do not have to wait and we can get a connection from the pool + # we can avoid the timeout ceil logic and directly return the connection + return conn + + async with ceil_timeout(timeout.connect, timeout.ceil_threshold): + if self._available_connections(key) <= 0: + await self._wait_for_available_connection(key, traces) + if (conn := await self._get(key, traces)) is not None: + return conn + + placeholder = cast( + ResponseHandler, _TransportPlaceholder(self._placeholder_future) + ) + self._acquired.add(placeholder) + if self._limit_per_host: + self._acquired_per_host[key].add(placeholder) + + try: + # Traces are done inside the try block to ensure that the + # that the placeholder is still cleaned up if an exception + # is raised. + if traces: + for trace in traces: + await trace.send_connection_create_start() + proto = await self._create_connection(req, traces, timeout) + if traces: + for trace in traces: + await trace.send_connection_create_end() + except BaseException: + self._release_acquired(key, placeholder) + raise + else: + if self._closed: + proto.close() + raise ClientConnectionError("Connector is closed.") + + # The connection was successfully created, drop the placeholder + # and add the real connection to the acquired set. There should + # be no awaits after the proto is added to the acquired set + # to ensure that the connection is not left in the acquired set + # on cancellation. + self._acquired.remove(placeholder) + self._acquired.add(proto) + if self._limit_per_host: + acquired_per_host = self._acquired_per_host[key] + acquired_per_host.remove(placeholder) + acquired_per_host.add(proto) + return Connection(self, key, proto, self._loop) + + async def _wait_for_available_connection( + self, key: "ConnectionKey", traces: List["Trace"] + ) -> None: + """Wait for an available connection slot.""" + # We loop here because there is a race between + # the connection limit check and the connection + # being acquired. If the connection is acquired + # between the check and the await statement, we + # need to loop again to check if the connection + # slot is still available. + attempts = 0 + while True: + fut: asyncio.Future[None] = self._loop.create_future() + keyed_waiters = self._waiters[key] + keyed_waiters[fut] = None + if attempts: + # If we have waited before, we need to move the waiter + # to the front of the queue as otherwise we might get + # starved and hit the timeout. + keyed_waiters.move_to_end(fut, last=False) + + try: + # Traces happen in the try block to ensure that the + # the waiter is still cleaned up if an exception is raised. + if traces: + for trace in traces: + await trace.send_connection_queued_start() + await fut + if traces: + for trace in traces: + await trace.send_connection_queued_end() + finally: + # pop the waiter from the queue if its still + # there and not already removed by _release_waiter + keyed_waiters.pop(fut, None) + if not self._waiters.get(key, True): + del self._waiters[key] + + if self._available_connections(key) > 0: + break + attempts += 1 + + async def _get( + self, key: "ConnectionKey", traces: List["Trace"] + ) -> Optional[Connection]: + """Get next reusable connection for the key or None. + + The connection will be marked as acquired. + """ + if (conns := self._conns.get(key)) is None: + return None + + t1 = monotonic() + while conns: + proto, t0 = conns.popleft() + # We will we reuse the connection if its connected and + # the keepalive timeout has not been exceeded + if proto.is_connected() and t1 - t0 <= self._keepalive_timeout: + if not conns: + # The very last connection was reclaimed: drop the key + del self._conns[key] + self._acquired.add(proto) + if self._limit_per_host: + self._acquired_per_host[key].add(proto) + if traces: + for trace in traces: + try: + await trace.send_connection_reuseconn() + except BaseException: + self._release_acquired(key, proto) + raise + return Connection(self, key, proto, self._loop) + + # Connection cannot be reused, close it + transport = proto.transport + proto.close() + # only for SSL transports + if not self._cleanup_closed_disabled and key.is_ssl: + self._cleanup_closed_transports.append(transport) + + # No more connections: drop the key + del self._conns[key] + return None + + def _release_waiter(self) -> None: + """ + Iterates over all waiters until one to be released is found. + + The one to be released is not finished and + belongs to a host that has available connections. + """ + if not self._waiters: + return + + # Having the dict keys ordered this avoids to iterate + # at the same order at each call. + queues = list(self._waiters) + random.shuffle(queues) + + for key in queues: + if self._available_connections(key) < 1: + continue + + waiters = self._waiters[key] + while waiters: + waiter, _ = waiters.popitem(last=False) + if not waiter.done(): + waiter.set_result(None) + return + + def _release_acquired(self, key: "ConnectionKey", proto: ResponseHandler) -> None: + """Release acquired connection.""" + if self._closed: + # acquired connection is already released on connector closing + return + + self._acquired.discard(proto) + if self._limit_per_host and (conns := self._acquired_per_host.get(key)): + conns.discard(proto) + if not conns: + del self._acquired_per_host[key] + self._release_waiter() + + def _release( + self, + key: "ConnectionKey", + protocol: ResponseHandler, + *, + should_close: bool = False, + ) -> None: + if self._closed: + # acquired connection is already released on connector closing + return + + self._release_acquired(key, protocol) + + if self._force_close or should_close or protocol.should_close: + transport = protocol.transport + protocol.close() + + if key.is_ssl and not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transport) + return + + self._conns[key].append((protocol, monotonic())) + + if self._cleanup_handle is None: + self._cleanup_handle = helpers.weakref_handle( + self, + "_cleanup", + self._keepalive_timeout, + self._loop, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + raise NotImplementedError() + + +class _DNSCacheTable: + def __init__(self, ttl: Optional[float] = None) -> None: + self._addrs_rr: Dict[Tuple[str, int], Tuple[Iterator[ResolveResult], int]] = {} + self._timestamps: Dict[Tuple[str, int], float] = {} + self._ttl = ttl + + def __contains__(self, host: object) -> bool: + return host in self._addrs_rr + + def add(self, key: Tuple[str, int], addrs: List[ResolveResult]) -> None: + self._addrs_rr[key] = (cycle(addrs), len(addrs)) + + if self._ttl is not None: + self._timestamps[key] = monotonic() + + def remove(self, key: Tuple[str, int]) -> None: + self._addrs_rr.pop(key, None) + + if self._ttl is not None: + self._timestamps.pop(key, None) + + def clear(self) -> None: + self._addrs_rr.clear() + self._timestamps.clear() + + def next_addrs(self, key: Tuple[str, int]) -> List[ResolveResult]: + loop, length = self._addrs_rr[key] + addrs = list(islice(loop, length)) + # Consume one more element to shift internal state of `cycle` + next(loop) + return addrs + + def expired(self, key: Tuple[str, int]) -> bool: + if self._ttl is None: + return False + + return self._timestamps[key] + self._ttl < monotonic() + + +def _make_ssl_context(verified: bool) -> SSLContext: + """Create SSL context. + + This method is not async-friendly and should be called from a thread + because it will load certificates from disk and do other blocking I/O. + """ + if ssl is None: + # No ssl support + return None + if verified: + sslcontext = ssl.create_default_context() + else: + sslcontext = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + sslcontext.options |= ssl.OP_NO_SSLv2 + sslcontext.options |= ssl.OP_NO_SSLv3 + sslcontext.check_hostname = False + sslcontext.verify_mode = ssl.CERT_NONE + sslcontext.options |= ssl.OP_NO_COMPRESSION + sslcontext.set_default_verify_paths() + sslcontext.set_alpn_protocols(("http/1.1",)) + return sslcontext + + +# The default SSLContext objects are created at import time +# since they do blocking I/O to load certificates from disk, +# and imports should always be done before the event loop starts +# or in a thread. +_SSL_CONTEXT_VERIFIED = _make_ssl_context(True) +_SSL_CONTEXT_UNVERIFIED = _make_ssl_context(False) + + +class TCPConnector(BaseConnector): + """TCP connector. + + verify_ssl - Set to True to check ssl certifications. + fingerprint - Pass the binary sha256 + digest of the expected certificate in DER format to verify + that the certificate the server presents matches. See also + https://en.wikipedia.org/wiki/HTTP_Public_Key_Pinning + resolver - Enable DNS lookups and use this + resolver + use_dns_cache - Use memory cache for DNS lookups. + ttl_dns_cache - Max seconds having cached a DNS entry, None forever. + family - socket address family + local_addr - local tuple of (host, port) to bind socket to + + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + enable_cleanup_closed - Enables clean-up closed ssl transports. + Disabled by default. + happy_eyeballs_delay - This is the “Connection Attempt Delay” + as defined in RFC 8305. To disable + the happy eyeballs algorithm, set to None. + interleave - “First Address Family Count” as defined in RFC 8305 + loop - Optional event loop. + socket_factory - A SocketFactoryType function that, if supplied, + will be used to create sockets given an + AddrInfoType. + ssl_shutdown_timeout - DEPRECATED. Will be removed in aiohttp 4.0. + Grace period for SSL shutdown handshake on TLS + connections. Default is 0 seconds (immediate abort). + This parameter allowed for a clean SSL shutdown by + notifying the remote peer of connection closure, + while avoiding excessive delays during connector cleanup. + Note: Only takes effect on Python 3.11+. + """ + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"tcp"}) + + def __init__( + self, + *, + verify_ssl: bool = True, + fingerprint: Optional[bytes] = None, + use_dns_cache: bool = True, + ttl_dns_cache: Optional[int] = 10, + family: socket.AddressFamily = socket.AddressFamily.AF_UNSPEC, + ssl_context: Optional[SSLContext] = None, + ssl: Union[bool, Fingerprint, SSLContext] = True, + local_addr: Optional[Tuple[str, int]] = None, + resolver: Optional[AbstractResolver] = None, + keepalive_timeout: Union[None, float, object] = sentinel, + force_close: bool = False, + limit: int = 100, + limit_per_host: int = 0, + enable_cleanup_closed: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + timeout_ceil_threshold: float = 5, + happy_eyeballs_delay: Optional[float] = 0.25, + interleave: Optional[int] = None, + socket_factory: Optional[SocketFactoryType] = None, + ssl_shutdown_timeout: Union[_SENTINEL, None, float] = sentinel, + ): + super().__init__( + keepalive_timeout=keepalive_timeout, + force_close=force_close, + limit=limit, + limit_per_host=limit_per_host, + enable_cleanup_closed=enable_cleanup_closed, + loop=loop, + timeout_ceil_threshold=timeout_ceil_threshold, + ) + + self._ssl = _merge_ssl_params(ssl, verify_ssl, ssl_context, fingerprint) + + self._resolver: AbstractResolver + if resolver is None: + self._resolver = DefaultResolver(loop=self._loop) + self._resolver_owner = True + else: + self._resolver = resolver + self._resolver_owner = False + + self._use_dns_cache = use_dns_cache + self._cached_hosts = _DNSCacheTable(ttl=ttl_dns_cache) + self._throttle_dns_futures: Dict[ + Tuple[str, int], Set["asyncio.Future[None]"] + ] = {} + self._family = family + self._local_addr_infos = aiohappyeyeballs.addr_to_addr_infos(local_addr) + self._happy_eyeballs_delay = happy_eyeballs_delay + self._interleave = interleave + self._resolve_host_tasks: Set["asyncio.Task[List[ResolveResult]]"] = set() + self._socket_factory = socket_factory + self._ssl_shutdown_timeout: Optional[float] + # Handle ssl_shutdown_timeout with warning for Python < 3.11 + if ssl_shutdown_timeout is sentinel: + self._ssl_shutdown_timeout = 0 + else: + # Deprecation warning for ssl_shutdown_timeout parameter + warnings.warn( + "The ssl_shutdown_timeout parameter is deprecated and will be removed in aiohttp 4.0", + DeprecationWarning, + stacklevel=2, + ) + if ( + sys.version_info < (3, 11) + and ssl_shutdown_timeout is not None + and ssl_shutdown_timeout != 0 + ): + warnings.warn( + f"ssl_shutdown_timeout={ssl_shutdown_timeout} is ignored on Python < 3.11; " + "only ssl_shutdown_timeout=0 is supported. The timeout will be ignored.", + RuntimeWarning, + stacklevel=2, + ) + self._ssl_shutdown_timeout = ssl_shutdown_timeout + + def _close(self, *, abort_ssl: bool = False) -> List[Awaitable[object]]: + """Close all ongoing DNS calls.""" + for fut in chain.from_iterable(self._throttle_dns_futures.values()): + fut.cancel() + + waiters = super()._close(abort_ssl=abort_ssl) + + for t in self._resolve_host_tasks: + t.cancel() + waiters.append(t) + + return waiters + + async def close(self, *, abort_ssl: bool = False) -> None: + """ + Close all opened transports. + + :param abort_ssl: If True, SSL connections will be aborted immediately + without performing the shutdown handshake. If False (default), + the behavior is determined by ssl_shutdown_timeout: + - If ssl_shutdown_timeout=0: connections are aborted + - If ssl_shutdown_timeout>0: graceful shutdown is performed + """ + if self._resolver_owner: + await self._resolver.close() + # Use abort_ssl param if explicitly set, otherwise use ssl_shutdown_timeout default + await super().close(abort_ssl=abort_ssl or self._ssl_shutdown_timeout == 0) + + @property + def family(self) -> int: + """Socket family like AF_INET.""" + return self._family + + @property + def use_dns_cache(self) -> bool: + """True if local DNS caching is enabled.""" + return self._use_dns_cache + + def clear_dns_cache( + self, host: Optional[str] = None, port: Optional[int] = None + ) -> None: + """Remove specified host/port or clear all dns local cache.""" + if host is not None and port is not None: + self._cached_hosts.remove((host, port)) + elif host is not None or port is not None: + raise ValueError("either both host and port or none of them are allowed") + else: + self._cached_hosts.clear() + + async def _resolve_host( + self, host: str, port: int, traces: Optional[Sequence["Trace"]] = None + ) -> List[ResolveResult]: + """Resolve host and return list of addresses.""" + if is_ip_address(host): + return [ + { + "hostname": host, + "host": host, + "port": port, + "family": self._family, + "proto": 0, + "flags": 0, + } + ] + + if not self._use_dns_cache: + + if traces: + for trace in traces: + await trace.send_dns_resolvehost_start(host) + + res = await self._resolver.resolve(host, port, family=self._family) + + if traces: + for trace in traces: + await trace.send_dns_resolvehost_end(host) + + return res + + key = (host, port) + if key in self._cached_hosts and not self._cached_hosts.expired(key): + # get result early, before any await (#4014) + result = self._cached_hosts.next_addrs(key) + + if traces: + for trace in traces: + await trace.send_dns_cache_hit(host) + return result + + futures: Set["asyncio.Future[None]"] + # + # If multiple connectors are resolving the same host, we wait + # for the first one to resolve and then use the result for all of them. + # We use a throttle to ensure that we only resolve the host once + # and then use the result for all the waiters. + # + if key in self._throttle_dns_futures: + # get futures early, before any await (#4014) + futures = self._throttle_dns_futures[key] + future: asyncio.Future[None] = self._loop.create_future() + futures.add(future) + if traces: + for trace in traces: + await trace.send_dns_cache_hit(host) + try: + await future + finally: + futures.discard(future) + return self._cached_hosts.next_addrs(key) + + # update dict early, before any await (#4014) + self._throttle_dns_futures[key] = futures = set() + # In this case we need to create a task to ensure that we can shield + # the task from cancellation as cancelling this lookup should not cancel + # the underlying lookup or else the cancel event will get broadcast to + # all the waiters across all connections. + # + coro = self._resolve_host_with_throttle(key, host, port, futures, traces) + loop = asyncio.get_running_loop() + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to send immediately + resolved_host_task = asyncio.Task(coro, loop=loop, eager_start=True) + else: + resolved_host_task = loop.create_task(coro) + + if not resolved_host_task.done(): + self._resolve_host_tasks.add(resolved_host_task) + resolved_host_task.add_done_callback(self._resolve_host_tasks.discard) + + try: + return await asyncio.shield(resolved_host_task) + except asyncio.CancelledError: + + def drop_exception(fut: "asyncio.Future[List[ResolveResult]]") -> None: + with suppress(Exception, asyncio.CancelledError): + fut.result() + + resolved_host_task.add_done_callback(drop_exception) + raise + + async def _resolve_host_with_throttle( + self, + key: Tuple[str, int], + host: str, + port: int, + futures: Set["asyncio.Future[None]"], + traces: Optional[Sequence["Trace"]], + ) -> List[ResolveResult]: + """Resolve host and set result for all waiters. + + This method must be run in a task and shielded from cancellation + to avoid cancelling the underlying lookup. + """ + try: + if traces: + for trace in traces: + await trace.send_dns_cache_miss(host) + + for trace in traces: + await trace.send_dns_resolvehost_start(host) + + addrs = await self._resolver.resolve(host, port, family=self._family) + if traces: + for trace in traces: + await trace.send_dns_resolvehost_end(host) + + self._cached_hosts.add(key, addrs) + for fut in futures: + set_result(fut, None) + except BaseException as e: + # any DNS exception is set for the waiters to raise the same exception. + # This coro is always run in task that is shielded from cancellation so + # we should never be propagating cancellation here. + for fut in futures: + set_exception(fut, e) + raise + finally: + self._throttle_dns_futures.pop(key) + + return self._cached_hosts.next_addrs(key) + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + """Create connection. + + Has same keyword arguments as BaseEventLoop.create_connection. + """ + if req.proxy: + _, proto = await self._create_proxy_connection(req, traces, timeout) + else: + _, proto = await self._create_direct_connection(req, traces, timeout) + + return proto + + def _get_ssl_context(self, req: ClientRequest) -> Optional[SSLContext]: + """Logic to get the correct SSL context + + 0. if req.ssl is false, return None + + 1. if ssl_context is specified in req, use it + 2. if _ssl_context is specified in self, use it + 3. otherwise: + 1. if verify_ssl is not specified in req, use self.ssl_context + (will generate a default context according to self.verify_ssl) + 2. if verify_ssl is True in req, generate a default SSL context + 3. if verify_ssl is False in req, generate a SSL context that + won't verify + """ + if not req.is_ssl(): + return None + + if ssl is None: # pragma: no cover + raise RuntimeError("SSL is not supported.") + sslcontext = req.ssl + if isinstance(sslcontext, ssl.SSLContext): + return sslcontext + if sslcontext is not True: + # not verified or fingerprinted + return _SSL_CONTEXT_UNVERIFIED + sslcontext = self._ssl + if isinstance(sslcontext, ssl.SSLContext): + return sslcontext + if sslcontext is not True: + # not verified or fingerprinted + return _SSL_CONTEXT_UNVERIFIED + return _SSL_CONTEXT_VERIFIED + + def _get_fingerprint(self, req: ClientRequest) -> Optional["Fingerprint"]: + ret = req.ssl + if isinstance(ret, Fingerprint): + return ret + ret = self._ssl + if isinstance(ret, Fingerprint): + return ret + return None + + async def _wrap_create_connection( + self, + *args: Any, + addr_infos: List[AddrInfoType], + req: ClientRequest, + timeout: "ClientTimeout", + client_error: Type[Exception] = ClientConnectorError, + **kwargs: Any, + ) -> Tuple[asyncio.Transport, ResponseHandler]: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + sock = await aiohappyeyeballs.start_connection( + addr_infos=addr_infos, + local_addr_infos=self._local_addr_infos, + happy_eyeballs_delay=self._happy_eyeballs_delay, + interleave=self._interleave, + loop=self._loop, + socket_factory=self._socket_factory, + ) + # Add ssl_shutdown_timeout for Python 3.11+ when SSL is used + if ( + kwargs.get("ssl") + and self._ssl_shutdown_timeout + and sys.version_info >= (3, 11) + ): + kwargs["ssl_shutdown_timeout"] = self._ssl_shutdown_timeout + return await self._loop.create_connection(*args, **kwargs, sock=sock) + except cert_errors as exc: + raise ClientConnectorCertificateError(req.connection_key, exc) from exc + except ssl_errors as exc: + raise ClientConnectorSSLError(req.connection_key, exc) from exc + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise client_error(req.connection_key, exc) from exc + + async def _wrap_existing_connection( + self, + *args: Any, + req: ClientRequest, + timeout: "ClientTimeout", + client_error: Type[Exception] = ClientConnectorError, + **kwargs: Any, + ) -> Tuple[asyncio.Transport, ResponseHandler]: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + return await self._loop.create_connection(*args, **kwargs) + except cert_errors as exc: + raise ClientConnectorCertificateError(req.connection_key, exc) from exc + except ssl_errors as exc: + raise ClientConnectorSSLError(req.connection_key, exc) from exc + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise client_error(req.connection_key, exc) from exc + + def _fail_on_no_start_tls(self, req: "ClientRequest") -> None: + """Raise a :py:exc:`RuntimeError` on missing ``start_tls()``. + + It is necessary for TLS-in-TLS so that it is possible to + send HTTPS queries through HTTPS proxies. + + This doesn't affect regular HTTP requests, though. + """ + if not req.is_ssl(): + return + + proxy_url = req.proxy + assert proxy_url is not None + if proxy_url.scheme != "https": + return + + self._check_loop_for_start_tls() + + def _check_loop_for_start_tls(self) -> None: + try: + self._loop.start_tls + except AttributeError as attr_exc: + raise RuntimeError( + "An HTTPS request is being sent through an HTTPS proxy. " + "This needs support for TLS in TLS but it is not implemented " + "in your runtime for the stdlib asyncio.\n\n" + "Please upgrade to Python 3.11 or higher. For more details, " + "please see:\n" + "* https://bugs.python.org/issue37179\n" + "* https://github.com/python/cpython/pull/28073\n" + "* https://docs.aiohttp.org/en/stable/" + "client_advanced.html#proxy-support\n" + "* https://github.com/aio-libs/aiohttp/discussions/6044\n", + ) from attr_exc + + def _loop_supports_start_tls(self) -> bool: + try: + self._check_loop_for_start_tls() + except RuntimeError: + return False + else: + return True + + def _warn_about_tls_in_tls( + self, + underlying_transport: asyncio.Transport, + req: ClientRequest, + ) -> None: + """Issue a warning if the requested URL has HTTPS scheme.""" + if req.request_info.url.scheme != "https": + return + + # Check if uvloop is being used, which supports TLS in TLS, + # otherwise assume that asyncio's native transport is being used. + if type(underlying_transport).__module__.startswith("uvloop"): + return + + # Support in asyncio was added in Python 3.11 (bpo-44011) + asyncio_supports_tls_in_tls = sys.version_info >= (3, 11) or getattr( + underlying_transport, + "_start_tls_compatible", + False, + ) + + if asyncio_supports_tls_in_tls: + return + + warnings.warn( + "An HTTPS request is being sent through an HTTPS proxy. " + "This support for TLS in TLS is known to be disabled " + "in the stdlib asyncio (Python <3.11). This is why you'll probably see " + "an error in the log below.\n\n" + "It is possible to enable it via monkeypatching. " + "For more details, see:\n" + "* https://bugs.python.org/issue37179\n" + "* https://github.com/python/cpython/pull/28073\n\n" + "You can temporarily patch this as follows:\n" + "* https://docs.aiohttp.org/en/stable/client_advanced.html#proxy-support\n" + "* https://github.com/aio-libs/aiohttp/discussions/6044\n", + RuntimeWarning, + source=self, + # Why `4`? At least 3 of the calls in the stack originate + # from the methods in this class. + stacklevel=3, + ) + + async def _start_tls_connection( + self, + underlying_transport: asyncio.Transport, + req: ClientRequest, + timeout: "ClientTimeout", + client_error: Type[Exception] = ClientConnectorError, + ) -> Tuple[asyncio.BaseTransport, ResponseHandler]: + """Wrap the raw TCP transport with TLS.""" + tls_proto = self._factory() # Create a brand new proto for TLS + sslcontext = self._get_ssl_context(req) + if TYPE_CHECKING: + # _start_tls_connection is unreachable in the current code path + # if sslcontext is None. + assert sslcontext is not None + + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + try: + # ssl_shutdown_timeout is only available in Python 3.11+ + if sys.version_info >= (3, 11) and self._ssl_shutdown_timeout: + tls_transport = await self._loop.start_tls( + underlying_transport, + tls_proto, + sslcontext, + server_hostname=req.server_hostname or req.host, + ssl_handshake_timeout=timeout.total, + ssl_shutdown_timeout=self._ssl_shutdown_timeout, + ) + else: + tls_transport = await self._loop.start_tls( + underlying_transport, + tls_proto, + sslcontext, + server_hostname=req.server_hostname or req.host, + ssl_handshake_timeout=timeout.total, + ) + except BaseException: + # We need to close the underlying transport since + # `start_tls()` probably failed before it had a + # chance to do this: + if self._ssl_shutdown_timeout == 0: + underlying_transport.abort() + else: + underlying_transport.close() + raise + if isinstance(tls_transport, asyncio.Transport): + fingerprint = self._get_fingerprint(req) + if fingerprint: + try: + fingerprint.check(tls_transport) + except ServerFingerprintMismatch: + tls_transport.close() + if not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(tls_transport) + raise + except cert_errors as exc: + raise ClientConnectorCertificateError(req.connection_key, exc) from exc + except ssl_errors as exc: + raise ClientConnectorSSLError(req.connection_key, exc) from exc + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise client_error(req.connection_key, exc) from exc + except TypeError as type_err: + # Example cause looks like this: + # TypeError: transport is not supported by start_tls() + + raise ClientConnectionError( + "Cannot initialize a TLS-in-TLS connection to host " + f"{req.host!s}:{req.port:d} through an underlying connection " + f"to an HTTPS proxy {req.proxy!s} ssl:{req.ssl or 'default'} " + f"[{type_err!s}]" + ) from type_err + else: + if tls_transport is None: + msg = "Failed to start TLS (possibly caused by closing transport)" + raise client_error(req.connection_key, OSError(msg)) + tls_proto.connection_made( + tls_transport + ) # Kick the state machine of the new TLS protocol + + return tls_transport, tls_proto + + def _convert_hosts_to_addr_infos( + self, hosts: List[ResolveResult] + ) -> List[AddrInfoType]: + """Converts the list of hosts to a list of addr_infos. + + The list of hosts is the result of a DNS lookup. The list of + addr_infos is the result of a call to `socket.getaddrinfo()`. + """ + addr_infos: List[AddrInfoType] = [] + for hinfo in hosts: + host = hinfo["host"] + is_ipv6 = ":" in host + family = socket.AF_INET6 if is_ipv6 else socket.AF_INET + if self._family and self._family != family: + continue + addr = (host, hinfo["port"], 0, 0) if is_ipv6 else (host, hinfo["port"]) + addr_infos.append( + (family, socket.SOCK_STREAM, socket.IPPROTO_TCP, "", addr) + ) + return addr_infos + + async def _create_direct_connection( + self, + req: ClientRequest, + traces: List["Trace"], + timeout: "ClientTimeout", + *, + client_error: Type[Exception] = ClientConnectorError, + ) -> Tuple[asyncio.Transport, ResponseHandler]: + sslcontext = self._get_ssl_context(req) + fingerprint = self._get_fingerprint(req) + + host = req.url.raw_host + assert host is not None + # Replace multiple trailing dots with a single one. + # A trailing dot is only present for fully-qualified domain names. + # See https://github.com/aio-libs/aiohttp/pull/7364. + if host.endswith(".."): + host = host.rstrip(".") + "." + port = req.port + assert port is not None + try: + # Cancelling this lookup should not cancel the underlying lookup + # or else the cancel event will get broadcast to all the waiters + # across all connections. + hosts = await self._resolve_host(host, port, traces=traces) + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + # in case of proxy it is not ClientProxyConnectionError + # it is problem of resolving proxy ip itself + raise ClientConnectorDNSError(req.connection_key, exc) from exc + + last_exc: Optional[Exception] = None + addr_infos = self._convert_hosts_to_addr_infos(hosts) + while addr_infos: + # Strip trailing dots, certificates contain FQDN without dots. + # See https://github.com/aio-libs/aiohttp/issues/3636 + server_hostname = ( + (req.server_hostname or host).rstrip(".") if sslcontext else None + ) + + try: + transp, proto = await self._wrap_create_connection( + self._factory, + timeout=timeout, + ssl=sslcontext, + addr_infos=addr_infos, + server_hostname=server_hostname, + req=req, + client_error=client_error, + ) + except (ClientConnectorError, asyncio.TimeoutError) as exc: + last_exc = exc + aiohappyeyeballs.pop_addr_infos_interleave(addr_infos, self._interleave) + continue + + if req.is_ssl() and fingerprint: + try: + fingerprint.check(transp) + except ServerFingerprintMismatch as exc: + transp.close() + if not self._cleanup_closed_disabled: + self._cleanup_closed_transports.append(transp) + last_exc = exc + # Remove the bad peer from the list of addr_infos + sock: socket.socket = transp.get_extra_info("socket") + bad_peer = sock.getpeername() + aiohappyeyeballs.remove_addr_infos(addr_infos, bad_peer) + continue + + return transp, proto + else: + assert last_exc is not None + raise last_exc + + async def _create_proxy_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> Tuple[asyncio.BaseTransport, ResponseHandler]: + self._fail_on_no_start_tls(req) + runtime_has_start_tls = self._loop_supports_start_tls() + + headers: Dict[str, str] = {} + if req.proxy_headers is not None: + headers = req.proxy_headers # type: ignore[assignment] + headers[hdrs.HOST] = req.headers[hdrs.HOST] + + url = req.proxy + assert url is not None + proxy_req = ClientRequest( + hdrs.METH_GET, + url, + headers=headers, + auth=req.proxy_auth, + loop=self._loop, + ssl=req.ssl, + ) + + # create connection to proxy server + transport, proto = await self._create_direct_connection( + proxy_req, [], timeout, client_error=ClientProxyConnectionError + ) + + auth = proxy_req.headers.pop(hdrs.AUTHORIZATION, None) + if auth is not None: + if not req.is_ssl(): + req.headers[hdrs.PROXY_AUTHORIZATION] = auth + else: + proxy_req.headers[hdrs.PROXY_AUTHORIZATION] = auth + + if req.is_ssl(): + if runtime_has_start_tls: + self._warn_about_tls_in_tls(transport, req) + + # For HTTPS requests over HTTP proxy + # we must notify proxy to tunnel connection + # so we send CONNECT command: + # CONNECT www.python.org:443 HTTP/1.1 + # Host: www.python.org + # + # next we must do TLS handshake and so on + # to do this we must wrap raw socket into secure one + # asyncio handles this perfectly + proxy_req.method = hdrs.METH_CONNECT + proxy_req.url = req.url + key = req.connection_key._replace( + proxy=None, proxy_auth=None, proxy_headers_hash=None + ) + conn = _ConnectTunnelConnection(self, key, proto, self._loop) + proxy_resp = await proxy_req.send(conn) + try: + protocol = conn._protocol + assert protocol is not None + + # read_until_eof=True will ensure the connection isn't closed + # once the response is received and processed allowing + # START_TLS to work on the connection below. + protocol.set_response_params( + read_until_eof=runtime_has_start_tls, + timeout_ceil_threshold=self._timeout_ceil_threshold, + ) + resp = await proxy_resp.start(conn) + except BaseException: + proxy_resp.close() + conn.close() + raise + else: + conn._protocol = None + try: + if resp.status != 200: + message = resp.reason + if message is None: + message = HTTPStatus(resp.status).phrase + raise ClientHttpProxyError( + proxy_resp.request_info, + resp.history, + status=resp.status, + message=message, + headers=resp.headers, + ) + if not runtime_has_start_tls: + rawsock = transport.get_extra_info("socket", default=None) + if rawsock is None: + raise RuntimeError( + "Transport does not expose socket instance" + ) + # Duplicate the socket, so now we can close proxy transport + rawsock = rawsock.dup() + except BaseException: + # It shouldn't be closed in `finally` because it's fed to + # `loop.start_tls()` and the docs say not to touch it after + # passing there. + transport.close() + raise + finally: + if not runtime_has_start_tls: + transport.close() + + if not runtime_has_start_tls: + # HTTP proxy with support for upgrade to HTTPS + sslcontext = self._get_ssl_context(req) + return await self._wrap_existing_connection( + self._factory, + timeout=timeout, + ssl=sslcontext, + sock=rawsock, + server_hostname=req.host, + req=req, + ) + + return await self._start_tls_connection( + # Access the old transport for the last time before it's + # closed and forgotten forever: + transport, + req=req, + timeout=timeout, + ) + finally: + proxy_resp.close() + + return transport, proto + + +class UnixConnector(BaseConnector): + """Unix socket connector. + + path - Unix socket path. + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + loop - Optional event loop. + """ + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"unix"}) + + def __init__( + self, + path: str, + force_close: bool = False, + keepalive_timeout: Union[object, float, None] = sentinel, + limit: int = 100, + limit_per_host: int = 0, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + super().__init__( + force_close=force_close, + keepalive_timeout=keepalive_timeout, + limit=limit, + limit_per_host=limit_per_host, + loop=loop, + ) + self._path = path + + @property + def path(self) -> str: + """Path to unix socket.""" + return self._path + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + _, proto = await self._loop.create_unix_connection( + self._factory, self._path + ) + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise UnixClientConnectorError(self.path, req.connection_key, exc) from exc + + return proto + + +class NamedPipeConnector(BaseConnector): + """Named pipe connector. + + Only supported by the proactor event loop. + See also: https://docs.python.org/3/library/asyncio-eventloop.html + + path - Windows named pipe path. + keepalive_timeout - (optional) Keep-alive timeout. + force_close - Set to True to force close and do reconnect + after each request (and between redirects). + limit - The total number of simultaneous connections. + limit_per_host - Number of simultaneous connections to one host. + loop - Optional event loop. + """ + + allowed_protocol_schema_set = HIGH_LEVEL_SCHEMA_SET | frozenset({"npipe"}) + + def __init__( + self, + path: str, + force_close: bool = False, + keepalive_timeout: Union[object, float, None] = sentinel, + limit: int = 100, + limit_per_host: int = 0, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + super().__init__( + force_close=force_close, + keepalive_timeout=keepalive_timeout, + limit=limit, + limit_per_host=limit_per_host, + loop=loop, + ) + if not isinstance( + self._loop, + asyncio.ProactorEventLoop, # type: ignore[attr-defined] + ): + raise RuntimeError( + "Named Pipes only available in proactor loop under windows" + ) + self._path = path + + @property + def path(self) -> str: + """Path to the named pipe.""" + return self._path + + async def _create_connection( + self, req: ClientRequest, traces: List["Trace"], timeout: "ClientTimeout" + ) -> ResponseHandler: + try: + async with ceil_timeout( + timeout.sock_connect, ceil_threshold=timeout.ceil_threshold + ): + _, proto = await self._loop.create_pipe_connection( # type: ignore[attr-defined] + self._factory, self._path + ) + # the drain is required so that the connection_made is called + # and transport is set otherwise it is not set before the + # `assert conn.transport is not None` + # in client.py's _request method + await asyncio.sleep(0) + # other option is to manually set transport like + # `proto.transport = trans` + except OSError as exc: + if exc.errno is None and isinstance(exc, asyncio.TimeoutError): + raise + raise ClientConnectorError(req.connection_key, exc) from exc + + return cast(ResponseHandler, proto) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/cookiejar.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/cookiejar.py new file mode 100644 index 0000000000000000000000000000000000000000..193648d4309fc9252332c0c1241ab6aafbd2fe05 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/cookiejar.py @@ -0,0 +1,522 @@ +import asyncio +import calendar +import contextlib +import datetime +import heapq +import itertools +import os # noqa +import pathlib +import pickle +import re +import time +import warnings +from collections import defaultdict +from collections.abc import Mapping +from http.cookies import BaseCookie, Morsel, SimpleCookie +from typing import ( + DefaultDict, + Dict, + Iterable, + Iterator, + List, + Optional, + Set, + Tuple, + Union, +) + +from yarl import URL + +from ._cookie_helpers import preserve_morsel_with_coded_value +from .abc import AbstractCookieJar, ClearCookiePredicate +from .helpers import is_ip_address +from .typedefs import LooseCookies, PathLike, StrOrURL + +__all__ = ("CookieJar", "DummyCookieJar") + + +CookieItem = Union[str, "Morsel[str]"] + +# We cache these string methods here as their use is in performance critical code. +_FORMAT_PATH = "{}/{}".format +_FORMAT_DOMAIN_REVERSED = "{1}.{0}".format + +# The minimum number of scheduled cookie expirations before we start cleaning up +# the expiration heap. This is a performance optimization to avoid cleaning up the +# heap too often when there are only a few scheduled expirations. +_MIN_SCHEDULED_COOKIE_EXPIRATION = 100 +_SIMPLE_COOKIE = SimpleCookie() + + +class CookieJar(AbstractCookieJar): + """Implements cookie storage adhering to RFC 6265.""" + + DATE_TOKENS_RE = re.compile( + r"[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]*" + r"(?P[\x00-\x08\x0A-\x1F\d:a-zA-Z\x7F-\xFF]+)" + ) + + DATE_HMS_TIME_RE = re.compile(r"(\d{1,2}):(\d{1,2}):(\d{1,2})") + + DATE_DAY_OF_MONTH_RE = re.compile(r"(\d{1,2})") + + DATE_MONTH_RE = re.compile( + "(jan)|(feb)|(mar)|(apr)|(may)|(jun)|(jul)|(aug)|(sep)|(oct)|(nov)|(dec)", + re.I, + ) + + DATE_YEAR_RE = re.compile(r"(\d{2,4})") + + # calendar.timegm() fails for timestamps after datetime.datetime.max + # Minus one as a loss of precision occurs when timestamp() is called. + MAX_TIME = ( + int(datetime.datetime.max.replace(tzinfo=datetime.timezone.utc).timestamp()) - 1 + ) + try: + calendar.timegm(time.gmtime(MAX_TIME)) + except (OSError, ValueError): + # Hit the maximum representable time on Windows + # https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/localtime-localtime32-localtime64 + # Throws ValueError on PyPy 3.9, OSError elsewhere + MAX_TIME = calendar.timegm((3000, 12, 31, 23, 59, 59, -1, -1, -1)) + except OverflowError: + # #4515: datetime.max may not be representable on 32-bit platforms + MAX_TIME = 2**31 - 1 + # Avoid minuses in the future, 3x faster + SUB_MAX_TIME = MAX_TIME - 1 + + def __init__( + self, + *, + unsafe: bool = False, + quote_cookie: bool = True, + treat_as_secure_origin: Union[StrOrURL, List[StrOrURL], None] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + super().__init__(loop=loop) + self._cookies: DefaultDict[Tuple[str, str], SimpleCookie] = defaultdict( + SimpleCookie + ) + self._morsel_cache: DefaultDict[Tuple[str, str], Dict[str, Morsel[str]]] = ( + defaultdict(dict) + ) + self._host_only_cookies: Set[Tuple[str, str]] = set() + self._unsafe = unsafe + self._quote_cookie = quote_cookie + if treat_as_secure_origin is None: + treat_as_secure_origin = [] + elif isinstance(treat_as_secure_origin, URL): + treat_as_secure_origin = [treat_as_secure_origin.origin()] + elif isinstance(treat_as_secure_origin, str): + treat_as_secure_origin = [URL(treat_as_secure_origin).origin()] + else: + treat_as_secure_origin = [ + URL(url).origin() if isinstance(url, str) else url.origin() + for url in treat_as_secure_origin + ] + self._treat_as_secure_origin = treat_as_secure_origin + self._expire_heap: List[Tuple[float, Tuple[str, str, str]]] = [] + self._expirations: Dict[Tuple[str, str, str], float] = {} + + @property + def quote_cookie(self) -> bool: + return self._quote_cookie + + def save(self, file_path: PathLike) -> None: + file_path = pathlib.Path(file_path) + with file_path.open(mode="wb") as f: + pickle.dump(self._cookies, f, pickle.HIGHEST_PROTOCOL) + + def load(self, file_path: PathLike) -> None: + file_path = pathlib.Path(file_path) + with file_path.open(mode="rb") as f: + self._cookies = pickle.load(f) + + def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: + if predicate is None: + self._expire_heap.clear() + self._cookies.clear() + self._morsel_cache.clear() + self._host_only_cookies.clear() + self._expirations.clear() + return + + now = time.time() + to_del = [ + key + for (domain, path), cookie in self._cookies.items() + for name, morsel in cookie.items() + if ( + (key := (domain, path, name)) in self._expirations + and self._expirations[key] <= now + ) + or predicate(morsel) + ] + if to_del: + self._delete_cookies(to_del) + + def clear_domain(self, domain: str) -> None: + self.clear(lambda x: self._is_domain_match(domain, x["domain"])) + + def __iter__(self) -> "Iterator[Morsel[str]]": + self._do_expiration() + for val in self._cookies.values(): + yield from val.values() + + def __len__(self) -> int: + """Return number of cookies. + + This function does not iterate self to avoid unnecessary expiration + checks. + """ + return sum(len(cookie.values()) for cookie in self._cookies.values()) + + def _do_expiration(self) -> None: + """Remove expired cookies.""" + if not (expire_heap_len := len(self._expire_heap)): + return + + # If the expiration heap grows larger than the number expirations + # times two, we clean it up to avoid keeping expired entries in + # the heap and consuming memory. We guard this with a minimum + # threshold to avoid cleaning up the heap too often when there are + # only a few scheduled expirations. + if ( + expire_heap_len > _MIN_SCHEDULED_COOKIE_EXPIRATION + and expire_heap_len > len(self._expirations) * 2 + ): + # Remove any expired entries from the expiration heap + # that do not match the expiration time in the expirations + # as it means the cookie has been re-added to the heap + # with a different expiration time. + self._expire_heap = [ + entry + for entry in self._expire_heap + if self._expirations.get(entry[1]) == entry[0] + ] + heapq.heapify(self._expire_heap) + + now = time.time() + to_del: List[Tuple[str, str, str]] = [] + # Find any expired cookies and add them to the to-delete list + while self._expire_heap: + when, cookie_key = self._expire_heap[0] + if when > now: + break + heapq.heappop(self._expire_heap) + # Check if the cookie hasn't been re-added to the heap + # with a different expiration time as it will be removed + # later when it reaches the top of the heap and its + # expiration time is met. + if self._expirations.get(cookie_key) == when: + to_del.append(cookie_key) + + if to_del: + self._delete_cookies(to_del) + + def _delete_cookies(self, to_del: List[Tuple[str, str, str]]) -> None: + for domain, path, name in to_del: + self._host_only_cookies.discard((domain, name)) + self._cookies[(domain, path)].pop(name, None) + self._morsel_cache[(domain, path)].pop(name, None) + self._expirations.pop((domain, path, name), None) + + def _expire_cookie(self, when: float, domain: str, path: str, name: str) -> None: + cookie_key = (domain, path, name) + if self._expirations.get(cookie_key) == when: + # Avoid adding duplicates to the heap + return + heapq.heappush(self._expire_heap, (when, cookie_key)) + self._expirations[cookie_key] = when + + def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: + """Update cookies.""" + hostname = response_url.raw_host + + if not self._unsafe and is_ip_address(hostname): + # Don't accept cookies from IPs + return + + if isinstance(cookies, Mapping): + cookies = cookies.items() + + for name, cookie in cookies: + if not isinstance(cookie, Morsel): + tmp = SimpleCookie() + tmp[name] = cookie # type: ignore[assignment] + cookie = tmp[name] + + domain = cookie["domain"] + + # ignore domains with trailing dots + if domain and domain[-1] == ".": + domain = "" + del cookie["domain"] + + if not domain and hostname is not None: + # Set the cookie's domain to the response hostname + # and set its host-only-flag + self._host_only_cookies.add((hostname, name)) + domain = cookie["domain"] = hostname + + if domain and domain[0] == ".": + # Remove leading dot + domain = domain[1:] + cookie["domain"] = domain + + if hostname and not self._is_domain_match(domain, hostname): + # Setting cookies for different domains is not allowed + continue + + path = cookie["path"] + if not path or path[0] != "/": + # Set the cookie's path to the response path + path = response_url.path + if not path.startswith("/"): + path = "/" + else: + # Cut everything from the last slash to the end + path = "/" + path[1 : path.rfind("/")] + cookie["path"] = path + path = path.rstrip("/") + + if max_age := cookie["max-age"]: + try: + delta_seconds = int(max_age) + max_age_expiration = min(time.time() + delta_seconds, self.MAX_TIME) + self._expire_cookie(max_age_expiration, domain, path, name) + except ValueError: + cookie["max-age"] = "" + + elif expires := cookie["expires"]: + if expire_time := self._parse_date(expires): + self._expire_cookie(expire_time, domain, path, name) + else: + cookie["expires"] = "" + + key = (domain, path) + if self._cookies[key].get(name) != cookie: + # Don't blow away the cache if the same + # cookie gets set again + self._cookies[key][name] = cookie + self._morsel_cache[key].pop(name, None) + + self._do_expiration() + + def filter_cookies(self, request_url: URL = URL()) -> "BaseCookie[str]": + """Returns this jar's cookies filtered by their attributes.""" + # We always use BaseCookie now since all + # cookies set on on filtered are fully constructed + # Morsels, not just names and values. + filtered: BaseCookie[str] = BaseCookie() + if not self._cookies: + # Skip do_expiration() if there are no cookies. + return filtered + self._do_expiration() + if not self._cookies: + # Skip rest of function if no non-expired cookies. + return filtered + if type(request_url) is not URL: + warnings.warn( + "filter_cookies expects yarl.URL instances only," + f"and will stop working in 4.x, got {type(request_url)}", + DeprecationWarning, + stacklevel=2, + ) + request_url = URL(request_url) + hostname = request_url.raw_host or "" + + is_not_secure = request_url.scheme not in ("https", "wss") + if is_not_secure and self._treat_as_secure_origin: + request_origin = URL() + with contextlib.suppress(ValueError): + request_origin = request_url.origin() + is_not_secure = request_origin not in self._treat_as_secure_origin + + # Send shared cookie + key = ("", "") + for c in self._cookies[key].values(): + # Check cache first + if c.key in self._morsel_cache[key]: + filtered[c.key] = self._morsel_cache[key][c.key] + continue + + # Build and cache the morsel + mrsl_val = self._build_morsel(c) + self._morsel_cache[key][c.key] = mrsl_val + filtered[c.key] = mrsl_val + + if is_ip_address(hostname): + if not self._unsafe: + return filtered + domains: Iterable[str] = (hostname,) + else: + # Get all the subdomains that might match a cookie (e.g. "foo.bar.com", "bar.com", "com") + domains = itertools.accumulate( + reversed(hostname.split(".")), _FORMAT_DOMAIN_REVERSED + ) + + # Get all the path prefixes that might match a cookie (e.g. "", "/foo", "/foo/bar") + paths = itertools.accumulate(request_url.path.split("/"), _FORMAT_PATH) + # Create every combination of (domain, path) pairs. + pairs = itertools.product(domains, paths) + + path_len = len(request_url.path) + # Point 2: https://www.rfc-editor.org/rfc/rfc6265.html#section-5.4 + for p in pairs: + if p not in self._cookies: + continue + for name, cookie in self._cookies[p].items(): + domain = cookie["domain"] + + if (domain, name) in self._host_only_cookies and domain != hostname: + continue + + # Skip edge case when the cookie has a trailing slash but request doesn't. + if len(cookie["path"]) > path_len: + continue + + if is_not_secure and cookie["secure"]: + continue + + # We already built the Morsel so reuse it here + if name in self._morsel_cache[p]: + filtered[name] = self._morsel_cache[p][name] + continue + + # Build and cache the morsel + mrsl_val = self._build_morsel(cookie) + self._morsel_cache[p][name] = mrsl_val + filtered[name] = mrsl_val + + return filtered + + def _build_morsel(self, cookie: Morsel[str]) -> Morsel[str]: + """Build a morsel for sending, respecting quote_cookie setting.""" + if self._quote_cookie and cookie.coded_value and cookie.coded_value[0] == '"': + return preserve_morsel_with_coded_value(cookie) + morsel: Morsel[str] = Morsel() + if self._quote_cookie: + value, coded_value = _SIMPLE_COOKIE.value_encode(cookie.value) + else: + coded_value = value = cookie.value + # We use __setstate__ instead of the public set() API because it allows us to + # bypass validation and set already validated state. This is more stable than + # setting protected attributes directly and unlikely to change since it would + # break pickling. + morsel.__setstate__({"key": cookie.key, "value": value, "coded_value": coded_value}) # type: ignore[attr-defined] + return morsel + + @staticmethod + def _is_domain_match(domain: str, hostname: str) -> bool: + """Implements domain matching adhering to RFC 6265.""" + if hostname == domain: + return True + + if not hostname.endswith(domain): + return False + + non_matching = hostname[: -len(domain)] + + if not non_matching.endswith("."): + return False + + return not is_ip_address(hostname) + + @classmethod + def _parse_date(cls, date_str: str) -> Optional[int]: + """Implements date string parsing adhering to RFC 6265.""" + if not date_str: + return None + + found_time = False + found_day = False + found_month = False + found_year = False + + hour = minute = second = 0 + day = 0 + month = 0 + year = 0 + + for token_match in cls.DATE_TOKENS_RE.finditer(date_str): + + token = token_match.group("token") + + if not found_time: + time_match = cls.DATE_HMS_TIME_RE.match(token) + if time_match: + found_time = True + hour, minute, second = (int(s) for s in time_match.groups()) + continue + + if not found_day: + day_match = cls.DATE_DAY_OF_MONTH_RE.match(token) + if day_match: + found_day = True + day = int(day_match.group()) + continue + + if not found_month: + month_match = cls.DATE_MONTH_RE.match(token) + if month_match: + found_month = True + assert month_match.lastindex is not None + month = month_match.lastindex + continue + + if not found_year: + year_match = cls.DATE_YEAR_RE.match(token) + if year_match: + found_year = True + year = int(year_match.group()) + + if 70 <= year <= 99: + year += 1900 + elif 0 <= year <= 69: + year += 2000 + + if False in (found_day, found_month, found_year, found_time): + return None + + if not 1 <= day <= 31: + return None + + if year < 1601 or hour > 23 or minute > 59 or second > 59: + return None + + return calendar.timegm((year, month, day, hour, minute, second, -1, -1, -1)) + + +class DummyCookieJar(AbstractCookieJar): + """Implements a dummy cookie storage. + + It can be used with the ClientSession when no cookie processing is needed. + + """ + + def __init__(self, *, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: + super().__init__(loop=loop) + + def __iter__(self) -> "Iterator[Morsel[str]]": + while False: + yield None + + def __len__(self) -> int: + return 0 + + @property + def quote_cookie(self) -> bool: + return True + + def clear(self, predicate: Optional[ClearCookiePredicate] = None) -> None: + pass + + def clear_domain(self, domain: str) -> None: + pass + + def update_cookies(self, cookies: LooseCookies, response_url: URL = URL()) -> None: + pass + + def filter_cookies(self, request_url: URL) -> "BaseCookie[str]": + return SimpleCookie() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/formdata.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/formdata.py new file mode 100644 index 0000000000000000000000000000000000000000..bdf591fae7ae05be98c223890282ffa57de69176 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/formdata.py @@ -0,0 +1,179 @@ +import io +import warnings +from typing import Any, Iterable, List, Optional +from urllib.parse import urlencode + +from multidict import MultiDict, MultiDictProxy + +from . import hdrs, multipart, payload +from .helpers import guess_filename +from .payload import Payload + +__all__ = ("FormData",) + + +class FormData: + """Helper class for form body generation. + + Supports multipart/form-data and application/x-www-form-urlencoded. + """ + + def __init__( + self, + fields: Iterable[Any] = (), + quote_fields: bool = True, + charset: Optional[str] = None, + *, + default_to_multipart: bool = False, + ) -> None: + self._writer = multipart.MultipartWriter("form-data") + self._fields: List[Any] = [] + self._is_multipart = default_to_multipart + self._quote_fields = quote_fields + self._charset = charset + + if isinstance(fields, dict): + fields = list(fields.items()) + elif not isinstance(fields, (list, tuple)): + fields = (fields,) + self.add_fields(*fields) + + @property + def is_multipart(self) -> bool: + return self._is_multipart + + def add_field( + self, + name: str, + value: Any, + *, + content_type: Optional[str] = None, + filename: Optional[str] = None, + content_transfer_encoding: Optional[str] = None, + ) -> None: + + if isinstance(value, io.IOBase): + self._is_multipart = True + elif isinstance(value, (bytes, bytearray, memoryview)): + msg = ( + "In v4, passing bytes will no longer create a file field. " + "Please explicitly use the filename parameter or pass a BytesIO object." + ) + if filename is None and content_transfer_encoding is None: + warnings.warn(msg, DeprecationWarning) + filename = name + + type_options: MultiDict[str] = MultiDict({"name": name}) + if filename is not None and not isinstance(filename, str): + raise TypeError("filename must be an instance of str. Got: %s" % filename) + if filename is None and isinstance(value, io.IOBase): + filename = guess_filename(value, name) + if filename is not None: + type_options["filename"] = filename + self._is_multipart = True + + headers = {} + if content_type is not None: + if not isinstance(content_type, str): + raise TypeError( + "content_type must be an instance of str. Got: %s" % content_type + ) + headers[hdrs.CONTENT_TYPE] = content_type + self._is_multipart = True + if content_transfer_encoding is not None: + if not isinstance(content_transfer_encoding, str): + raise TypeError( + "content_transfer_encoding must be an instance" + " of str. Got: %s" % content_transfer_encoding + ) + msg = ( + "content_transfer_encoding is deprecated. " + "To maintain compatibility with v4 please pass a BytesPayload." + ) + warnings.warn(msg, DeprecationWarning) + self._is_multipart = True + + self._fields.append((type_options, headers, value)) + + def add_fields(self, *fields: Any) -> None: + to_add = list(fields) + + while to_add: + rec = to_add.pop(0) + + if isinstance(rec, io.IOBase): + k = guess_filename(rec, "unknown") + self.add_field(k, rec) # type: ignore[arg-type] + + elif isinstance(rec, (MultiDictProxy, MultiDict)): + to_add.extend(rec.items()) + + elif isinstance(rec, (list, tuple)) and len(rec) == 2: + k, fp = rec + self.add_field(k, fp) # type: ignore[arg-type] + + else: + raise TypeError( + "Only io.IOBase, multidict and (name, file) " + "pairs allowed, use .add_field() for passing " + "more complex parameters, got {!r}".format(rec) + ) + + def _gen_form_urlencoded(self) -> payload.BytesPayload: + # form data (x-www-form-urlencoded) + data = [] + for type_options, _, value in self._fields: + data.append((type_options["name"], value)) + + charset = self._charset if self._charset is not None else "utf-8" + + if charset == "utf-8": + content_type = "application/x-www-form-urlencoded" + else: + content_type = "application/x-www-form-urlencoded; charset=%s" % charset + + return payload.BytesPayload( + urlencode(data, doseq=True, encoding=charset).encode(), + content_type=content_type, + ) + + def _gen_form_data(self) -> multipart.MultipartWriter: + """Encode a list of fields using the multipart/form-data MIME format""" + for dispparams, headers, value in self._fields: + try: + if hdrs.CONTENT_TYPE in headers: + part = payload.get_payload( + value, + content_type=headers[hdrs.CONTENT_TYPE], + headers=headers, + encoding=self._charset, + ) + else: + part = payload.get_payload( + value, headers=headers, encoding=self._charset + ) + except Exception as exc: + raise TypeError( + "Can not serialize value type: %r\n " + "headers: %r\n value: %r" % (type(value), headers, value) + ) from exc + + if dispparams: + part.set_content_disposition( + "form-data", quote_fields=self._quote_fields, **dispparams + ) + # FIXME cgi.FieldStorage doesn't likes body parts with + # Content-Length which were sent via chunked transfer encoding + assert part.headers is not None + part.headers.popall(hdrs.CONTENT_LENGTH, None) + + self._writer.append_payload(part) + + self._fields.clear() + return self._writer + + def __call__(self) -> Payload: + if self._is_multipart: + return self._gen_form_data() + else: + return self._gen_form_urlencoded() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/hdrs.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/hdrs.py new file mode 100644 index 0000000000000000000000000000000000000000..c8d6b35f33ae4be537d7776ce4085982618d1305 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/hdrs.py @@ -0,0 +1,121 @@ +"""HTTP Headers constants.""" + +# After changing the file content call ./tools/gen.py +# to regenerate the headers parser +import itertools +from typing import Final, Set + +from multidict import istr + +METH_ANY: Final[str] = "*" +METH_CONNECT: Final[str] = "CONNECT" +METH_HEAD: Final[str] = "HEAD" +METH_GET: Final[str] = "GET" +METH_DELETE: Final[str] = "DELETE" +METH_OPTIONS: Final[str] = "OPTIONS" +METH_PATCH: Final[str] = "PATCH" +METH_POST: Final[str] = "POST" +METH_PUT: Final[str] = "PUT" +METH_TRACE: Final[str] = "TRACE" + +METH_ALL: Final[Set[str]] = { + METH_CONNECT, + METH_HEAD, + METH_GET, + METH_DELETE, + METH_OPTIONS, + METH_PATCH, + METH_POST, + METH_PUT, + METH_TRACE, +} + +ACCEPT: Final[istr] = istr("Accept") +ACCEPT_CHARSET: Final[istr] = istr("Accept-Charset") +ACCEPT_ENCODING: Final[istr] = istr("Accept-Encoding") +ACCEPT_LANGUAGE: Final[istr] = istr("Accept-Language") +ACCEPT_RANGES: Final[istr] = istr("Accept-Ranges") +ACCESS_CONTROL_MAX_AGE: Final[istr] = istr("Access-Control-Max-Age") +ACCESS_CONTROL_ALLOW_CREDENTIALS: Final[istr] = istr("Access-Control-Allow-Credentials") +ACCESS_CONTROL_ALLOW_HEADERS: Final[istr] = istr("Access-Control-Allow-Headers") +ACCESS_CONTROL_ALLOW_METHODS: Final[istr] = istr("Access-Control-Allow-Methods") +ACCESS_CONTROL_ALLOW_ORIGIN: Final[istr] = istr("Access-Control-Allow-Origin") +ACCESS_CONTROL_EXPOSE_HEADERS: Final[istr] = istr("Access-Control-Expose-Headers") +ACCESS_CONTROL_REQUEST_HEADERS: Final[istr] = istr("Access-Control-Request-Headers") +ACCESS_CONTROL_REQUEST_METHOD: Final[istr] = istr("Access-Control-Request-Method") +AGE: Final[istr] = istr("Age") +ALLOW: Final[istr] = istr("Allow") +AUTHORIZATION: Final[istr] = istr("Authorization") +CACHE_CONTROL: Final[istr] = istr("Cache-Control") +CONNECTION: Final[istr] = istr("Connection") +CONTENT_DISPOSITION: Final[istr] = istr("Content-Disposition") +CONTENT_ENCODING: Final[istr] = istr("Content-Encoding") +CONTENT_LANGUAGE: Final[istr] = istr("Content-Language") +CONTENT_LENGTH: Final[istr] = istr("Content-Length") +CONTENT_LOCATION: Final[istr] = istr("Content-Location") +CONTENT_MD5: Final[istr] = istr("Content-MD5") +CONTENT_RANGE: Final[istr] = istr("Content-Range") +CONTENT_TRANSFER_ENCODING: Final[istr] = istr("Content-Transfer-Encoding") +CONTENT_TYPE: Final[istr] = istr("Content-Type") +COOKIE: Final[istr] = istr("Cookie") +DATE: Final[istr] = istr("Date") +DESTINATION: Final[istr] = istr("Destination") +DIGEST: Final[istr] = istr("Digest") +ETAG: Final[istr] = istr("Etag") +EXPECT: Final[istr] = istr("Expect") +EXPIRES: Final[istr] = istr("Expires") +FORWARDED: Final[istr] = istr("Forwarded") +FROM: Final[istr] = istr("From") +HOST: Final[istr] = istr("Host") +IF_MATCH: Final[istr] = istr("If-Match") +IF_MODIFIED_SINCE: Final[istr] = istr("If-Modified-Since") +IF_NONE_MATCH: Final[istr] = istr("If-None-Match") +IF_RANGE: Final[istr] = istr("If-Range") +IF_UNMODIFIED_SINCE: Final[istr] = istr("If-Unmodified-Since") +KEEP_ALIVE: Final[istr] = istr("Keep-Alive") +LAST_EVENT_ID: Final[istr] = istr("Last-Event-ID") +LAST_MODIFIED: Final[istr] = istr("Last-Modified") +LINK: Final[istr] = istr("Link") +LOCATION: Final[istr] = istr("Location") +MAX_FORWARDS: Final[istr] = istr("Max-Forwards") +ORIGIN: Final[istr] = istr("Origin") +PRAGMA: Final[istr] = istr("Pragma") +PROXY_AUTHENTICATE: Final[istr] = istr("Proxy-Authenticate") +PROXY_AUTHORIZATION: Final[istr] = istr("Proxy-Authorization") +RANGE: Final[istr] = istr("Range") +REFERER: Final[istr] = istr("Referer") +RETRY_AFTER: Final[istr] = istr("Retry-After") +SEC_WEBSOCKET_ACCEPT: Final[istr] = istr("Sec-WebSocket-Accept") +SEC_WEBSOCKET_VERSION: Final[istr] = istr("Sec-WebSocket-Version") +SEC_WEBSOCKET_PROTOCOL: Final[istr] = istr("Sec-WebSocket-Protocol") +SEC_WEBSOCKET_EXTENSIONS: Final[istr] = istr("Sec-WebSocket-Extensions") +SEC_WEBSOCKET_KEY: Final[istr] = istr("Sec-WebSocket-Key") +SEC_WEBSOCKET_KEY1: Final[istr] = istr("Sec-WebSocket-Key1") +SERVER: Final[istr] = istr("Server") +SET_COOKIE: Final[istr] = istr("Set-Cookie") +TE: Final[istr] = istr("TE") +TRAILER: Final[istr] = istr("Trailer") +TRANSFER_ENCODING: Final[istr] = istr("Transfer-Encoding") +UPGRADE: Final[istr] = istr("Upgrade") +URI: Final[istr] = istr("URI") +USER_AGENT: Final[istr] = istr("User-Agent") +VARY: Final[istr] = istr("Vary") +VIA: Final[istr] = istr("Via") +WANT_DIGEST: Final[istr] = istr("Want-Digest") +WARNING: Final[istr] = istr("Warning") +WWW_AUTHENTICATE: Final[istr] = istr("WWW-Authenticate") +X_FORWARDED_FOR: Final[istr] = istr("X-Forwarded-For") +X_FORWARDED_HOST: Final[istr] = istr("X-Forwarded-Host") +X_FORWARDED_PROTO: Final[istr] = istr("X-Forwarded-Proto") + +# These are the upper/lower case variants of the headers/methods +# Example: {'hOst', 'host', 'HoST', 'HOSt', 'hOsT', 'HosT', 'hoSt', ...} +METH_HEAD_ALL: Final = frozenset( + map("".join, itertools.product(*zip(METH_HEAD.upper(), METH_HEAD.lower()))) +) +METH_CONNECT_ALL: Final = frozenset( + map("".join, itertools.product(*zip(METH_CONNECT.upper(), METH_CONNECT.lower()))) +) +HOST_ALL: Final = frozenset( + map("".join, itertools.product(*zip(HOST.upper(), HOST.lower()))) +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/helpers.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..ace4f0e9b5305dd68b6683c68a1627c037d809ae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/helpers.py @@ -0,0 +1,958 @@ +"""Various helper functions""" + +import asyncio +import base64 +import binascii +import contextlib +import datetime +import enum +import functools +import inspect +import netrc +import os +import platform +import re +import sys +import time +import weakref +from collections import namedtuple +from contextlib import suppress +from email.parser import HeaderParser +from email.utils import parsedate +from math import ceil +from pathlib import Path +from types import MappingProxyType, TracebackType +from typing import ( + Any, + Callable, + ContextManager, + Dict, + Generator, + Generic, + Iterable, + Iterator, + List, + Mapping, + Optional, + Protocol, + Tuple, + Type, + TypeVar, + Union, + get_args, + overload, +) +from urllib.parse import quote +from urllib.request import getproxies, proxy_bypass + +import attr +from multidict import MultiDict, MultiDictProxy, MultiMapping +from propcache.api import under_cached_property as reify +from yarl import URL + +from . import hdrs +from .log import client_logger + +if sys.version_info >= (3, 11): + import asyncio as async_timeout +else: + import async_timeout + +__all__ = ("BasicAuth", "ChainMapProxy", "ETag", "reify") + +IS_MACOS = platform.system() == "Darwin" +IS_WINDOWS = platform.system() == "Windows" + +PY_310 = sys.version_info >= (3, 10) +PY_311 = sys.version_info >= (3, 11) + + +_T = TypeVar("_T") +_S = TypeVar("_S") + +_SENTINEL = enum.Enum("_SENTINEL", "sentinel") +sentinel = _SENTINEL.sentinel + +NO_EXTENSIONS = bool(os.environ.get("AIOHTTP_NO_EXTENSIONS")) + +# https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1 +EMPTY_BODY_STATUS_CODES = frozenset((204, 304, *range(100, 200))) +# https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.1 +# https://datatracker.ietf.org/doc/html/rfc9112#section-6.3-2.2 +EMPTY_BODY_METHODS = hdrs.METH_HEAD_ALL + +DEBUG = sys.flags.dev_mode or ( + not sys.flags.ignore_environment and bool(os.environ.get("PYTHONASYNCIODEBUG")) +) + + +CHAR = {chr(i) for i in range(0, 128)} +CTL = {chr(i) for i in range(0, 32)} | { + chr(127), +} +SEPARATORS = { + "(", + ")", + "<", + ">", + "@", + ",", + ";", + ":", + "\\", + '"', + "/", + "[", + "]", + "?", + "=", + "{", + "}", + " ", + chr(9), +} +TOKEN = CHAR ^ CTL ^ SEPARATORS + + +class noop: + def __await__(self) -> Generator[None, None, None]: + yield + + +class BasicAuth(namedtuple("BasicAuth", ["login", "password", "encoding"])): + """Http basic authentication helper.""" + + def __new__( + cls, login: str, password: str = "", encoding: str = "latin1" + ) -> "BasicAuth": + if login is None: + raise ValueError("None is not allowed as login value") + + if password is None: + raise ValueError("None is not allowed as password value") + + if ":" in login: + raise ValueError('A ":" is not allowed in login (RFC 1945#section-11.1)') + + return super().__new__(cls, login, password, encoding) + + @classmethod + def decode(cls, auth_header: str, encoding: str = "latin1") -> "BasicAuth": + """Create a BasicAuth object from an Authorization HTTP header.""" + try: + auth_type, encoded_credentials = auth_header.split(" ", 1) + except ValueError: + raise ValueError("Could not parse authorization header.") + + if auth_type.lower() != "basic": + raise ValueError("Unknown authorization method %s" % auth_type) + + try: + decoded = base64.b64decode( + encoded_credentials.encode("ascii"), validate=True + ).decode(encoding) + except binascii.Error: + raise ValueError("Invalid base64 encoding.") + + try: + # RFC 2617 HTTP Authentication + # https://www.ietf.org/rfc/rfc2617.txt + # the colon must be present, but the username and password may be + # otherwise blank. + username, password = decoded.split(":", 1) + except ValueError: + raise ValueError("Invalid credentials.") + + return cls(username, password, encoding=encoding) + + @classmethod + def from_url(cls, url: URL, *, encoding: str = "latin1") -> Optional["BasicAuth"]: + """Create BasicAuth from url.""" + if not isinstance(url, URL): + raise TypeError("url should be yarl.URL instance") + # Check raw_user and raw_password first as yarl is likely + # to already have these values parsed from the netloc in the cache. + if url.raw_user is None and url.raw_password is None: + return None + return cls(url.user or "", url.password or "", encoding=encoding) + + def encode(self) -> str: + """Encode credentials.""" + creds = (f"{self.login}:{self.password}").encode(self.encoding) + return "Basic %s" % base64.b64encode(creds).decode(self.encoding) + + +def strip_auth_from_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: + """Remove user and password from URL if present and return BasicAuth object.""" + # Check raw_user and raw_password first as yarl is likely + # to already have these values parsed from the netloc in the cache. + if url.raw_user is None and url.raw_password is None: + return url, None + return url.with_user(None), BasicAuth(url.user or "", url.password or "") + + +def netrc_from_env() -> Optional[netrc.netrc]: + """Load netrc from file. + + Attempt to load it from the path specified by the env-var + NETRC or in the default location in the user's home directory. + + Returns None if it couldn't be found or fails to parse. + """ + netrc_env = os.environ.get("NETRC") + + if netrc_env is not None: + netrc_path = Path(netrc_env) + else: + try: + home_dir = Path.home() + except RuntimeError as e: # pragma: no cover + # if pathlib can't resolve home, it may raise a RuntimeError + client_logger.debug( + "Could not resolve home directory when " + "trying to look for .netrc file: %s", + e, + ) + return None + + netrc_path = home_dir / ("_netrc" if IS_WINDOWS else ".netrc") + + try: + return netrc.netrc(str(netrc_path)) + except netrc.NetrcParseError as e: + client_logger.warning("Could not parse .netrc file: %s", e) + except OSError as e: + netrc_exists = False + with contextlib.suppress(OSError): + netrc_exists = netrc_path.is_file() + # we couldn't read the file (doesn't exist, permissions, etc.) + if netrc_env or netrc_exists: + # only warn if the environment wanted us to load it, + # or it appears like the default file does actually exist + client_logger.warning("Could not read .netrc file: %s", e) + + return None + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ProxyInfo: + proxy: URL + proxy_auth: Optional[BasicAuth] + + +def basicauth_from_netrc(netrc_obj: Optional[netrc.netrc], host: str) -> BasicAuth: + """ + Return :py:class:`~aiohttp.BasicAuth` credentials for ``host`` from ``netrc_obj``. + + :raises LookupError: if ``netrc_obj`` is :py:data:`None` or if no + entry is found for the ``host``. + """ + if netrc_obj is None: + raise LookupError("No .netrc file found") + auth_from_netrc = netrc_obj.authenticators(host) + + if auth_from_netrc is None: + raise LookupError(f"No entry for {host!s} found in the `.netrc` file.") + login, account, password = auth_from_netrc + + # TODO(PY311): username = login or account + # Up to python 3.10, account could be None if not specified, + # and login will be empty string if not specified. From 3.11, + # login and account will be empty string if not specified. + username = login if (login or account is None) else account + + # TODO(PY311): Remove this, as password will be empty string + # if not specified + if password is None: + password = "" + + return BasicAuth(username, password) + + +def proxies_from_env() -> Dict[str, ProxyInfo]: + proxy_urls = { + k: URL(v) + for k, v in getproxies().items() + if k in ("http", "https", "ws", "wss") + } + netrc_obj = netrc_from_env() + stripped = {k: strip_auth_from_url(v) for k, v in proxy_urls.items()} + ret = {} + for proto, val in stripped.items(): + proxy, auth = val + if proxy.scheme in ("https", "wss"): + client_logger.warning( + "%s proxies %s are not supported, ignoring", proxy.scheme.upper(), proxy + ) + continue + if netrc_obj and auth is None: + if proxy.host is not None: + try: + auth = basicauth_from_netrc(netrc_obj, proxy.host) + except LookupError: + auth = None + ret[proto] = ProxyInfo(proxy, auth) + return ret + + +def get_env_proxy_for_url(url: URL) -> Tuple[URL, Optional[BasicAuth]]: + """Get a permitted proxy for the given URL from the env.""" + if url.host is not None and proxy_bypass(url.host): + raise LookupError(f"Proxying is disallowed for `{url.host!r}`") + + proxies_in_env = proxies_from_env() + try: + proxy_info = proxies_in_env[url.scheme] + except KeyError: + raise LookupError(f"No proxies found for `{url!s}` in the env") + else: + return proxy_info.proxy, proxy_info.proxy_auth + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class MimeType: + type: str + subtype: str + suffix: str + parameters: "MultiDictProxy[str]" + + +@functools.lru_cache(maxsize=56) +def parse_mimetype(mimetype: str) -> MimeType: + """Parses a MIME type into its components. + + mimetype is a MIME type string. + + Returns a MimeType object. + + Example: + + >>> parse_mimetype('text/html; charset=utf-8') + MimeType(type='text', subtype='html', suffix='', + parameters={'charset': 'utf-8'}) + + """ + if not mimetype: + return MimeType( + type="", subtype="", suffix="", parameters=MultiDictProxy(MultiDict()) + ) + + parts = mimetype.split(";") + params: MultiDict[str] = MultiDict() + for item in parts[1:]: + if not item: + continue + key, _, value = item.partition("=") + params.add(key.lower().strip(), value.strip(' "')) + + fulltype = parts[0].strip().lower() + if fulltype == "*": + fulltype = "*/*" + + mtype, _, stype = fulltype.partition("/") + stype, _, suffix = stype.partition("+") + + return MimeType( + type=mtype, subtype=stype, suffix=suffix, parameters=MultiDictProxy(params) + ) + + +@functools.lru_cache(maxsize=56) +def parse_content_type(raw: str) -> Tuple[str, MappingProxyType[str, str]]: + """Parse Content-Type header. + + Returns a tuple of the parsed content type and a + MappingProxyType of parameters. + """ + msg = HeaderParser().parsestr(f"Content-Type: {raw}") + content_type = msg.get_content_type() + params = msg.get_params(()) + content_dict = dict(params[1:]) # First element is content type again + return content_type, MappingProxyType(content_dict) + + +def guess_filename(obj: Any, default: Optional[str] = None) -> Optional[str]: + name = getattr(obj, "name", None) + if name and isinstance(name, str) and name[0] != "<" and name[-1] != ">": + return Path(name).name + return default + + +not_qtext_re = re.compile(r"[^\041\043-\133\135-\176]") +QCONTENT = {chr(i) for i in range(0x20, 0x7F)} | {"\t"} + + +def quoted_string(content: str) -> str: + """Return 7-bit content as quoted-string. + + Format content into a quoted-string as defined in RFC5322 for + Internet Message Format. Notice that this is not the 8-bit HTTP + format, but the 7-bit email format. Content must be in usascii or + a ValueError is raised. + """ + if not (QCONTENT > set(content)): + raise ValueError(f"bad content for quoted-string {content!r}") + return not_qtext_re.sub(lambda x: "\\" + x.group(0), content) + + +def content_disposition_header( + disptype: str, quote_fields: bool = True, _charset: str = "utf-8", **params: str +) -> str: + """Sets ``Content-Disposition`` header for MIME. + + This is the MIME payload Content-Disposition header from RFC 2183 + and RFC 7579 section 4.2, not the HTTP Content-Disposition from + RFC 6266. + + disptype is a disposition type: inline, attachment, form-data. + Should be valid extension token (see RFC 2183) + + quote_fields performs value quoting to 7-bit MIME headers + according to RFC 7578. Set to quote_fields to False if recipient + can take 8-bit file names and field values. + + _charset specifies the charset to use when quote_fields is True. + + params is a dict with disposition params. + """ + if not disptype or not (TOKEN > set(disptype)): + raise ValueError(f"bad content disposition type {disptype!r}") + + value = disptype + if params: + lparams = [] + for key, val in params.items(): + if not key or not (TOKEN > set(key)): + raise ValueError(f"bad content disposition parameter {key!r}={val!r}") + if quote_fields: + if key.lower() == "filename": + qval = quote(val, "", encoding=_charset) + lparams.append((key, '"%s"' % qval)) + else: + try: + qval = quoted_string(val) + except ValueError: + qval = "".join( + (_charset, "''", quote(val, "", encoding=_charset)) + ) + lparams.append((key + "*", qval)) + else: + lparams.append((key, '"%s"' % qval)) + else: + qval = val.replace("\\", "\\\\").replace('"', '\\"') + lparams.append((key, '"%s"' % qval)) + sparams = "; ".join("=".join(pair) for pair in lparams) + value = "; ".join((value, sparams)) + return value + + +def is_ip_address(host: Optional[str]) -> bool: + """Check if host looks like an IP Address. + + This check is only meant as a heuristic to ensure that + a host is not a domain name. + """ + if not host: + return False + # For a host to be an ipv4 address, it must be all numeric. + # The host must contain a colon to be an IPv6 address. + return ":" in host or host.replace(".", "").isdigit() + + +_cached_current_datetime: Optional[int] = None +_cached_formatted_datetime = "" + + +def rfc822_formatted_time() -> str: + global _cached_current_datetime + global _cached_formatted_datetime + + now = int(time.time()) + if now != _cached_current_datetime: + # Weekday and month names for HTTP date/time formatting; + # always English! + # Tuples are constants stored in codeobject! + _weekdayname = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") + _monthname = ( + "", # Dummy so we can use 1-based month numbers + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec", + ) + + year, month, day, hh, mm, ss, wd, *tail = time.gmtime(now) + _cached_formatted_datetime = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( + _weekdayname[wd], + day, + _monthname[month], + year, + hh, + mm, + ss, + ) + _cached_current_datetime = now + return _cached_formatted_datetime + + +def _weakref_handle(info: "Tuple[weakref.ref[object], str]") -> None: + ref, name = info + ob = ref() + if ob is not None: + with suppress(Exception): + getattr(ob, name)() + + +def weakref_handle( + ob: object, + name: str, + timeout: float, + loop: asyncio.AbstractEventLoop, + timeout_ceil_threshold: float = 5, +) -> Optional[asyncio.TimerHandle]: + if timeout is not None and timeout > 0: + when = loop.time() + timeout + if timeout >= timeout_ceil_threshold: + when = ceil(when) + + return loop.call_at(when, _weakref_handle, (weakref.ref(ob), name)) + return None + + +def call_later( + cb: Callable[[], Any], + timeout: float, + loop: asyncio.AbstractEventLoop, + timeout_ceil_threshold: float = 5, +) -> Optional[asyncio.TimerHandle]: + if timeout is None or timeout <= 0: + return None + now = loop.time() + when = calculate_timeout_when(now, timeout, timeout_ceil_threshold) + return loop.call_at(when, cb) + + +def calculate_timeout_when( + loop_time: float, + timeout: float, + timeout_ceiling_threshold: float, +) -> float: + """Calculate when to execute a timeout.""" + when = loop_time + timeout + if timeout > timeout_ceiling_threshold: + return ceil(when) + return when + + +class TimeoutHandle: + """Timeout handle""" + + __slots__ = ("_timeout", "_loop", "_ceil_threshold", "_callbacks") + + def __init__( + self, + loop: asyncio.AbstractEventLoop, + timeout: Optional[float], + ceil_threshold: float = 5, + ) -> None: + self._timeout = timeout + self._loop = loop + self._ceil_threshold = ceil_threshold + self._callbacks: List[ + Tuple[Callable[..., None], Tuple[Any, ...], Dict[str, Any]] + ] = [] + + def register( + self, callback: Callable[..., None], *args: Any, **kwargs: Any + ) -> None: + self._callbacks.append((callback, args, kwargs)) + + def close(self) -> None: + self._callbacks.clear() + + def start(self) -> Optional[asyncio.TimerHandle]: + timeout = self._timeout + if timeout is not None and timeout > 0: + when = self._loop.time() + timeout + if timeout >= self._ceil_threshold: + when = ceil(when) + return self._loop.call_at(when, self.__call__) + else: + return None + + def timer(self) -> "BaseTimerContext": + if self._timeout is not None and self._timeout > 0: + timer = TimerContext(self._loop) + self.register(timer.timeout) + return timer + else: + return TimerNoop() + + def __call__(self) -> None: + for cb, args, kwargs in self._callbacks: + with suppress(Exception): + cb(*args, **kwargs) + + self._callbacks.clear() + + +class BaseTimerContext(ContextManager["BaseTimerContext"]): + + __slots__ = () + + def assert_timeout(self) -> None: + """Raise TimeoutError if timeout has been exceeded.""" + + +class TimerNoop(BaseTimerContext): + + __slots__ = () + + def __enter__(self) -> BaseTimerContext: + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + return + + +class TimerContext(BaseTimerContext): + """Low resolution timeout context manager""" + + __slots__ = ("_loop", "_tasks", "_cancelled", "_cancelling") + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop = loop + self._tasks: List[asyncio.Task[Any]] = [] + self._cancelled = False + self._cancelling = 0 + + def assert_timeout(self) -> None: + """Raise TimeoutError if timer has already been cancelled.""" + if self._cancelled: + raise asyncio.TimeoutError from None + + def __enter__(self) -> BaseTimerContext: + task = asyncio.current_task(loop=self._loop) + if task is None: + raise RuntimeError("Timeout context manager should be used inside a task") + + if sys.version_info >= (3, 11): + # Remember if the task was already cancelling + # so when we __exit__ we can decide if we should + # raise asyncio.TimeoutError or let the cancellation propagate + self._cancelling = task.cancelling() + + if self._cancelled: + raise asyncio.TimeoutError from None + + self._tasks.append(task) + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + enter_task: Optional[asyncio.Task[Any]] = None + if self._tasks: + enter_task = self._tasks.pop() + + if exc_type is asyncio.CancelledError and self._cancelled: + assert enter_task is not None + # The timeout was hit, and the task was cancelled + # so we need to uncancel the last task that entered the context manager + # since the cancellation should not leak out of the context manager + if sys.version_info >= (3, 11): + # If the task was already cancelling don't raise + # asyncio.TimeoutError and instead return None + # to allow the cancellation to propagate + if enter_task.uncancel() > self._cancelling: + return None + raise asyncio.TimeoutError from exc_val + return None + + def timeout(self) -> None: + if not self._cancelled: + for task in set(self._tasks): + task.cancel() + + self._cancelled = True + + +def ceil_timeout( + delay: Optional[float], ceil_threshold: float = 5 +) -> async_timeout.Timeout: + if delay is None or delay <= 0: + return async_timeout.timeout(None) + + loop = asyncio.get_running_loop() + now = loop.time() + when = now + delay + if delay > ceil_threshold: + when = ceil(when) + return async_timeout.timeout_at(when) + + +class HeadersMixin: + """Mixin for handling headers.""" + + ATTRS = frozenset(["_content_type", "_content_dict", "_stored_content_type"]) + + _headers: MultiMapping[str] + _content_type: Optional[str] = None + _content_dict: Optional[Dict[str, str]] = None + _stored_content_type: Union[str, None, _SENTINEL] = sentinel + + def _parse_content_type(self, raw: Optional[str]) -> None: + self._stored_content_type = raw + if raw is None: + # default value according to RFC 2616 + self._content_type = "application/octet-stream" + self._content_dict = {} + else: + content_type, content_mapping_proxy = parse_content_type(raw) + self._content_type = content_type + # _content_dict needs to be mutable so we can update it + self._content_dict = content_mapping_proxy.copy() + + @property + def content_type(self) -> str: + """The value of content part for Content-Type HTTP header.""" + raw = self._headers.get(hdrs.CONTENT_TYPE) + if self._stored_content_type != raw: + self._parse_content_type(raw) + assert self._content_type is not None + return self._content_type + + @property + def charset(self) -> Optional[str]: + """The value of charset part for Content-Type HTTP header.""" + raw = self._headers.get(hdrs.CONTENT_TYPE) + if self._stored_content_type != raw: + self._parse_content_type(raw) + assert self._content_dict is not None + return self._content_dict.get("charset") + + @property + def content_length(self) -> Optional[int]: + """The value of Content-Length HTTP header.""" + content_length = self._headers.get(hdrs.CONTENT_LENGTH) + return None if content_length is None else int(content_length) + + +def set_result(fut: "asyncio.Future[_T]", result: _T) -> None: + if not fut.done(): + fut.set_result(result) + + +_EXC_SENTINEL = BaseException() + + +class ErrorableProtocol(Protocol): + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = ..., + ) -> None: ... # pragma: no cover + + +def set_exception( + fut: "asyncio.Future[_T] | ErrorableProtocol", + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, +) -> None: + """Set future exception. + + If the future is marked as complete, this function is a no-op. + + :param exc_cause: An exception that is a direct cause of ``exc``. + Only set if provided. + """ + if asyncio.isfuture(fut) and fut.done(): + return + + exc_is_sentinel = exc_cause is _EXC_SENTINEL + exc_causes_itself = exc is exc_cause + if not exc_is_sentinel and not exc_causes_itself: + exc.__cause__ = exc_cause + + fut.set_exception(exc) + + +@functools.total_ordering +class AppKey(Generic[_T]): + """Keys for static typing support in Application.""" + + __slots__ = ("_name", "_t", "__orig_class__") + + # This may be set by Python when instantiating with a generic type. We need to + # support this, in order to support types that are not concrete classes, + # like Iterable, which can't be passed as the second parameter to __init__. + __orig_class__: Type[object] + + def __init__(self, name: str, t: Optional[Type[_T]] = None): + # Prefix with module name to help deduplicate key names. + frame = inspect.currentframe() + while frame: + if frame.f_code.co_name == "": + module: str = frame.f_globals["__name__"] + break + frame = frame.f_back + + self._name = module + "." + name + self._t = t + + def __lt__(self, other: object) -> bool: + if isinstance(other, AppKey): + return self._name < other._name + return True # Order AppKey above other types. + + def __repr__(self) -> str: + t = self._t + if t is None: + with suppress(AttributeError): + # Set to type arg. + t = get_args(self.__orig_class__)[0] + + if t is None: + t_repr = "<>" + elif isinstance(t, type): + if t.__module__ == "builtins": + t_repr = t.__qualname__ + else: + t_repr = f"{t.__module__}.{t.__qualname__}" + else: + t_repr = repr(t) + return f"" + + +class ChainMapProxy(Mapping[Union[str, AppKey[Any]], Any]): + __slots__ = ("_maps",) + + def __init__(self, maps: Iterable[Mapping[Union[str, AppKey[Any]], Any]]) -> None: + self._maps = tuple(maps) + + def __init_subclass__(cls) -> None: + raise TypeError( + "Inheritance class {} from ChainMapProxy " + "is forbidden".format(cls.__name__) + ) + + @overload # type: ignore[override] + def __getitem__(self, key: AppKey[_T]) -> _T: ... + + @overload + def __getitem__(self, key: str) -> Any: ... + + def __getitem__(self, key: Union[str, AppKey[_T]]) -> Any: + for mapping in self._maps: + try: + return mapping[key] + except KeyError: + pass + raise KeyError(key) + + @overload # type: ignore[override] + def get(self, key: AppKey[_T], default: _S) -> Union[_T, _S]: ... + + @overload + def get(self, key: AppKey[_T], default: None = ...) -> Optional[_T]: ... + + @overload + def get(self, key: str, default: Any = ...) -> Any: ... + + def get(self, key: Union[str, AppKey[_T]], default: Any = None) -> Any: + try: + return self[key] + except KeyError: + return default + + def __len__(self) -> int: + # reuses stored hash values if possible + return len(set().union(*self._maps)) + + def __iter__(self) -> Iterator[Union[str, AppKey[Any]]]: + d: Dict[Union[str, AppKey[Any]], Any] = {} + for mapping in reversed(self._maps): + # reuses stored hash values if possible + d.update(mapping) + return iter(d) + + def __contains__(self, key: object) -> bool: + return any(key in m for m in self._maps) + + def __bool__(self) -> bool: + return any(self._maps) + + def __repr__(self) -> str: + content = ", ".join(map(repr, self._maps)) + return f"ChainMapProxy({content})" + + +# https://tools.ietf.org/html/rfc7232#section-2.3 +_ETAGC = r"[!\x23-\x7E\x80-\xff]+" +_ETAGC_RE = re.compile(_ETAGC) +_QUOTED_ETAG = rf'(W/)?"({_ETAGC})"' +QUOTED_ETAG_RE = re.compile(_QUOTED_ETAG) +LIST_QUOTED_ETAG_RE = re.compile(rf"({_QUOTED_ETAG})(?:\s*,\s*|$)|(.)") + +ETAG_ANY = "*" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class ETag: + value: str + is_weak: bool = False + + +def validate_etag_value(value: str) -> None: + if value != ETAG_ANY and not _ETAGC_RE.fullmatch(value): + raise ValueError( + f"Value {value!r} is not a valid etag. Maybe it contains '\"'?" + ) + + +def parse_http_date(date_str: Optional[str]) -> Optional[datetime.datetime]: + """Process a date string, return a datetime object""" + if date_str is not None: + timetuple = parsedate(date_str) + if timetuple is not None: + with suppress(ValueError): + return datetime.datetime(*timetuple[:6], tzinfo=datetime.timezone.utc) + return None + + +@functools.lru_cache +def must_be_empty_body(method: str, code: int) -> bool: + """Check if a request must return an empty body.""" + return ( + code in EMPTY_BODY_STATUS_CODES + or method in EMPTY_BODY_METHODS + or (200 <= code < 300 and method in hdrs.METH_CONNECT_ALL) + ) + + +def should_remove_content_length(method: str, code: int) -> bool: + """Check if a Content-Length header should be removed. + + This should always be a subset of must_be_empty_body + """ + # https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-8 + # https://www.rfc-editor.org/rfc/rfc9110.html#section-15.4.5-4 + return code in EMPTY_BODY_STATUS_CODES or ( + 200 <= code < 300 and method in hdrs.METH_CONNECT_ALL + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http.py new file mode 100644 index 0000000000000000000000000000000000000000..a1feae2d9b8fe631d539a15dbf8e5ea2914d70d5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http.py @@ -0,0 +1,72 @@ +import sys +from http import HTTPStatus +from typing import Mapping, Tuple + +from . import __version__ +from .http_exceptions import HttpProcessingError as HttpProcessingError +from .http_parser import ( + HeadersParser as HeadersParser, + HttpParser as HttpParser, + HttpRequestParser as HttpRequestParser, + HttpResponseParser as HttpResponseParser, + RawRequestMessage as RawRequestMessage, + RawResponseMessage as RawResponseMessage, +) +from .http_websocket import ( + WS_CLOSED_MESSAGE as WS_CLOSED_MESSAGE, + WS_CLOSING_MESSAGE as WS_CLOSING_MESSAGE, + WS_KEY as WS_KEY, + WebSocketError as WebSocketError, + WebSocketReader as WebSocketReader, + WebSocketWriter as WebSocketWriter, + WSCloseCode as WSCloseCode, + WSMessage as WSMessage, + WSMsgType as WSMsgType, + ws_ext_gen as ws_ext_gen, + ws_ext_parse as ws_ext_parse, +) +from .http_writer import ( + HttpVersion as HttpVersion, + HttpVersion10 as HttpVersion10, + HttpVersion11 as HttpVersion11, + StreamWriter as StreamWriter, +) + +__all__ = ( + "HttpProcessingError", + "RESPONSES", + "SERVER_SOFTWARE", + # .http_writer + "StreamWriter", + "HttpVersion", + "HttpVersion10", + "HttpVersion11", + # .http_parser + "HeadersParser", + "HttpParser", + "HttpRequestParser", + "HttpResponseParser", + "RawRequestMessage", + "RawResponseMessage", + # .http_websocket + "WS_CLOSED_MESSAGE", + "WS_CLOSING_MESSAGE", + "WS_KEY", + "WebSocketReader", + "WebSocketWriter", + "ws_ext_gen", + "ws_ext_parse", + "WSMessage", + "WebSocketError", + "WSMsgType", + "WSCloseCode", +) + + +SERVER_SOFTWARE: str = "Python/{0[0]}.{0[1]} aiohttp/{1}".format( + sys.version_info, __version__ +) + +RESPONSES: Mapping[int, Tuple[str, str]] = { + v: (v.phrase, v.description) for v in HTTPStatus.__members__.values() +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_exceptions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..773830211e6e654147afb000992782fb8bff4db8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_exceptions.py @@ -0,0 +1,112 @@ +"""Low-level http related exceptions.""" + +from textwrap import indent +from typing import Optional, Union + +from .typedefs import _CIMultiDict + +__all__ = ("HttpProcessingError",) + + +class HttpProcessingError(Exception): + """HTTP error. + + Shortcut for raising HTTP errors with custom code, message and headers. + + code: HTTP Error code. + message: (optional) Error message. + headers: (optional) Headers to be sent in response, a list of pairs + """ + + code = 0 + message = "" + headers = None + + def __init__( + self, + *, + code: Optional[int] = None, + message: str = "", + headers: Optional[_CIMultiDict] = None, + ) -> None: + if code is not None: + self.code = code + self.headers = headers + self.message = message + + def __str__(self) -> str: + msg = indent(self.message, " ") + return f"{self.code}, message:\n{msg}" + + def __repr__(self) -> str: + return f"<{self.__class__.__name__}: {self.code}, message={self.message!r}>" + + +class BadHttpMessage(HttpProcessingError): + + code = 400 + message = "Bad Request" + + def __init__(self, message: str, *, headers: Optional[_CIMultiDict] = None) -> None: + super().__init__(message=message, headers=headers) + self.args = (message,) + + +class HttpBadRequest(BadHttpMessage): + + code = 400 + message = "Bad Request" + + +class PayloadEncodingError(BadHttpMessage): + """Base class for payload errors""" + + +class ContentEncodingError(PayloadEncodingError): + """Content encoding error.""" + + +class TransferEncodingError(PayloadEncodingError): + """transfer encoding error.""" + + +class ContentLengthError(PayloadEncodingError): + """Not enough data to satisfy content length header.""" + + +class LineTooLong(BadHttpMessage): + def __init__( + self, line: str, limit: str = "Unknown", actual_size: str = "Unknown" + ) -> None: + super().__init__( + f"Got more than {limit} bytes ({actual_size}) when reading {line}." + ) + self.args = (line, limit, actual_size) + + +class InvalidHeader(BadHttpMessage): + def __init__(self, hdr: Union[bytes, str]) -> None: + hdr_s = hdr.decode(errors="backslashreplace") if isinstance(hdr, bytes) else hdr + super().__init__(f"Invalid HTTP header: {hdr!r}") + self.hdr = hdr_s + self.args = (hdr,) + + +class BadStatusLine(BadHttpMessage): + def __init__(self, line: str = "", error: Optional[str] = None) -> None: + if not isinstance(line, str): + line = repr(line) + super().__init__(error or f"Bad status line {line!r}") + self.args = (line,) + self.line = line + + +class BadHttpMethod(BadStatusLine): + """Invalid HTTP method in status line.""" + + def __init__(self, line: str = "", error: Optional[str] = None) -> None: + super().__init__(line, error or f"Bad HTTP method in status line {line!r}") + + +class InvalidURLError(BadHttpMessage): + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_parser.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..9f864b2787666060bb4a5b98717abaf019d843fd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_parser.py @@ -0,0 +1,1050 @@ +import abc +import asyncio +import re +import string +from contextlib import suppress +from enum import IntEnum +from typing import ( + Any, + ClassVar, + Final, + Generic, + List, + Literal, + NamedTuple, + Optional, + Pattern, + Set, + Tuple, + Type, + TypeVar, + Union, +) + +from multidict import CIMultiDict, CIMultiDictProxy, istr +from yarl import URL + +from . import hdrs +from .base_protocol import BaseProtocol +from .compression_utils import HAS_BROTLI, BrotliDecompressor, ZLibDecompressor +from .helpers import ( + _EXC_SENTINEL, + DEBUG, + EMPTY_BODY_METHODS, + EMPTY_BODY_STATUS_CODES, + NO_EXTENSIONS, + BaseTimerContext, + set_exception, +) +from .http_exceptions import ( + BadHttpMessage, + BadHttpMethod, + BadStatusLine, + ContentEncodingError, + ContentLengthError, + InvalidHeader, + InvalidURLError, + LineTooLong, + TransferEncodingError, +) +from .http_writer import HttpVersion, HttpVersion10 +from .streams import EMPTY_PAYLOAD, StreamReader +from .typedefs import RawHeaders + +__all__ = ( + "HeadersParser", + "HttpParser", + "HttpRequestParser", + "HttpResponseParser", + "RawRequestMessage", + "RawResponseMessage", +) + +_SEP = Literal[b"\r\n", b"\n"] + +ASCIISET: Final[Set[str]] = set(string.printable) + +# See https://www.rfc-editor.org/rfc/rfc9110.html#name-overview +# and https://www.rfc-editor.org/rfc/rfc9110.html#name-tokens +# +# method = token +# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" / "+" / "-" / "." / +# "^" / "_" / "`" / "|" / "~" / DIGIT / ALPHA +# token = 1*tchar +_TCHAR_SPECIALS: Final[str] = re.escape("!#$%&'*+-.^_`|~") +TOKENRE: Final[Pattern[str]] = re.compile(f"[0-9A-Za-z{_TCHAR_SPECIALS}]+") +VERSRE: Final[Pattern[str]] = re.compile(r"HTTP/(\d)\.(\d)", re.ASCII) +DIGITS: Final[Pattern[str]] = re.compile(r"\d+", re.ASCII) +HEXDIGITS: Final[Pattern[bytes]] = re.compile(rb"[0-9a-fA-F]+") + + +class RawRequestMessage(NamedTuple): + method: str + path: str + version: HttpVersion + headers: "CIMultiDictProxy[str]" + raw_headers: RawHeaders + should_close: bool + compression: Optional[str] + upgrade: bool + chunked: bool + url: URL + + +class RawResponseMessage(NamedTuple): + version: HttpVersion + code: int + reason: str + headers: CIMultiDictProxy[str] + raw_headers: RawHeaders + should_close: bool + compression: Optional[str] + upgrade: bool + chunked: bool + + +_MsgT = TypeVar("_MsgT", RawRequestMessage, RawResponseMessage) + + +class ParseState(IntEnum): + + PARSE_NONE = 0 + PARSE_LENGTH = 1 + PARSE_CHUNKED = 2 + PARSE_UNTIL_EOF = 3 + + +class ChunkState(IntEnum): + PARSE_CHUNKED_SIZE = 0 + PARSE_CHUNKED_CHUNK = 1 + PARSE_CHUNKED_CHUNK_EOF = 2 + PARSE_MAYBE_TRAILERS = 3 + PARSE_TRAILERS = 4 + + +class HeadersParser: + def __init__( + self, + max_line_size: int = 8190, + max_headers: int = 32768, + max_field_size: int = 8190, + lax: bool = False, + ) -> None: + self.max_line_size = max_line_size + self.max_headers = max_headers + self.max_field_size = max_field_size + self._lax = lax + + def parse_headers( + self, lines: List[bytes] + ) -> Tuple["CIMultiDictProxy[str]", RawHeaders]: + headers: CIMultiDict[str] = CIMultiDict() + # note: "raw" does not mean inclusion of OWS before/after the field value + raw_headers = [] + + lines_idx = 0 + line = lines[lines_idx] + line_count = len(lines) + + while line: + # Parse initial header name : value pair. + try: + bname, bvalue = line.split(b":", 1) + except ValueError: + raise InvalidHeader(line) from None + + if len(bname) == 0: + raise InvalidHeader(bname) + + # https://www.rfc-editor.org/rfc/rfc9112.html#section-5.1-2 + if {bname[0], bname[-1]} & {32, 9}: # {" ", "\t"} + raise InvalidHeader(line) + + bvalue = bvalue.lstrip(b" \t") + if len(bname) > self.max_field_size: + raise LineTooLong( + "request header name {}".format( + bname.decode("utf8", "backslashreplace") + ), + str(self.max_field_size), + str(len(bname)), + ) + name = bname.decode("utf-8", "surrogateescape") + if not TOKENRE.fullmatch(name): + raise InvalidHeader(bname) + + header_length = len(bvalue) + + # next line + lines_idx += 1 + line = lines[lines_idx] + + # consume continuation lines + continuation = self._lax and line and line[0] in (32, 9) # (' ', '\t') + + # Deprecated: https://www.rfc-editor.org/rfc/rfc9112.html#name-obsolete-line-folding + if continuation: + bvalue_lst = [bvalue] + while continuation: + header_length += len(line) + if header_length > self.max_field_size: + raise LineTooLong( + "request header field {}".format( + bname.decode("utf8", "backslashreplace") + ), + str(self.max_field_size), + str(header_length), + ) + bvalue_lst.append(line) + + # next line + lines_idx += 1 + if lines_idx < line_count: + line = lines[lines_idx] + if line: + continuation = line[0] in (32, 9) # (' ', '\t') + else: + line = b"" + break + bvalue = b"".join(bvalue_lst) + else: + if header_length > self.max_field_size: + raise LineTooLong( + "request header field {}".format( + bname.decode("utf8", "backslashreplace") + ), + str(self.max_field_size), + str(header_length), + ) + + bvalue = bvalue.strip(b" \t") + value = bvalue.decode("utf-8", "surrogateescape") + + # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-5 + if "\n" in value or "\r" in value or "\x00" in value: + raise InvalidHeader(bvalue) + + headers.add(name, value) + raw_headers.append((bname, bvalue)) + + return (CIMultiDictProxy(headers), tuple(raw_headers)) + + +def _is_supported_upgrade(headers: CIMultiDictProxy[str]) -> bool: + """Check if the upgrade header is supported.""" + return headers.get(hdrs.UPGRADE, "").lower() in {"tcp", "websocket"} + + +class HttpParser(abc.ABC, Generic[_MsgT]): + lax: ClassVar[bool] = False + + def __init__( + self, + protocol: Optional[BaseProtocol] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + limit: int = 2**16, + max_line_size: int = 8190, + max_headers: int = 32768, + max_field_size: int = 8190, + timer: Optional[BaseTimerContext] = None, + code: Optional[int] = None, + method: Optional[str] = None, + payload_exception: Optional[Type[BaseException]] = None, + response_with_body: bool = True, + read_until_eof: bool = False, + auto_decompress: bool = True, + ) -> None: + self.protocol = protocol + self.loop = loop + self.max_line_size = max_line_size + self.max_headers = max_headers + self.max_field_size = max_field_size + self.timer = timer + self.code = code + self.method = method + self.payload_exception = payload_exception + self.response_with_body = response_with_body + self.read_until_eof = read_until_eof + + self._lines: List[bytes] = [] + self._tail = b"" + self._upgraded = False + self._payload = None + self._payload_parser: Optional[HttpPayloadParser] = None + self._auto_decompress = auto_decompress + self._limit = limit + self._headers_parser = HeadersParser( + max_line_size, max_headers, max_field_size, self.lax + ) + + @abc.abstractmethod + def parse_message(self, lines: List[bytes]) -> _MsgT: ... + + @abc.abstractmethod + def _is_chunked_te(self, te: str) -> bool: ... + + def feed_eof(self) -> Optional[_MsgT]: + if self._payload_parser is not None: + self._payload_parser.feed_eof() + self._payload_parser = None + else: + # try to extract partial message + if self._tail: + self._lines.append(self._tail) + + if self._lines: + if self._lines[-1] != "\r\n": + self._lines.append(b"") + with suppress(Exception): + return self.parse_message(self._lines) + return None + + def feed_data( + self, + data: bytes, + SEP: _SEP = b"\r\n", + EMPTY: bytes = b"", + CONTENT_LENGTH: istr = hdrs.CONTENT_LENGTH, + METH_CONNECT: str = hdrs.METH_CONNECT, + SEC_WEBSOCKET_KEY1: istr = hdrs.SEC_WEBSOCKET_KEY1, + ) -> Tuple[List[Tuple[_MsgT, StreamReader]], bool, bytes]: + + messages = [] + + if self._tail: + data, self._tail = self._tail + data, b"" + + data_len = len(data) + start_pos = 0 + loop = self.loop + + should_close = False + while start_pos < data_len: + + # read HTTP message (request/response line + headers), \r\n\r\n + # and split by lines + if self._payload_parser is None and not self._upgraded: + pos = data.find(SEP, start_pos) + # consume \r\n + if pos == start_pos and not self._lines: + start_pos = pos + len(SEP) + continue + + if pos >= start_pos: + if should_close: + raise BadHttpMessage("Data after `Connection: close`") + + # line found + line = data[start_pos:pos] + if SEP == b"\n": # For lax response parsing + line = line.rstrip(b"\r") + self._lines.append(line) + start_pos = pos + len(SEP) + + # \r\n\r\n found + if self._lines[-1] == EMPTY: + try: + msg: _MsgT = self.parse_message(self._lines) + finally: + self._lines.clear() + + def get_content_length() -> Optional[int]: + # payload length + length_hdr = msg.headers.get(CONTENT_LENGTH) + if length_hdr is None: + return None + + # Shouldn't allow +/- or other number formats. + # https://www.rfc-editor.org/rfc/rfc9110#section-8.6-2 + # msg.headers is already stripped of leading/trailing wsp + if not DIGITS.fullmatch(length_hdr): + raise InvalidHeader(CONTENT_LENGTH) + + return int(length_hdr) + + length = get_content_length() + # do not support old websocket spec + if SEC_WEBSOCKET_KEY1 in msg.headers: + raise InvalidHeader(SEC_WEBSOCKET_KEY1) + + self._upgraded = msg.upgrade and _is_supported_upgrade( + msg.headers + ) + + method = getattr(msg, "method", self.method) + # code is only present on responses + code = getattr(msg, "code", 0) + + assert self.protocol is not None + # calculate payload + empty_body = code in EMPTY_BODY_STATUS_CODES or bool( + method and method in EMPTY_BODY_METHODS + ) + if not empty_body and ( + ((length is not None and length > 0) or msg.chunked) + and not self._upgraded + ): + payload = StreamReader( + self.protocol, + timer=self.timer, + loop=loop, + limit=self._limit, + ) + payload_parser = HttpPayloadParser( + payload, + length=length, + chunked=msg.chunked, + method=method, + compression=msg.compression, + code=self.code, + response_with_body=self.response_with_body, + auto_decompress=self._auto_decompress, + lax=self.lax, + headers_parser=self._headers_parser, + ) + if not payload_parser.done: + self._payload_parser = payload_parser + elif method == METH_CONNECT: + assert isinstance(msg, RawRequestMessage) + payload = StreamReader( + self.protocol, + timer=self.timer, + loop=loop, + limit=self._limit, + ) + self._upgraded = True + self._payload_parser = HttpPayloadParser( + payload, + method=msg.method, + compression=msg.compression, + auto_decompress=self._auto_decompress, + lax=self.lax, + headers_parser=self._headers_parser, + ) + elif not empty_body and length is None and self.read_until_eof: + payload = StreamReader( + self.protocol, + timer=self.timer, + loop=loop, + limit=self._limit, + ) + payload_parser = HttpPayloadParser( + payload, + length=length, + chunked=msg.chunked, + method=method, + compression=msg.compression, + code=self.code, + response_with_body=self.response_with_body, + auto_decompress=self._auto_decompress, + lax=self.lax, + headers_parser=self._headers_parser, + ) + if not payload_parser.done: + self._payload_parser = payload_parser + else: + payload = EMPTY_PAYLOAD + + messages.append((msg, payload)) + should_close = msg.should_close + else: + self._tail = data[start_pos:] + data = EMPTY + break + + # no parser, just store + elif self._payload_parser is None and self._upgraded: + assert not self._lines + break + + # feed payload + elif data and start_pos < data_len: + assert not self._lines + assert self._payload_parser is not None + try: + eof, data = self._payload_parser.feed_data(data[start_pos:], SEP) + except BaseException as underlying_exc: + reraised_exc = underlying_exc + if self.payload_exception is not None: + reraised_exc = self.payload_exception(str(underlying_exc)) + + set_exception( + self._payload_parser.payload, + reraised_exc, + underlying_exc, + ) + + eof = True + data = b"" + if isinstance( + underlying_exc, (InvalidHeader, TransferEncodingError) + ): + raise + + if eof: + start_pos = 0 + data_len = len(data) + self._payload_parser = None + continue + else: + break + + if data and start_pos < data_len: + data = data[start_pos:] + else: + data = EMPTY + + return messages, self._upgraded, data + + def parse_headers( + self, lines: List[bytes] + ) -> Tuple[ + "CIMultiDictProxy[str]", RawHeaders, Optional[bool], Optional[str], bool, bool + ]: + """Parses RFC 5322 headers from a stream. + + Line continuations are supported. Returns list of header name + and value pairs. Header name is in upper case. + """ + headers, raw_headers = self._headers_parser.parse_headers(lines) + close_conn = None + encoding = None + upgrade = False + chunked = False + + # https://www.rfc-editor.org/rfc/rfc9110.html#section-5.5-6 + # https://www.rfc-editor.org/rfc/rfc9110.html#name-collected-abnf + singletons = ( + hdrs.CONTENT_LENGTH, + hdrs.CONTENT_LOCATION, + hdrs.CONTENT_RANGE, + hdrs.CONTENT_TYPE, + hdrs.ETAG, + hdrs.HOST, + hdrs.MAX_FORWARDS, + hdrs.SERVER, + hdrs.TRANSFER_ENCODING, + hdrs.USER_AGENT, + ) + bad_hdr = next((h for h in singletons if len(headers.getall(h, ())) > 1), None) + if bad_hdr is not None: + raise BadHttpMessage(f"Duplicate '{bad_hdr}' header found.") + + # keep-alive + conn = headers.get(hdrs.CONNECTION) + if conn: + v = conn.lower() + if v == "close": + close_conn = True + elif v == "keep-alive": + close_conn = False + # https://www.rfc-editor.org/rfc/rfc9110.html#name-101-switching-protocols + elif v == "upgrade" and headers.get(hdrs.UPGRADE): + upgrade = True + + # encoding + enc = headers.get(hdrs.CONTENT_ENCODING) + if enc: + enc = enc.lower() + if enc in ("gzip", "deflate", "br"): + encoding = enc + + # chunking + te = headers.get(hdrs.TRANSFER_ENCODING) + if te is not None: + if self._is_chunked_te(te): + chunked = True + + if hdrs.CONTENT_LENGTH in headers: + raise BadHttpMessage( + "Transfer-Encoding can't be present with Content-Length", + ) + + return (headers, raw_headers, close_conn, encoding, upgrade, chunked) + + def set_upgraded(self, val: bool) -> None: + """Set connection upgraded (to websocket) mode. + + :param bool val: new state. + """ + self._upgraded = val + + +class HttpRequestParser(HttpParser[RawRequestMessage]): + """Read request status line. + + Exception .http_exceptions.BadStatusLine + could be raised in case of any errors in status line. + Returns RawRequestMessage. + """ + + def parse_message(self, lines: List[bytes]) -> RawRequestMessage: + # request line + line = lines[0].decode("utf-8", "surrogateescape") + try: + method, path, version = line.split(" ", maxsplit=2) + except ValueError: + raise BadHttpMethod(line) from None + + if len(path) > self.max_line_size: + raise LineTooLong( + "Status line is too long", str(self.max_line_size), str(len(path)) + ) + + # method + if not TOKENRE.fullmatch(method): + raise BadHttpMethod(method) + + # version + match = VERSRE.fullmatch(version) + if match is None: + raise BadStatusLine(line) + version_o = HttpVersion(int(match.group(1)), int(match.group(2))) + + if method == "CONNECT": + # authority-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3 + url = URL.build(authority=path, encoded=True) + elif path.startswith("/"): + # origin-form, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.1 + path_part, _hash_separator, url_fragment = path.partition("#") + path_part, _question_mark_separator, qs_part = path_part.partition("?") + + # NOTE: `yarl.URL.build()` is used to mimic what the Cython-based + # NOTE: parser does, otherwise it results into the same + # NOTE: HTTP Request-Line input producing different + # NOTE: `yarl.URL()` objects + url = URL.build( + path=path_part, + query_string=qs_part, + fragment=url_fragment, + encoded=True, + ) + elif path == "*" and method == "OPTIONS": + # asterisk-form, + url = URL(path, encoded=True) + else: + # absolute-form for proxy maybe, + # https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.2 + url = URL(path, encoded=True) + if url.scheme == "": + # not absolute-form + raise InvalidURLError( + path.encode(errors="surrogateescape").decode("latin1") + ) + + # read headers + ( + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + ) = self.parse_headers(lines[1:]) + + if close is None: # then the headers weren't set in the request + if version_o <= HttpVersion10: # HTTP 1.0 must asks to not close + close = True + else: # HTTP 1.1 must ask to close. + close = False + + return RawRequestMessage( + method, + path, + version_o, + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + url, + ) + + def _is_chunked_te(self, te: str) -> bool: + if te.rsplit(",", maxsplit=1)[-1].strip(" \t").lower() == "chunked": + return True + # https://www.rfc-editor.org/rfc/rfc9112#section-6.3-2.4.3 + raise BadHttpMessage("Request has invalid `Transfer-Encoding`") + + +class HttpResponseParser(HttpParser[RawResponseMessage]): + """Read response status line and headers. + + BadStatusLine could be raised in case of any errors in status line. + Returns RawResponseMessage. + """ + + # Lax mode should only be enabled on response parser. + lax = not DEBUG + + def feed_data( + self, + data: bytes, + SEP: Optional[_SEP] = None, + *args: Any, + **kwargs: Any, + ) -> Tuple[List[Tuple[RawResponseMessage, StreamReader]], bool, bytes]: + if SEP is None: + SEP = b"\r\n" if DEBUG else b"\n" + return super().feed_data(data, SEP, *args, **kwargs) + + def parse_message(self, lines: List[bytes]) -> RawResponseMessage: + line = lines[0].decode("utf-8", "surrogateescape") + try: + version, status = line.split(maxsplit=1) + except ValueError: + raise BadStatusLine(line) from None + + try: + status, reason = status.split(maxsplit=1) + except ValueError: + status = status.strip() + reason = "" + + if len(reason) > self.max_line_size: + raise LineTooLong( + "Status line is too long", str(self.max_line_size), str(len(reason)) + ) + + # version + match = VERSRE.fullmatch(version) + if match is None: + raise BadStatusLine(line) + version_o = HttpVersion(int(match.group(1)), int(match.group(2))) + + # The status code is a three-digit ASCII number, no padding + if len(status) != 3 or not DIGITS.fullmatch(status): + raise BadStatusLine(line) + status_i = int(status) + + # read headers + ( + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + ) = self.parse_headers(lines[1:]) + + if close is None: + if version_o <= HttpVersion10: + close = True + # https://www.rfc-editor.org/rfc/rfc9112.html#name-message-body-length + elif 100 <= status_i < 200 or status_i in {204, 304}: + close = False + elif hdrs.CONTENT_LENGTH in headers or hdrs.TRANSFER_ENCODING in headers: + close = False + else: + # https://www.rfc-editor.org/rfc/rfc9112.html#section-6.3-2.8 + close = True + + return RawResponseMessage( + version_o, + status_i, + reason.strip(), + headers, + raw_headers, + close, + compression, + upgrade, + chunked, + ) + + def _is_chunked_te(self, te: str) -> bool: + # https://www.rfc-editor.org/rfc/rfc9112#section-6.3-2.4.2 + return te.rsplit(",", maxsplit=1)[-1].strip(" \t").lower() == "chunked" + + +class HttpPayloadParser: + def __init__( + self, + payload: StreamReader, + length: Optional[int] = None, + chunked: bool = False, + compression: Optional[str] = None, + code: Optional[int] = None, + method: Optional[str] = None, + response_with_body: bool = True, + auto_decompress: bool = True, + lax: bool = False, + *, + headers_parser: HeadersParser, + ) -> None: + self._length = 0 + self._type = ParseState.PARSE_UNTIL_EOF + self._chunk = ChunkState.PARSE_CHUNKED_SIZE + self._chunk_size = 0 + self._chunk_tail = b"" + self._auto_decompress = auto_decompress + self._lax = lax + self._headers_parser = headers_parser + self._trailer_lines: list[bytes] = [] + self.done = False + + # payload decompression wrapper + if response_with_body and compression and self._auto_decompress: + real_payload: Union[StreamReader, DeflateBuffer] = DeflateBuffer( + payload, compression + ) + else: + real_payload = payload + + # payload parser + if not response_with_body: + # don't parse payload if it's not expected to be received + self._type = ParseState.PARSE_NONE + real_payload.feed_eof() + self.done = True + elif chunked: + self._type = ParseState.PARSE_CHUNKED + elif length is not None: + self._type = ParseState.PARSE_LENGTH + self._length = length + if self._length == 0: + real_payload.feed_eof() + self.done = True + + self.payload = real_payload + + def feed_eof(self) -> None: + if self._type == ParseState.PARSE_UNTIL_EOF: + self.payload.feed_eof() + elif self._type == ParseState.PARSE_LENGTH: + raise ContentLengthError( + "Not enough data to satisfy content length header." + ) + elif self._type == ParseState.PARSE_CHUNKED: + raise TransferEncodingError( + "Not enough data to satisfy transfer length header." + ) + + def feed_data( + self, chunk: bytes, SEP: _SEP = b"\r\n", CHUNK_EXT: bytes = b";" + ) -> Tuple[bool, bytes]: + # Read specified amount of bytes + if self._type == ParseState.PARSE_LENGTH: + required = self._length + chunk_len = len(chunk) + + if required >= chunk_len: + self._length = required - chunk_len + self.payload.feed_data(chunk, chunk_len) + if self._length == 0: + self.payload.feed_eof() + return True, b"" + else: + self._length = 0 + self.payload.feed_data(chunk[:required], required) + self.payload.feed_eof() + return True, chunk[required:] + + # Chunked transfer encoding parser + elif self._type == ParseState.PARSE_CHUNKED: + if self._chunk_tail: + chunk = self._chunk_tail + chunk + self._chunk_tail = b"" + + while chunk: + + # read next chunk size + if self._chunk == ChunkState.PARSE_CHUNKED_SIZE: + pos = chunk.find(SEP) + if pos >= 0: + i = chunk.find(CHUNK_EXT, 0, pos) + if i >= 0: + size_b = chunk[:i] # strip chunk-extensions + # Verify no LF in the chunk-extension + if b"\n" in (ext := chunk[i:pos]): + exc = TransferEncodingError( + f"Unexpected LF in chunk-extension: {ext!r}" + ) + set_exception(self.payload, exc) + raise exc + else: + size_b = chunk[:pos] + + if self._lax: # Allow whitespace in lax mode. + size_b = size_b.strip() + + if not re.fullmatch(HEXDIGITS, size_b): + exc = TransferEncodingError( + chunk[:pos].decode("ascii", "surrogateescape") + ) + set_exception(self.payload, exc) + raise exc + size = int(bytes(size_b), 16) + + chunk = chunk[pos + len(SEP) :] + if size == 0: # eof marker + self._chunk = ChunkState.PARSE_TRAILERS + if self._lax and chunk.startswith(b"\r"): + chunk = chunk[1:] + else: + self._chunk = ChunkState.PARSE_CHUNKED_CHUNK + self._chunk_size = size + self.payload.begin_http_chunk_receiving() + else: + self._chunk_tail = chunk + return False, b"" + + # read chunk and feed buffer + if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK: + required = self._chunk_size + chunk_len = len(chunk) + + if required > chunk_len: + self._chunk_size = required - chunk_len + self.payload.feed_data(chunk, chunk_len) + return False, b"" + else: + self._chunk_size = 0 + self.payload.feed_data(chunk[:required], required) + chunk = chunk[required:] + self._chunk = ChunkState.PARSE_CHUNKED_CHUNK_EOF + self.payload.end_http_chunk_receiving() + + # toss the CRLF at the end of the chunk + if self._chunk == ChunkState.PARSE_CHUNKED_CHUNK_EOF: + if self._lax and chunk.startswith(b"\r"): + chunk = chunk[1:] + if chunk[: len(SEP)] == SEP: + chunk = chunk[len(SEP) :] + self._chunk = ChunkState.PARSE_CHUNKED_SIZE + else: + self._chunk_tail = chunk + return False, b"" + + if self._chunk == ChunkState.PARSE_TRAILERS: + pos = chunk.find(SEP) + if pos < 0: # No line found + self._chunk_tail = chunk + return False, b"" + + line = chunk[:pos] + chunk = chunk[pos + len(SEP) :] + if SEP == b"\n": # For lax response parsing + line = line.rstrip(b"\r") + self._trailer_lines.append(line) + + # \r\n\r\n found, end of stream + if self._trailer_lines[-1] == b"": + # Headers and trailers are defined the same way, + # so we reuse the HeadersParser here. + try: + trailers, raw_trailers = self._headers_parser.parse_headers( + self._trailer_lines + ) + finally: + self._trailer_lines.clear() + self.payload.feed_eof() + return True, chunk + + # Read all bytes until eof + elif self._type == ParseState.PARSE_UNTIL_EOF: + self.payload.feed_data(chunk, len(chunk)) + + return False, b"" + + +class DeflateBuffer: + """DeflateStream decompress stream and feed data into specified stream.""" + + decompressor: Any + + def __init__(self, out: StreamReader, encoding: Optional[str]) -> None: + self.out = out + self.size = 0 + self.encoding = encoding + self._started_decoding = False + + self.decompressor: Union[BrotliDecompressor, ZLibDecompressor] + if encoding == "br": + if not HAS_BROTLI: # pragma: no cover + raise ContentEncodingError( + "Can not decode content-encoding: brotli (br). " + "Please install `Brotli`" + ) + self.decompressor = BrotliDecompressor() + else: + self.decompressor = ZLibDecompressor(encoding=encoding) + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + set_exception(self.out, exc, exc_cause) + + def feed_data(self, chunk: bytes, size: int) -> None: + if not size: + return + + self.size += size + + # RFC1950 + # bits 0..3 = CM = 0b1000 = 8 = "deflate" + # bits 4..7 = CINFO = 1..7 = windows size. + if ( + not self._started_decoding + and self.encoding == "deflate" + and chunk[0] & 0xF != 8 + ): + # Change the decoder to decompress incorrectly compressed data + # Actually we should issue a warning about non-RFC-compliant data. + self.decompressor = ZLibDecompressor( + encoding=self.encoding, suppress_deflate_header=True + ) + + try: + chunk = self.decompressor.decompress_sync(chunk) + except Exception: + raise ContentEncodingError( + "Can not decode content-encoding: %s" % self.encoding + ) + + self._started_decoding = True + + if chunk: + self.out.feed_data(chunk, len(chunk)) + + def feed_eof(self) -> None: + chunk = self.decompressor.flush() + + if chunk or self.size > 0: + self.out.feed_data(chunk, len(chunk)) + if self.encoding == "deflate" and not self.decompressor.eof: + raise ContentEncodingError("deflate") + + self.out.feed_eof() + + def begin_http_chunk_receiving(self) -> None: + self.out.begin_http_chunk_receiving() + + def end_http_chunk_receiving(self) -> None: + self.out.end_http_chunk_receiving() + + +HttpRequestParserPy = HttpRequestParser +HttpResponseParserPy = HttpResponseParser +RawRequestMessagePy = RawRequestMessage +RawResponseMessagePy = RawResponseMessage + +try: + if not NO_EXTENSIONS: + from ._http_parser import ( # type: ignore[import-not-found,no-redef] + HttpRequestParser, + HttpResponseParser, + RawRequestMessage, + RawResponseMessage, + ) + + HttpRequestParserC = HttpRequestParser + HttpResponseParserC = HttpResponseParser + RawRequestMessageC = RawRequestMessage + RawResponseMessageC = RawResponseMessage +except ImportError: # pragma: no cover + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_websocket.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_websocket.py new file mode 100644 index 0000000000000000000000000000000000000000..6b4b30e02b247e30e0c84d3eb118b749bbe52079 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_websocket.py @@ -0,0 +1,36 @@ +"""WebSocket protocol versions 13 and 8.""" + +from ._websocket.helpers import WS_KEY, ws_ext_gen, ws_ext_parse +from ._websocket.models import ( + WS_CLOSED_MESSAGE, + WS_CLOSING_MESSAGE, + WebSocketError, + WSCloseCode, + WSHandshakeError, + WSMessage, + WSMsgType, +) +from ._websocket.reader import WebSocketReader +from ._websocket.writer import WebSocketWriter + +# Messages that the WebSocketResponse.receive needs to handle internally +_INTERNAL_RECEIVE_TYPES = frozenset( + (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.PING, WSMsgType.PONG) +) + + +__all__ = ( + "WS_CLOSED_MESSAGE", + "WS_CLOSING_MESSAGE", + "WS_KEY", + "WebSocketReader", + "WebSocketWriter", + "WSMessage", + "WebSocketError", + "WSMsgType", + "WSCloseCode", + "ws_ext_gen", + "ws_ext_parse", + "WSHandshakeError", + "WSMessage", +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_writer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_writer.py new file mode 100644 index 0000000000000000000000000000000000000000..a140b218b25fedccb49451c547d4d01326367cfb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/http_writer.py @@ -0,0 +1,378 @@ +"""Http related parsers and protocol.""" + +import asyncio +import sys +from typing import ( # noqa + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Iterable, + List, + NamedTuple, + Optional, + Union, +) + +from multidict import CIMultiDict + +from .abc import AbstractStreamWriter +from .base_protocol import BaseProtocol +from .client_exceptions import ClientConnectionResetError +from .compression_utils import ZLibCompressor +from .helpers import NO_EXTENSIONS + +__all__ = ("StreamWriter", "HttpVersion", "HttpVersion10", "HttpVersion11") + + +MIN_PAYLOAD_FOR_WRITELINES = 2048 +IS_PY313_BEFORE_313_2 = (3, 13, 0) <= sys.version_info < (3, 13, 2) +IS_PY_BEFORE_312_9 = sys.version_info < (3, 12, 9) +SKIP_WRITELINES = IS_PY313_BEFORE_313_2 or IS_PY_BEFORE_312_9 +# writelines is not safe for use +# on Python 3.12+ until 3.12.9 +# on Python 3.13+ until 3.13.2 +# and on older versions it not any faster than write +# CVE-2024-12254: https://github.com/python/cpython/pull/127656 + + +class HttpVersion(NamedTuple): + major: int + minor: int + + +HttpVersion10 = HttpVersion(1, 0) +HttpVersion11 = HttpVersion(1, 1) + + +_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] +_T_OnHeadersSent = Optional[Callable[["CIMultiDict[str]"], Awaitable[None]]] + + +class StreamWriter(AbstractStreamWriter): + + length: Optional[int] = None + chunked: bool = False + _eof: bool = False + _compress: Optional[ZLibCompressor] = None + + def __init__( + self, + protocol: BaseProtocol, + loop: asyncio.AbstractEventLoop, + on_chunk_sent: _T_OnChunkSent = None, + on_headers_sent: _T_OnHeadersSent = None, + ) -> None: + self._protocol = protocol + self.loop = loop + self._on_chunk_sent: _T_OnChunkSent = on_chunk_sent + self._on_headers_sent: _T_OnHeadersSent = on_headers_sent + self._headers_buf: Optional[bytes] = None + self._headers_written: bool = False + + @property + def transport(self) -> Optional[asyncio.Transport]: + return self._protocol.transport + + @property + def protocol(self) -> BaseProtocol: + return self._protocol + + def enable_chunking(self) -> None: + self.chunked = True + + def enable_compression( + self, encoding: str = "deflate", strategy: Optional[int] = None + ) -> None: + self._compress = ZLibCompressor(encoding=encoding, strategy=strategy) + + def _write(self, chunk: Union[bytes, bytearray, memoryview]) -> None: + size = len(chunk) + self.buffer_size += size + self.output_size += size + transport = self._protocol.transport + if transport is None or transport.is_closing(): + raise ClientConnectionResetError("Cannot write to closing transport") + transport.write(chunk) + + def _writelines(self, chunks: Iterable[bytes]) -> None: + size = 0 + for chunk in chunks: + size += len(chunk) + self.buffer_size += size + self.output_size += size + transport = self._protocol.transport + if transport is None or transport.is_closing(): + raise ClientConnectionResetError("Cannot write to closing transport") + if SKIP_WRITELINES or size < MIN_PAYLOAD_FOR_WRITELINES: + transport.write(b"".join(chunks)) + else: + transport.writelines(chunks) + + def _write_chunked_payload( + self, chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"] + ) -> None: + """Write a chunk with proper chunked encoding.""" + chunk_len_pre = f"{len(chunk):x}\r\n".encode("ascii") + self._writelines((chunk_len_pre, chunk, b"\r\n")) + + def _send_headers_with_payload( + self, + chunk: Union[bytes, bytearray, "memoryview[int]", "memoryview[bytes]"], + is_eof: bool, + ) -> None: + """Send buffered headers with payload, coalescing into single write.""" + # Mark headers as written + self._headers_written = True + headers_buf = self._headers_buf + self._headers_buf = None + + if TYPE_CHECKING: + # Safe because callers (write() and write_eof()) only invoke this method + # after checking that self._headers_buf is truthy + assert headers_buf is not None + + if not self.chunked: + # Non-chunked: coalesce headers with body + if chunk: + self._writelines((headers_buf, chunk)) + else: + self._write(headers_buf) + return + + # Coalesce headers with chunked data + if chunk: + chunk_len_pre = f"{len(chunk):x}\r\n".encode("ascii") + if is_eof: + self._writelines((headers_buf, chunk_len_pre, chunk, b"\r\n0\r\n\r\n")) + else: + self._writelines((headers_buf, chunk_len_pre, chunk, b"\r\n")) + elif is_eof: + self._writelines((headers_buf, b"0\r\n\r\n")) + else: + self._write(headers_buf) + + async def write( + self, + chunk: Union[bytes, bytearray, memoryview], + *, + drain: bool = True, + LIMIT: int = 0x10000, + ) -> None: + """ + Writes chunk of data to a stream. + + write_eof() indicates end of stream. + writer can't be used after write_eof() method being called. + write() return drain future. + """ + if self._on_chunk_sent is not None: + await self._on_chunk_sent(chunk) + + if isinstance(chunk, memoryview): + if chunk.nbytes != len(chunk): + # just reshape it + chunk = chunk.cast("c") + + if self._compress is not None: + chunk = await self._compress.compress(chunk) + if not chunk: + return + + if self.length is not None: + chunk_len = len(chunk) + if self.length >= chunk_len: + self.length = self.length - chunk_len + else: + chunk = chunk[: self.length] + self.length = 0 + if not chunk: + return + + # Handle buffered headers for small payload optimization + if self._headers_buf and not self._headers_written: + self._send_headers_with_payload(chunk, False) + if drain and self.buffer_size > LIMIT: + self.buffer_size = 0 + await self.drain() + return + + if chunk: + if self.chunked: + self._write_chunked_payload(chunk) + else: + self._write(chunk) + + if drain and self.buffer_size > LIMIT: + self.buffer_size = 0 + await self.drain() + + async def write_headers( + self, status_line: str, headers: "CIMultiDict[str]" + ) -> None: + """Write headers to the stream.""" + if self._on_headers_sent is not None: + await self._on_headers_sent(headers) + # status + headers + buf = _serialize_headers(status_line, headers) + self._headers_written = False + self._headers_buf = buf + + def send_headers(self) -> None: + """Force sending buffered headers if not already sent.""" + if not self._headers_buf or self._headers_written: + return + + self._headers_written = True + headers_buf = self._headers_buf + self._headers_buf = None + + if TYPE_CHECKING: + # Safe because we only enter this block when self._headers_buf is truthy + assert headers_buf is not None + + self._write(headers_buf) + + def set_eof(self) -> None: + """Indicate that the message is complete.""" + if self._eof: + return + + # If headers haven't been sent yet, send them now + # This handles the case where there's no body at all + if self._headers_buf and not self._headers_written: + self._headers_written = True + headers_buf = self._headers_buf + self._headers_buf = None + + if TYPE_CHECKING: + # Safe because we only enter this block when self._headers_buf is truthy + assert headers_buf is not None + + # Combine headers and chunked EOF marker in a single write + if self.chunked: + self._writelines((headers_buf, b"0\r\n\r\n")) + else: + self._write(headers_buf) + elif self.chunked and self._headers_written: + # Headers already sent, just send the final chunk marker + self._write(b"0\r\n\r\n") + + self._eof = True + + async def write_eof(self, chunk: bytes = b"") -> None: + if self._eof: + return + + if chunk and self._on_chunk_sent is not None: + await self._on_chunk_sent(chunk) + + # Handle body/compression + if self._compress: + chunks: List[bytes] = [] + chunks_len = 0 + if chunk and (compressed_chunk := await self._compress.compress(chunk)): + chunks_len = len(compressed_chunk) + chunks.append(compressed_chunk) + + flush_chunk = self._compress.flush() + chunks_len += len(flush_chunk) + chunks.append(flush_chunk) + assert chunks_len + + # Send buffered headers with compressed data if not yet sent + if self._headers_buf and not self._headers_written: + self._headers_written = True + headers_buf = self._headers_buf + self._headers_buf = None + + if self.chunked: + # Coalesce headers with compressed chunked data + chunk_len_pre = f"{chunks_len:x}\r\n".encode("ascii") + self._writelines( + (headers_buf, chunk_len_pre, *chunks, b"\r\n0\r\n\r\n") + ) + else: + # Coalesce headers with compressed data + self._writelines((headers_buf, *chunks)) + await self.drain() + self._eof = True + return + + # Headers already sent, just write compressed data + if self.chunked: + chunk_len_pre = f"{chunks_len:x}\r\n".encode("ascii") + self._writelines((chunk_len_pre, *chunks, b"\r\n0\r\n\r\n")) + elif len(chunks) > 1: + self._writelines(chunks) + else: + self._write(chunks[0]) + await self.drain() + self._eof = True + return + + # No compression - send buffered headers if not yet sent + if self._headers_buf and not self._headers_written: + # Use helper to send headers with payload + self._send_headers_with_payload(chunk, True) + await self.drain() + self._eof = True + return + + # Handle remaining body + if self.chunked: + if chunk: + # Write final chunk with EOF marker + self._writelines( + (f"{len(chunk):x}\r\n".encode("ascii"), chunk, b"\r\n0\r\n\r\n") + ) + else: + self._write(b"0\r\n\r\n") + await self.drain() + self._eof = True + return + + if chunk: + self._write(chunk) + await self.drain() + + self._eof = True + + async def drain(self) -> None: + """Flush the write buffer. + + The intended use is to write + + await w.write(data) + await w.drain() + """ + protocol = self._protocol + if protocol.transport is not None and protocol._paused: + await protocol._drain_helper() + + +def _safe_header(string: str) -> str: + if "\r" in string or "\n" in string: + raise ValueError( + "Newline or carriage return detected in headers. " + "Potential header injection attack." + ) + return string + + +def _py_serialize_headers(status_line: str, headers: "CIMultiDict[str]") -> bytes: + headers_gen = (_safe_header(k) + ": " + _safe_header(v) for k, v in headers.items()) + line = status_line + "\r\n" + "\r\n".join(headers_gen) + "\r\n\r\n" + return line.encode("utf-8") + + +_serialize_headers = _py_serialize_headers + +try: + import aiohttp._http_writer as _http_writer # type: ignore[import-not-found] + + _c_serialize_headers = _http_writer._serialize_headers + if not NO_EXTENSIONS: + _serialize_headers = _c_serialize_headers +except ImportError: + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/log.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/log.py new file mode 100644 index 0000000000000000000000000000000000000000..3cecea2bac185df741bccd0a32a5fef9cfe23299 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/log.py @@ -0,0 +1,8 @@ +import logging + +access_logger = logging.getLogger("aiohttp.access") +client_logger = logging.getLogger("aiohttp.client") +internal_logger = logging.getLogger("aiohttp.internal") +server_logger = logging.getLogger("aiohttp.server") +web_logger = logging.getLogger("aiohttp.web") +ws_logger = logging.getLogger("aiohttp.websocket") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/multipart.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/multipart.py new file mode 100644 index 0000000000000000000000000000000000000000..026051467203ec85bf54ebf38a088a7d20ea73d5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/multipart.py @@ -0,0 +1,1140 @@ +import base64 +import binascii +import json +import re +import sys +import uuid +import warnings +from collections import deque +from collections.abc import Mapping, Sequence +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Deque, + Dict, + Iterator, + List, + Optional, + Tuple, + Type, + Union, + cast, +) +from urllib.parse import parse_qsl, unquote, urlencode + +from multidict import CIMultiDict, CIMultiDictProxy + +from .compression_utils import ZLibCompressor, ZLibDecompressor +from .hdrs import ( + CONTENT_DISPOSITION, + CONTENT_ENCODING, + CONTENT_LENGTH, + CONTENT_TRANSFER_ENCODING, + CONTENT_TYPE, +) +from .helpers import CHAR, TOKEN, parse_mimetype, reify +from .http import HeadersParser +from .log import internal_logger +from .payload import ( + JsonPayload, + LookupError, + Order, + Payload, + StringPayload, + get_payload, + payload_type, +) +from .streams import StreamReader + +if sys.version_info >= (3, 11): + from typing import Self +else: + from typing import TypeVar + + Self = TypeVar("Self", bound="BodyPartReader") + +__all__ = ( + "MultipartReader", + "MultipartWriter", + "BodyPartReader", + "BadContentDispositionHeader", + "BadContentDispositionParam", + "parse_content_disposition", + "content_disposition_filename", +) + + +if TYPE_CHECKING: + from .client_reqrep import ClientResponse + + +class BadContentDispositionHeader(RuntimeWarning): + pass + + +class BadContentDispositionParam(RuntimeWarning): + pass + + +def parse_content_disposition( + header: Optional[str], +) -> Tuple[Optional[str], Dict[str, str]]: + def is_token(string: str) -> bool: + return bool(string) and TOKEN >= set(string) + + def is_quoted(string: str) -> bool: + return string[0] == string[-1] == '"' + + def is_rfc5987(string: str) -> bool: + return is_token(string) and string.count("'") == 2 + + def is_extended_param(string: str) -> bool: + return string.endswith("*") + + def is_continuous_param(string: str) -> bool: + pos = string.find("*") + 1 + if not pos: + return False + substring = string[pos:-1] if string.endswith("*") else string[pos:] + return substring.isdigit() + + def unescape(text: str, *, chars: str = "".join(map(re.escape, CHAR))) -> str: + return re.sub(f"\\\\([{chars}])", "\\1", text) + + if not header: + return None, {} + + disptype, *parts = header.split(";") + if not is_token(disptype): + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + params: Dict[str, str] = {} + while parts: + item = parts.pop(0) + + if "=" not in item: + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + key, value = item.split("=", 1) + key = key.lower().strip() + value = value.lstrip() + + if key in params: + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + if not is_token(key): + warnings.warn(BadContentDispositionParam(item)) + continue + + elif is_continuous_param(key): + if is_quoted(value): + value = unescape(value[1:-1]) + elif not is_token(value): + warnings.warn(BadContentDispositionParam(item)) + continue + + elif is_extended_param(key): + if is_rfc5987(value): + encoding, _, value = value.split("'", 2) + encoding = encoding or "utf-8" + else: + warnings.warn(BadContentDispositionParam(item)) + continue + + try: + value = unquote(value, encoding, "strict") + except UnicodeDecodeError: # pragma: nocover + warnings.warn(BadContentDispositionParam(item)) + continue + + else: + failed = True + if is_quoted(value): + failed = False + value = unescape(value[1:-1].lstrip("\\/")) + elif is_token(value): + failed = False + elif parts: + # maybe just ; in filename, in any case this is just + # one case fix, for proper fix we need to redesign parser + _value = f"{value};{parts[0]}" + if is_quoted(_value): + parts.pop(0) + value = unescape(_value[1:-1].lstrip("\\/")) + failed = False + + if failed: + warnings.warn(BadContentDispositionHeader(header)) + return None, {} + + params[key] = value + + return disptype.lower(), params + + +def content_disposition_filename( + params: Mapping[str, str], name: str = "filename" +) -> Optional[str]: + name_suf = "%s*" % name + if not params: + return None + elif name_suf in params: + return params[name_suf] + elif name in params: + return params[name] + else: + parts = [] + fnparams = sorted( + (key, value) for key, value in params.items() if key.startswith(name_suf) + ) + for num, (key, value) in enumerate(fnparams): + _, tail = key.split("*", 1) + if tail.endswith("*"): + tail = tail[:-1] + if tail == str(num): + parts.append(value) + else: + break + if not parts: + return None + value = "".join(parts) + if "'" in value: + encoding, _, value = value.split("'", 2) + encoding = encoding or "utf-8" + return unquote(value, encoding, "strict") + return value + + +class MultipartResponseWrapper: + """Wrapper around the MultipartReader. + + It takes care about + underlying connection and close it when it needs in. + """ + + def __init__( + self, + resp: "ClientResponse", + stream: "MultipartReader", + ) -> None: + self.resp = resp + self.stream = stream + + def __aiter__(self) -> "MultipartResponseWrapper": + return self + + async def __anext__( + self, + ) -> Union["MultipartReader", "BodyPartReader"]: + part = await self.next() + if part is None: + raise StopAsyncIteration + return part + + def at_eof(self) -> bool: + """Returns True when all response data had been read.""" + return self.resp.content.at_eof() + + async def next( + self, + ) -> Optional[Union["MultipartReader", "BodyPartReader"]]: + """Emits next multipart reader object.""" + item = await self.stream.next() + if self.stream.at_eof(): + await self.release() + return item + + async def release(self) -> None: + """Release the connection gracefully. + + All remaining content is read to the void. + """ + await self.resp.release() + + +class BodyPartReader: + """Multipart reader for single body part.""" + + chunk_size = 8192 + + def __init__( + self, + boundary: bytes, + headers: "CIMultiDictProxy[str]", + content: StreamReader, + *, + subtype: str = "mixed", + default_charset: Optional[str] = None, + ) -> None: + self.headers = headers + self._boundary = boundary + self._boundary_len = len(boundary) + 2 # Boundary + \r\n + self._content = content + self._default_charset = default_charset + self._at_eof = False + self._is_form_data = subtype == "form-data" + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8 + length = None if self._is_form_data else self.headers.get(CONTENT_LENGTH, None) + self._length = int(length) if length is not None else None + self._read_bytes = 0 + self._unread: Deque[bytes] = deque() + self._prev_chunk: Optional[bytes] = None + self._content_eof = 0 + self._cache: Dict[str, Any] = {} + + def __aiter__(self: Self) -> Self: + return self + + async def __anext__(self) -> bytes: + part = await self.next() + if part is None: + raise StopAsyncIteration + return part + + async def next(self) -> Optional[bytes]: + item = await self.read() + if not item: + return None + return item + + async def read(self, *, decode: bool = False) -> bytes: + """Reads body part data. + + decode: Decodes data following by encoding + method from Content-Encoding header. If it missed + data remains untouched + """ + if self._at_eof: + return b"" + data = bytearray() + while not self._at_eof: + data.extend(await self.read_chunk(self.chunk_size)) + if decode: + return self.decode(data) + return data + + async def read_chunk(self, size: int = chunk_size) -> bytes: + """Reads body part content chunk of the specified size. + + size: chunk size + """ + if self._at_eof: + return b"" + if self._length: + chunk = await self._read_chunk_from_length(size) + else: + chunk = await self._read_chunk_from_stream(size) + + # For the case of base64 data, we must read a fragment of size with a + # remainder of 0 by dividing by 4 for string without symbols \n or \r + encoding = self.headers.get(CONTENT_TRANSFER_ENCODING) + if encoding and encoding.lower() == "base64": + stripped_chunk = b"".join(chunk.split()) + remainder = len(stripped_chunk) % 4 + + while remainder != 0 and not self.at_eof(): + over_chunk_size = 4 - remainder + over_chunk = b"" + + if self._prev_chunk: + over_chunk = self._prev_chunk[:over_chunk_size] + self._prev_chunk = self._prev_chunk[len(over_chunk) :] + + if len(over_chunk) != over_chunk_size: + over_chunk += await self._content.read(4 - len(over_chunk)) + + if not over_chunk: + self._at_eof = True + + stripped_chunk += b"".join(over_chunk.split()) + chunk += over_chunk + remainder = len(stripped_chunk) % 4 + + self._read_bytes += len(chunk) + if self._read_bytes == self._length: + self._at_eof = True + if self._at_eof: + clrf = await self._content.readline() + assert ( + b"\r\n" == clrf + ), "reader did not read all the data or it is malformed" + return chunk + + async def _read_chunk_from_length(self, size: int) -> bytes: + # Reads body part content chunk of the specified size. + # The body part must has Content-Length header with proper value. + assert self._length is not None, "Content-Length required for chunked read" + chunk_size = min(size, self._length - self._read_bytes) + chunk = await self._content.read(chunk_size) + if self._content.at_eof(): + self._at_eof = True + return chunk + + async def _read_chunk_from_stream(self, size: int) -> bytes: + # Reads content chunk of body part with unknown length. + # The Content-Length header for body part is not necessary. + assert ( + size >= self._boundary_len + ), "Chunk size must be greater or equal than boundary length + 2" + first_chunk = self._prev_chunk is None + if first_chunk: + self._prev_chunk = await self._content.read(size) + + chunk = b"" + # content.read() may return less than size, so we need to loop to ensure + # we have enough data to detect the boundary. + while len(chunk) < self._boundary_len: + chunk += await self._content.read(size) + self._content_eof += int(self._content.at_eof()) + assert self._content_eof < 3, "Reading after EOF" + if self._content_eof: + break + if len(chunk) > size: + self._content.unread_data(chunk[size:]) + chunk = chunk[:size] + + assert self._prev_chunk is not None + window = self._prev_chunk + chunk + sub = b"\r\n" + self._boundary + if first_chunk: + idx = window.find(sub) + else: + idx = window.find(sub, max(0, len(self._prev_chunk) - len(sub))) + if idx >= 0: + # pushing boundary back to content + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", category=DeprecationWarning) + self._content.unread_data(window[idx:]) + if size > idx: + self._prev_chunk = self._prev_chunk[:idx] + chunk = window[len(self._prev_chunk) : idx] + if not chunk: + self._at_eof = True + result = self._prev_chunk + self._prev_chunk = chunk + return result + + async def readline(self) -> bytes: + """Reads body part by line by line.""" + if self._at_eof: + return b"" + + if self._unread: + line = self._unread.popleft() + else: + line = await self._content.readline() + + if line.startswith(self._boundary): + # the very last boundary may not come with \r\n, + # so set single rules for everyone + sline = line.rstrip(b"\r\n") + boundary = self._boundary + last_boundary = self._boundary + b"--" + # ensure that we read exactly the boundary, not something alike + if sline == boundary or sline == last_boundary: + self._at_eof = True + self._unread.append(line) + return b"" + else: + next_line = await self._content.readline() + if next_line.startswith(self._boundary): + line = line[:-2] # strip CRLF but only once + self._unread.append(next_line) + + return line + + async def release(self) -> None: + """Like read(), but reads all the data to the void.""" + if self._at_eof: + return + while not self._at_eof: + await self.read_chunk(self.chunk_size) + + async def text(self, *, encoding: Optional[str] = None) -> str: + """Like read(), but assumes that body part contains text data.""" + data = await self.read(decode=True) + # see https://www.w3.org/TR/html5/forms.html#multipart/form-data-encoding-algorithm + # and https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#dom-xmlhttprequest-send + encoding = encoding or self.get_charset(default="utf-8") + return data.decode(encoding) + + async def json(self, *, encoding: Optional[str] = None) -> Optional[Dict[str, Any]]: + """Like read(), but assumes that body parts contains JSON data.""" + data = await self.read(decode=True) + if not data: + return None + encoding = encoding or self.get_charset(default="utf-8") + return cast(Dict[str, Any], json.loads(data.decode(encoding))) + + async def form(self, *, encoding: Optional[str] = None) -> List[Tuple[str, str]]: + """Like read(), but assumes that body parts contain form urlencoded data.""" + data = await self.read(decode=True) + if not data: + return [] + if encoding is not None: + real_encoding = encoding + else: + real_encoding = self.get_charset(default="utf-8") + try: + decoded_data = data.rstrip().decode(real_encoding) + except UnicodeDecodeError: + raise ValueError("data cannot be decoded with %s encoding" % real_encoding) + + return parse_qsl( + decoded_data, + keep_blank_values=True, + encoding=real_encoding, + ) + + def at_eof(self) -> bool: + """Returns True if the boundary was reached or False otherwise.""" + return self._at_eof + + def decode(self, data: bytes) -> bytes: + """Decodes data. + + Decoding is done according the specified Content-Encoding + or Content-Transfer-Encoding headers value. + """ + if CONTENT_TRANSFER_ENCODING in self.headers: + data = self._decode_content_transfer(data) + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8 + if not self._is_form_data and CONTENT_ENCODING in self.headers: + return self._decode_content(data) + return data + + def _decode_content(self, data: bytes) -> bytes: + encoding = self.headers.get(CONTENT_ENCODING, "").lower() + if encoding == "identity": + return data + if encoding in {"deflate", "gzip"}: + return ZLibDecompressor( + encoding=encoding, + suppress_deflate_header=True, + ).decompress_sync(data) + + raise RuntimeError(f"unknown content encoding: {encoding}") + + def _decode_content_transfer(self, data: bytes) -> bytes: + encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() + + if encoding == "base64": + return base64.b64decode(data) + elif encoding == "quoted-printable": + return binascii.a2b_qp(data) + elif encoding in ("binary", "8bit", "7bit"): + return data + else: + raise RuntimeError(f"unknown content transfer encoding: {encoding}") + + def get_charset(self, default: str) -> str: + """Returns charset parameter from Content-Type header or default.""" + ctype = self.headers.get(CONTENT_TYPE, "") + mimetype = parse_mimetype(ctype) + return mimetype.parameters.get("charset", self._default_charset or default) + + @reify + def name(self) -> Optional[str]: + """Returns name specified in Content-Disposition header. + + If the header is missing or malformed, returns None. + """ + _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) + return content_disposition_filename(params, "name") + + @reify + def filename(self) -> Optional[str]: + """Returns filename specified in Content-Disposition header. + + Returns None if the header is missing or malformed. + """ + _, params = parse_content_disposition(self.headers.get(CONTENT_DISPOSITION)) + return content_disposition_filename(params, "filename") + + +@payload_type(BodyPartReader, order=Order.try_first) +class BodyPartReaderPayload(Payload): + _value: BodyPartReader + # _autoclose = False (inherited) - Streaming reader that may have resources + + def __init__(self, value: BodyPartReader, *args: Any, **kwargs: Any) -> None: + super().__init__(value, *args, **kwargs) + + params: Dict[str, str] = {} + if value.name is not None: + params["name"] = value.name + if value.filename is not None: + params["filename"] = value.filename + + if params: + self.set_content_disposition("attachment", True, **params) + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + raise TypeError("Unable to decode.") + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """Raises TypeError as body parts should be consumed via write(). + + This is intentional: BodyPartReader payloads are designed for streaming + large data (potentially gigabytes) and must be consumed only once via + the write() method to avoid memory exhaustion. They cannot be buffered + in memory for reuse. + """ + raise TypeError("Unable to read body part as bytes. Use write() to consume.") + + async def write(self, writer: Any) -> None: + field = self._value + chunk = await field.read_chunk(size=2**16) + while chunk: + await writer.write(field.decode(chunk)) + chunk = await field.read_chunk(size=2**16) + + +class MultipartReader: + """Multipart body reader.""" + + #: Response wrapper, used when multipart readers constructs from response. + response_wrapper_cls = MultipartResponseWrapper + #: Multipart reader class, used to handle multipart/* body parts. + #: None points to type(self) + multipart_reader_cls: Optional[Type["MultipartReader"]] = None + #: Body part reader class for non multipart/* content types. + part_reader_cls = BodyPartReader + + def __init__(self, headers: Mapping[str, str], content: StreamReader) -> None: + self._mimetype = parse_mimetype(headers[CONTENT_TYPE]) + assert self._mimetype.type == "multipart", "multipart/* content type expected" + if "boundary" not in self._mimetype.parameters: + raise ValueError( + "boundary missed for Content-Type: %s" % headers[CONTENT_TYPE] + ) + + self.headers = headers + self._boundary = ("--" + self._get_boundary()).encode() + self._content = content + self._default_charset: Optional[str] = None + self._last_part: Optional[Union["MultipartReader", BodyPartReader]] = None + self._at_eof = False + self._at_bof = True + self._unread: List[bytes] = [] + + def __aiter__(self: Self) -> Self: + return self + + async def __anext__( + self, + ) -> Optional[Union["MultipartReader", BodyPartReader]]: + part = await self.next() + if part is None: + raise StopAsyncIteration + return part + + @classmethod + def from_response( + cls, + response: "ClientResponse", + ) -> MultipartResponseWrapper: + """Constructs reader instance from HTTP response. + + :param response: :class:`~aiohttp.client.ClientResponse` instance + """ + obj = cls.response_wrapper_cls( + response, cls(response.headers, response.content) + ) + return obj + + def at_eof(self) -> bool: + """Returns True if the final boundary was reached, false otherwise.""" + return self._at_eof + + async def next( + self, + ) -> Optional[Union["MultipartReader", BodyPartReader]]: + """Emits the next multipart body part.""" + # So, if we're at BOF, we need to skip till the boundary. + if self._at_eof: + return None + await self._maybe_release_last_part() + if self._at_bof: + await self._read_until_first_boundary() + self._at_bof = False + else: + await self._read_boundary() + if self._at_eof: # we just read the last boundary, nothing to do there + return None + + part = await self.fetch_next_part() + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.6 + if ( + self._last_part is None + and self._mimetype.subtype == "form-data" + and isinstance(part, BodyPartReader) + ): + _, params = parse_content_disposition(part.headers.get(CONTENT_DISPOSITION)) + if params.get("name") == "_charset_": + # Longest encoding in https://encoding.spec.whatwg.org/encodings.json + # is 19 characters, so 32 should be more than enough for any valid encoding. + charset = await part.read_chunk(32) + if len(charset) > 31: + raise RuntimeError("Invalid default charset") + self._default_charset = charset.strip().decode() + part = await self.fetch_next_part() + self._last_part = part + return self._last_part + + async def release(self) -> None: + """Reads all the body parts to the void till the final boundary.""" + while not self._at_eof: + item = await self.next() + if item is None: + break + await item.release() + + async def fetch_next_part( + self, + ) -> Union["MultipartReader", BodyPartReader]: + """Returns the next body part reader.""" + headers = await self._read_headers() + return self._get_part_reader(headers) + + def _get_part_reader( + self, + headers: "CIMultiDictProxy[str]", + ) -> Union["MultipartReader", BodyPartReader]: + """Dispatches the response by the `Content-Type` header. + + Returns a suitable reader instance. + + :param dict headers: Response headers + """ + ctype = headers.get(CONTENT_TYPE, "") + mimetype = parse_mimetype(ctype) + + if mimetype.type == "multipart": + if self.multipart_reader_cls is None: + return type(self)(headers, self._content) + return self.multipart_reader_cls(headers, self._content) + else: + return self.part_reader_cls( + self._boundary, + headers, + self._content, + subtype=self._mimetype.subtype, + default_charset=self._default_charset, + ) + + def _get_boundary(self) -> str: + boundary = self._mimetype.parameters["boundary"] + if len(boundary) > 70: + raise ValueError("boundary %r is too long (70 chars max)" % boundary) + + return boundary + + async def _readline(self) -> bytes: + if self._unread: + return self._unread.pop() + return await self._content.readline() + + async def _read_until_first_boundary(self) -> None: + while True: + chunk = await self._readline() + if chunk == b"": + raise ValueError( + "Could not find starting boundary %r" % (self._boundary) + ) + chunk = chunk.rstrip() + if chunk == self._boundary: + return + elif chunk == self._boundary + b"--": + self._at_eof = True + return + + async def _read_boundary(self) -> None: + chunk = (await self._readline()).rstrip() + if chunk == self._boundary: + pass + elif chunk == self._boundary + b"--": + self._at_eof = True + epilogue = await self._readline() + next_line = await self._readline() + + # the epilogue is expected and then either the end of input or the + # parent multipart boundary, if the parent boundary is found then + # it should be marked as unread and handed to the parent for + # processing + if next_line[:2] == b"--": + self._unread.append(next_line) + # otherwise the request is likely missing an epilogue and both + # lines should be passed to the parent for processing + # (this handles the old behavior gracefully) + else: + self._unread.extend([next_line, epilogue]) + else: + raise ValueError(f"Invalid boundary {chunk!r}, expected {self._boundary!r}") + + async def _read_headers(self) -> "CIMultiDictProxy[str]": + lines = [] + while True: + chunk = await self._content.readline() + chunk = chunk.strip() + lines.append(chunk) + if not chunk: + break + parser = HeadersParser() + headers, raw_headers = parser.parse_headers(lines) + return headers + + async def _maybe_release_last_part(self) -> None: + """Ensures that the last read body part is read completely.""" + if self._last_part is not None: + if not self._last_part.at_eof(): + await self._last_part.release() + self._unread.extend(self._last_part._unread) + self._last_part = None + + +_Part = Tuple[Payload, str, str] + + +class MultipartWriter(Payload): + """Multipart body writer.""" + + _value: None + # _consumed = False (inherited) - Can be encoded multiple times + _autoclose = True # No file handles, just collects parts in memory + + def __init__(self, subtype: str = "mixed", boundary: Optional[str] = None) -> None: + boundary = boundary if boundary is not None else uuid.uuid4().hex + # The underlying Payload API demands a str (utf-8), not bytes, + # so we need to ensure we don't lose anything during conversion. + # As a result, require the boundary to be ASCII only. + # In both situations. + + try: + self._boundary = boundary.encode("ascii") + except UnicodeEncodeError: + raise ValueError("boundary should contain ASCII only chars") from None + ctype = f"multipart/{subtype}; boundary={self._boundary_value}" + + super().__init__(None, content_type=ctype) + + self._parts: List[_Part] = [] + self._is_form_data = subtype == "form-data" + + def __enter__(self) -> "MultipartWriter": + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> None: + pass + + def __iter__(self) -> Iterator[_Part]: + return iter(self._parts) + + def __len__(self) -> int: + return len(self._parts) + + def __bool__(self) -> bool: + return True + + _valid_tchar_regex = re.compile(rb"\A[!#$%&'*+\-.^_`|~\w]+\Z") + _invalid_qdtext_char_regex = re.compile(rb"[\x00-\x08\x0A-\x1F\x7F]") + + @property + def _boundary_value(self) -> str: + """Wrap boundary parameter value in quotes, if necessary. + + Reads self.boundary and returns a unicode string. + """ + # Refer to RFCs 7231, 7230, 5234. + # + # parameter = token "=" ( token / quoted-string ) + # token = 1*tchar + # quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + # qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + # obs-text = %x80-FF + # quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + # tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + # / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + # / DIGIT / ALPHA + # ; any VCHAR, except delimiters + # VCHAR = %x21-7E + value = self._boundary + if re.match(self._valid_tchar_regex, value): + return value.decode("ascii") # cannot fail + + if re.search(self._invalid_qdtext_char_regex, value): + raise ValueError("boundary value contains invalid characters") + + # escape %x5C and %x22 + quoted_value_content = value.replace(b"\\", b"\\\\") + quoted_value_content = quoted_value_content.replace(b'"', b'\\"') + + return '"' + quoted_value_content.decode("ascii") + '"' + + @property + def boundary(self) -> str: + return self._boundary.decode("ascii") + + def append(self, obj: Any, headers: Optional[Mapping[str, str]] = None) -> Payload: + if headers is None: + headers = CIMultiDict() + + if isinstance(obj, Payload): + obj.headers.update(headers) + return self.append_payload(obj) + else: + try: + payload = get_payload(obj, headers=headers) + except LookupError: + raise TypeError("Cannot create payload from %r" % obj) + else: + return self.append_payload(payload) + + def append_payload(self, payload: Payload) -> Payload: + """Adds a new body part to multipart writer.""" + encoding: Optional[str] = None + te_encoding: Optional[str] = None + if self._is_form_data: + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.7 + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.8 + assert ( + not {CONTENT_ENCODING, CONTENT_LENGTH, CONTENT_TRANSFER_ENCODING} + & payload.headers.keys() + ) + # Set default Content-Disposition in case user doesn't create one + if CONTENT_DISPOSITION not in payload.headers: + name = f"section-{len(self._parts)}" + payload.set_content_disposition("form-data", name=name) + else: + # compression + encoding = payload.headers.get(CONTENT_ENCODING, "").lower() + if encoding and encoding not in ("deflate", "gzip", "identity"): + raise RuntimeError(f"unknown content encoding: {encoding}") + if encoding == "identity": + encoding = None + + # te encoding + te_encoding = payload.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() + if te_encoding not in ("", "base64", "quoted-printable", "binary"): + raise RuntimeError(f"unknown content transfer encoding: {te_encoding}") + if te_encoding == "binary": + te_encoding = None + + # size + size = payload.size + if size is not None and not (encoding or te_encoding): + payload.headers[CONTENT_LENGTH] = str(size) + + self._parts.append((payload, encoding, te_encoding)) # type: ignore[arg-type] + return payload + + def append_json( + self, obj: Any, headers: Optional[Mapping[str, str]] = None + ) -> Payload: + """Helper to append JSON part.""" + if headers is None: + headers = CIMultiDict() + + return self.append_payload(JsonPayload(obj, headers=headers)) + + def append_form( + self, + obj: Union[Sequence[Tuple[str, str]], Mapping[str, str]], + headers: Optional[Mapping[str, str]] = None, + ) -> Payload: + """Helper to append form urlencoded part.""" + assert isinstance(obj, (Sequence, Mapping)) + + if headers is None: + headers = CIMultiDict() + + if isinstance(obj, Mapping): + obj = list(obj.items()) + data = urlencode(obj, doseq=True) + + return self.append_payload( + StringPayload( + data, headers=headers, content_type="application/x-www-form-urlencoded" + ) + ) + + @property + def size(self) -> Optional[int]: + """Size of the payload.""" + total = 0 + for part, encoding, te_encoding in self._parts: + if encoding or te_encoding or part.size is None: + return None + + total += int( + 2 + + len(self._boundary) + + 2 + + part.size # b'--'+self._boundary+b'\r\n' + + len(part._binary_headers) + + 2 # b'\r\n' + ) + + total += 2 + len(self._boundary) + 4 # b'--'+self._boundary+b'--\r\n' + return total + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + """Return string representation of the multipart data. + + WARNING: This method may do blocking I/O if parts contain file payloads. + It should not be called in the event loop. Use as_bytes().decode() instead. + """ + return "".join( + "--" + + self.boundary + + "\r\n" + + part._binary_headers.decode(encoding, errors) + + part.decode() + for part, _e, _te in self._parts + ) + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """Return bytes representation of the multipart data. + + This method is async-safe and calls as_bytes on underlying payloads. + """ + parts: List[bytes] = [] + + # Process each part + for part, _e, _te in self._parts: + # Add boundary + parts.append(b"--" + self._boundary + b"\r\n") + + # Add headers + parts.append(part._binary_headers) + + # Add payload content using as_bytes for async safety + part_bytes = await part.as_bytes(encoding, errors) + parts.append(part_bytes) + + # Add trailing CRLF + parts.append(b"\r\n") + + # Add closing boundary + parts.append(b"--" + self._boundary + b"--\r\n") + + return b"".join(parts) + + async def write(self, writer: Any, close_boundary: bool = True) -> None: + """Write body.""" + for part, encoding, te_encoding in self._parts: + if self._is_form_data: + # https://datatracker.ietf.org/doc/html/rfc7578#section-4.2 + assert CONTENT_DISPOSITION in part.headers + assert "name=" in part.headers[CONTENT_DISPOSITION] + + await writer.write(b"--" + self._boundary + b"\r\n") + await writer.write(part._binary_headers) + + if encoding or te_encoding: + w = MultipartPayloadWriter(writer) + if encoding: + w.enable_compression(encoding) + if te_encoding: + w.enable_encoding(te_encoding) + await part.write(w) # type: ignore[arg-type] + await w.write_eof() + else: + await part.write(writer) + + await writer.write(b"\r\n") + + if close_boundary: + await writer.write(b"--" + self._boundary + b"--\r\n") + + async def close(self) -> None: + """ + Close all part payloads that need explicit closing. + + IMPORTANT: This method must not await anything that might not finish + immediately, as it may be called during cleanup/cancellation. Schedule + any long-running operations without awaiting them. + """ + if self._consumed: + return + self._consumed = True + + # Close all parts that need explicit closing + # We catch and log exceptions to ensure all parts get a chance to close + # we do not use asyncio.gather() here because we are not allowed + # to suspend given we may be called during cleanup + for idx, (part, _, _) in enumerate(self._parts): + if not part.autoclose and not part.consumed: + try: + await part.close() + except Exception as exc: + internal_logger.error( + "Failed to close multipart part %d: %s", idx, exc, exc_info=True + ) + + +class MultipartPayloadWriter: + def __init__(self, writer: Any) -> None: + self._writer = writer + self._encoding: Optional[str] = None + self._compress: Optional[ZLibCompressor] = None + self._encoding_buffer: Optional[bytearray] = None + + def enable_encoding(self, encoding: str) -> None: + if encoding == "base64": + self._encoding = encoding + self._encoding_buffer = bytearray() + elif encoding == "quoted-printable": + self._encoding = "quoted-printable" + + def enable_compression( + self, encoding: str = "deflate", strategy: Optional[int] = None + ) -> None: + self._compress = ZLibCompressor( + encoding=encoding, + suppress_deflate_header=True, + strategy=strategy, + ) + + async def write_eof(self) -> None: + if self._compress is not None: + chunk = self._compress.flush() + if chunk: + self._compress = None + await self.write(chunk) + + if self._encoding == "base64": + if self._encoding_buffer: + await self._writer.write(base64.b64encode(self._encoding_buffer)) + + async def write(self, chunk: bytes) -> None: + if self._compress is not None: + if chunk: + chunk = await self._compress.compress(chunk) + if not chunk: + return + + if self._encoding == "base64": + buf = self._encoding_buffer + assert buf is not None + buf.extend(chunk) + + if buf: + div, mod = divmod(len(buf), 3) + enc_chunk, self._encoding_buffer = (buf[: div * 3], buf[div * 3 :]) + if enc_chunk: + b64chunk = base64.b64encode(enc_chunk) + await self._writer.write(b64chunk) + elif self._encoding == "quoted-printable": + await self._writer.write(binascii.b2a_qp(chunk)) + else: + await self._writer.write(chunk) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/payload.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/payload.py new file mode 100644 index 0000000000000000000000000000000000000000..3affa710b63bc47a2d170c4ffd3dbff4612da4cc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/payload.py @@ -0,0 +1,1124 @@ +import asyncio +import enum +import io +import json +import mimetypes +import os +import sys +import warnings +from abc import ABC, abstractmethod +from collections.abc import Iterable +from itertools import chain +from typing import ( + IO, + TYPE_CHECKING, + Any, + Dict, + Final, + List, + Optional, + Set, + TextIO, + Tuple, + Type, + Union, +) + +from multidict import CIMultiDict + +from . import hdrs +from .abc import AbstractStreamWriter +from .helpers import ( + _SENTINEL, + content_disposition_header, + guess_filename, + parse_mimetype, + sentinel, +) +from .streams import StreamReader +from .typedefs import JSONEncoder, _CIMultiDict + +__all__ = ( + "PAYLOAD_REGISTRY", + "get_payload", + "payload_type", + "Payload", + "BytesPayload", + "StringPayload", + "IOBasePayload", + "BytesIOPayload", + "BufferedReaderPayload", + "TextIOPayload", + "StringIOPayload", + "JsonPayload", + "AsyncIterablePayload", +) + +TOO_LARGE_BYTES_BODY: Final[int] = 2**20 # 1 MB +READ_SIZE: Final[int] = 2**16 # 64 KB +_CLOSE_FUTURES: Set[asyncio.Future[None]] = set() + + +class LookupError(Exception): + """Raised when no payload factory is found for the given data type.""" + + +class Order(str, enum.Enum): + normal = "normal" + try_first = "try_first" + try_last = "try_last" + + +def get_payload(data: Any, *args: Any, **kwargs: Any) -> "Payload": + return PAYLOAD_REGISTRY.get(data, *args, **kwargs) + + +def register_payload( + factory: Type["Payload"], type: Any, *, order: Order = Order.normal +) -> None: + PAYLOAD_REGISTRY.register(factory, type, order=order) + + +class payload_type: + def __init__(self, type: Any, *, order: Order = Order.normal) -> None: + self.type = type + self.order = order + + def __call__(self, factory: Type["Payload"]) -> Type["Payload"]: + register_payload(factory, self.type, order=self.order) + return factory + + +PayloadType = Type["Payload"] +_PayloadRegistryItem = Tuple[PayloadType, Any] + + +class PayloadRegistry: + """Payload registry. + + note: we need zope.interface for more efficient adapter search + """ + + __slots__ = ("_first", "_normal", "_last", "_normal_lookup") + + def __init__(self) -> None: + self._first: List[_PayloadRegistryItem] = [] + self._normal: List[_PayloadRegistryItem] = [] + self._last: List[_PayloadRegistryItem] = [] + self._normal_lookup: Dict[Any, PayloadType] = {} + + def get( + self, + data: Any, + *args: Any, + _CHAIN: "Type[chain[_PayloadRegistryItem]]" = chain, + **kwargs: Any, + ) -> "Payload": + if self._first: + for factory, type_ in self._first: + if isinstance(data, type_): + return factory(data, *args, **kwargs) + # Try the fast lookup first + if lookup_factory := self._normal_lookup.get(type(data)): + return lookup_factory(data, *args, **kwargs) + # Bail early if its already a Payload + if isinstance(data, Payload): + return data + # Fallback to the slower linear search + for factory, type_ in _CHAIN(self._normal, self._last): + if isinstance(data, type_): + return factory(data, *args, **kwargs) + raise LookupError() + + def register( + self, factory: PayloadType, type: Any, *, order: Order = Order.normal + ) -> None: + if order is Order.try_first: + self._first.append((factory, type)) + elif order is Order.normal: + self._normal.append((factory, type)) + if isinstance(type, Iterable): + for t in type: + self._normal_lookup[t] = factory + else: + self._normal_lookup[type] = factory + elif order is Order.try_last: + self._last.append((factory, type)) + else: + raise ValueError(f"Unsupported order {order!r}") + + +class Payload(ABC): + + _default_content_type: str = "application/octet-stream" + _size: Optional[int] = None + _consumed: bool = False # Default: payload has not been consumed yet + _autoclose: bool = False # Default: assume resource needs explicit closing + + def __init__( + self, + value: Any, + headers: Optional[ + Union[_CIMultiDict, Dict[str, str], Iterable[Tuple[str, str]]] + ] = None, + content_type: Union[str, None, _SENTINEL] = sentinel, + filename: Optional[str] = None, + encoding: Optional[str] = None, + **kwargs: Any, + ) -> None: + self._encoding = encoding + self._filename = filename + self._headers: _CIMultiDict = CIMultiDict() + self._value = value + if content_type is not sentinel and content_type is not None: + self._headers[hdrs.CONTENT_TYPE] = content_type + elif self._filename is not None: + if sys.version_info >= (3, 13): + guesser = mimetypes.guess_file_type + else: + guesser = mimetypes.guess_type + content_type = guesser(self._filename)[0] + if content_type is None: + content_type = self._default_content_type + self._headers[hdrs.CONTENT_TYPE] = content_type + else: + self._headers[hdrs.CONTENT_TYPE] = self._default_content_type + if headers: + self._headers.update(headers) + + @property + def size(self) -> Optional[int]: + """Size of the payload in bytes. + + Returns the number of bytes that will be transmitted when the payload + is written. For string payloads, this is the size after encoding to bytes, + not the length of the string. + """ + return self._size + + @property + def filename(self) -> Optional[str]: + """Filename of the payload.""" + return self._filename + + @property + def headers(self) -> _CIMultiDict: + """Custom item headers""" + return self._headers + + @property + def _binary_headers(self) -> bytes: + return ( + "".join([k + ": " + v + "\r\n" for k, v in self.headers.items()]).encode( + "utf-8" + ) + + b"\r\n" + ) + + @property + def encoding(self) -> Optional[str]: + """Payload encoding""" + return self._encoding + + @property + def content_type(self) -> str: + """Content type""" + return self._headers[hdrs.CONTENT_TYPE] + + @property + def consumed(self) -> bool: + """Whether the payload has been consumed and cannot be reused.""" + return self._consumed + + @property + def autoclose(self) -> bool: + """ + Whether the payload can close itself automatically. + + Returns True if the payload has no file handles or resources that need + explicit closing. If False, callers must await close() to release resources. + """ + return self._autoclose + + def set_content_disposition( + self, + disptype: str, + quote_fields: bool = True, + _charset: str = "utf-8", + **params: Any, + ) -> None: + """Sets ``Content-Disposition`` header.""" + self._headers[hdrs.CONTENT_DISPOSITION] = content_disposition_header( + disptype, quote_fields=quote_fields, _charset=_charset, **params + ) + + @abstractmethod + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + """ + Return string representation of the value. + + This is named decode() to allow compatibility with bytes objects. + """ + + @abstractmethod + async def write(self, writer: AbstractStreamWriter) -> None: + """ + Write payload to the writer stream. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + + This is a legacy method that writes the entire payload without length constraints. + + Important: + For new implementations, use write_with_length() instead of this method. + This method is maintained for backwards compatibility and will eventually + delegate to write_with_length(writer, None) in all implementations. + + All payload subclasses must override this method for backwards compatibility, + but new code should use write_with_length for more flexibility and control. + + """ + + # write_with_length is new in aiohttp 3.12 + # it should be overridden by subclasses + async def write_with_length( + self, writer: AbstractStreamWriter, content_length: Optional[int] + ) -> None: + """ + Write payload with a specific content length constraint. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + content_length: Maximum number of bytes to write (None for unlimited) + + This method allows writing payload content with a specific length constraint, + which is particularly useful for HTTP responses with Content-Length header. + + Note: + This is the base implementation that provides backwards compatibility + for subclasses that don't override this method. Specific payload types + should override this method to implement proper length-constrained writing. + + """ + # Backwards compatibility for subclasses that don't override this method + # and for the default implementation + await self.write(writer) + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """ + Return bytes representation of the value. + + This is a convenience method that calls decode() and encodes the result + to bytes using the specified encoding. + """ + # Use instance encoding if available, otherwise use parameter + actual_encoding = self._encoding or encoding + return self.decode(actual_encoding, errors).encode(actual_encoding) + + def _close(self) -> None: + """ + Async safe synchronous close operations for backwards compatibility. + + This method exists only for backwards compatibility with code that + needs to clean up payloads synchronously. In the future, we will + drop this method and only support the async close() method. + + WARNING: This method must be safe to call from within the event loop + without blocking. Subclasses should not perform any blocking I/O here. + + WARNING: This method must be called from within an event loop for + certain payload types (e.g., IOBasePayload). Calling it outside an + event loop may raise RuntimeError. + """ + # This is a no-op by default, but subclasses can override it + # for non-blocking cleanup operations. + + async def close(self) -> None: + """ + Close the payload if it holds any resources. + + IMPORTANT: This method must not await anything that might not finish + immediately, as it may be called during cleanup/cancellation. Schedule + any long-running operations without awaiting them. + + In the future, this will be the only close method supported. + """ + self._close() + + +class BytesPayload(Payload): + _value: bytes + # _consumed = False (inherited) - Bytes are immutable and can be reused + _autoclose = True # No file handle, just bytes in memory + + def __init__( + self, value: Union[bytes, bytearray, memoryview], *args: Any, **kwargs: Any + ) -> None: + if "content_type" not in kwargs: + kwargs["content_type"] = "application/octet-stream" + + super().__init__(value, *args, **kwargs) + + if isinstance(value, memoryview): + self._size = value.nbytes + elif isinstance(value, (bytes, bytearray)): + self._size = len(value) + else: + raise TypeError(f"value argument must be byte-ish, not {type(value)!r}") + + if self._size > TOO_LARGE_BYTES_BODY: + kwargs = {"source": self} + warnings.warn( + "Sending a large body directly with raw bytes might" + " lock the event loop. You should probably pass an " + "io.BytesIO object instead", + ResourceWarning, + **kwargs, + ) + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + return self._value.decode(encoding, errors) + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """ + Return bytes representation of the value. + + This method returns the raw bytes content of the payload. + It is equivalent to accessing the _value attribute directly. + """ + return self._value + + async def write(self, writer: AbstractStreamWriter) -> None: + """ + Write the entire bytes payload to the writer stream. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + + This method writes the entire bytes content without any length constraint. + + Note: + For new implementations that need length control, use write_with_length(). + This method is maintained for backwards compatibility and is equivalent + to write_with_length(writer, None). + + """ + await writer.write(self._value) + + async def write_with_length( + self, writer: AbstractStreamWriter, content_length: Optional[int] + ) -> None: + """ + Write bytes payload with a specific content length constraint. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + content_length: Maximum number of bytes to write (None for unlimited) + + This method writes either the entire byte sequence or a slice of it + up to the specified content_length. For BytesPayload, this operation + is performed efficiently using array slicing. + + """ + if content_length is not None: + await writer.write(self._value[:content_length]) + else: + await writer.write(self._value) + + +class StringPayload(BytesPayload): + def __init__( + self, + value: str, + *args: Any, + encoding: Optional[str] = None, + content_type: Optional[str] = None, + **kwargs: Any, + ) -> None: + + if encoding is None: + if content_type is None: + real_encoding = "utf-8" + content_type = "text/plain; charset=utf-8" + else: + mimetype = parse_mimetype(content_type) + real_encoding = mimetype.parameters.get("charset", "utf-8") + else: + if content_type is None: + content_type = "text/plain; charset=%s" % encoding + real_encoding = encoding + + super().__init__( + value.encode(real_encoding), + encoding=real_encoding, + content_type=content_type, + *args, + **kwargs, + ) + + +class StringIOPayload(StringPayload): + def __init__(self, value: IO[str], *args: Any, **kwargs: Any) -> None: + super().__init__(value.read(), *args, **kwargs) + + +class IOBasePayload(Payload): + _value: io.IOBase + # _consumed = False (inherited) - File can be re-read from the same position + _start_position: Optional[int] = None + # _autoclose = False (inherited) - Has file handle that needs explicit closing + + def __init__( + self, value: IO[Any], disposition: str = "attachment", *args: Any, **kwargs: Any + ) -> None: + if "filename" not in kwargs: + kwargs["filename"] = guess_filename(value) + + super().__init__(value, *args, **kwargs) + + if self._filename is not None and disposition is not None: + if hdrs.CONTENT_DISPOSITION not in self.headers: + self.set_content_disposition(disposition, filename=self._filename) + + def _set_or_restore_start_position(self) -> None: + """Set or restore the start position of the file-like object.""" + if self._start_position is None: + try: + self._start_position = self._value.tell() + except (OSError, AttributeError): + self._consumed = True # Cannot seek, mark as consumed + return + try: + self._value.seek(self._start_position) + except (OSError, AttributeError): + # Failed to seek back - mark as consumed since we've already read + self._consumed = True + + def _read_and_available_len( + self, remaining_content_len: Optional[int] + ) -> Tuple[Optional[int], bytes]: + """ + Read the file-like object and return both its total size and the first chunk. + + Args: + remaining_content_len: Optional limit on how many bytes to read in this operation. + If None, READ_SIZE will be used as the default chunk size. + + Returns: + A tuple containing: + - The total size of the remaining unread content (None if size cannot be determined) + - The first chunk of bytes read from the file object + + This method is optimized to perform both size calculation and initial read + in a single operation, which is executed in a single executor job to minimize + context switches and file operations when streaming content. + + """ + self._set_or_restore_start_position() + size = self.size # Call size only once since it does I/O + return size, self._value.read( + min(READ_SIZE, size or READ_SIZE, remaining_content_len or READ_SIZE) + ) + + def _read(self, remaining_content_len: Optional[int]) -> bytes: + """ + Read a chunk of data from the file-like object. + + Args: + remaining_content_len: Optional maximum number of bytes to read. + If None, READ_SIZE will be used as the default chunk size. + + Returns: + A chunk of bytes read from the file object, respecting the + remaining_content_len limit if specified. + + This method is used for subsequent reads during streaming after + the initial _read_and_available_len call has been made. + + """ + return self._value.read(remaining_content_len or READ_SIZE) # type: ignore[no-any-return] + + @property + def size(self) -> Optional[int]: + """ + Size of the payload in bytes. + + Returns the total size of the payload content from the initial position. + This ensures consistent Content-Length for requests, including 307/308 redirects + where the same payload instance is reused. + + Returns None if the size cannot be determined (e.g., for unseekable streams). + """ + try: + # Store the start position on first access. + # This is critical when the same payload instance is reused (e.g., 307/308 + # redirects). Without storing the initial position, after the payload is + # read once, the file position would be at EOF, which would cause the + # size calculation to return 0 (file_size - EOF position). + # By storing the start position, we ensure the size calculation always + # returns the correct total size for any subsequent use. + if self._start_position is None: + try: + self._start_position = self._value.tell() + except (OSError, AttributeError): + # Can't get position, can't determine size + return None + + # Return the total size from the start position + # This ensures Content-Length is correct even after reading + return os.fstat(self._value.fileno()).st_size - self._start_position + except (AttributeError, OSError): + return None + + async def write(self, writer: AbstractStreamWriter) -> None: + """ + Write the entire file-like payload to the writer stream. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + + This method writes the entire file content without any length constraint. + It delegates to write_with_length() with no length limit for implementation + consistency. + + Note: + For new implementations that need length control, use write_with_length() directly. + This method is maintained for backwards compatibility with existing code. + + """ + await self.write_with_length(writer, None) + + async def write_with_length( + self, writer: AbstractStreamWriter, content_length: Optional[int] + ) -> None: + """ + Write file-like payload with a specific content length constraint. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + content_length: Maximum number of bytes to write (None for unlimited) + + This method implements optimized streaming of file content with length constraints: + + 1. File reading is performed in a thread pool to avoid blocking the event loop + 2. Content is read and written in chunks to maintain memory efficiency + 3. Writing stops when either: + - All available file content has been written (when size is known) + - The specified content_length has been reached + 4. File resources are properly closed even if the operation is cancelled + + The implementation carefully handles both known-size and unknown-size payloads, + as well as constrained and unconstrained content lengths. + + """ + loop = asyncio.get_running_loop() + total_written_len = 0 + remaining_content_len = content_length + + # Get initial data and available length + available_len, chunk = await loop.run_in_executor( + None, self._read_and_available_len, remaining_content_len + ) + # Process data chunks until done + while chunk: + chunk_len = len(chunk) + + # Write data with or without length constraint + if remaining_content_len is None: + await writer.write(chunk) + else: + await writer.write(chunk[:remaining_content_len]) + remaining_content_len -= chunk_len + + total_written_len += chunk_len + + # Check if we're done writing + if self._should_stop_writing( + available_len, total_written_len, remaining_content_len + ): + return + + # Read next chunk + chunk = await loop.run_in_executor( + None, + self._read, + ( + min(READ_SIZE, remaining_content_len) + if remaining_content_len is not None + else READ_SIZE + ), + ) + + def _should_stop_writing( + self, + available_len: Optional[int], + total_written_len: int, + remaining_content_len: Optional[int], + ) -> bool: + """ + Determine if we should stop writing data. + + Args: + available_len: Known size of the payload if available (None if unknown) + total_written_len: Number of bytes already written + remaining_content_len: Remaining bytes to be written for content-length limited responses + + Returns: + True if we should stop writing data, based on either: + - Having written all available data (when size is known) + - Having written all requested content (when content-length is specified) + + """ + return (available_len is not None and total_written_len >= available_len) or ( + remaining_content_len is not None and remaining_content_len <= 0 + ) + + def _close(self) -> None: + """ + Async safe synchronous close operations for backwards compatibility. + + This method exists only for backwards + compatibility. Use the async close() method instead. + + WARNING: This method MUST be called from within an event loop. + Calling it outside an event loop will raise RuntimeError. + """ + # Skip if already consumed + if self._consumed: + return + self._consumed = True # Mark as consumed to prevent further writes + # Schedule file closing without awaiting to prevent cancellation issues + loop = asyncio.get_running_loop() + close_future = loop.run_in_executor(None, self._value.close) + # Hold a strong reference to the future to prevent it from being + # garbage collected before it completes. + _CLOSE_FUTURES.add(close_future) + close_future.add_done_callback(_CLOSE_FUTURES.remove) + + async def close(self) -> None: + """ + Close the payload if it holds any resources. + + IMPORTANT: This method must not await anything that might not finish + immediately, as it may be called during cleanup/cancellation. Schedule + any long-running operations without awaiting them. + """ + self._close() + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + """ + Return string representation of the value. + + WARNING: This method does blocking I/O and should not be called in the event loop. + """ + return self._read_all().decode(encoding, errors) + + def _read_all(self) -> bytes: + """Read the entire file-like object and return its content as bytes.""" + self._set_or_restore_start_position() + # Use readlines() to ensure we get all content + return b"".join(self._value.readlines()) + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """ + Return bytes representation of the value. + + This method reads the entire file content and returns it as bytes. + It is equivalent to reading the file-like object directly. + The file reading is performed in an executor to avoid blocking the event loop. + """ + loop = asyncio.get_running_loop() + return await loop.run_in_executor(None, self._read_all) + + +class TextIOPayload(IOBasePayload): + _value: io.TextIOBase + # _autoclose = False (inherited) - Has text file handle that needs explicit closing + + def __init__( + self, + value: TextIO, + *args: Any, + encoding: Optional[str] = None, + content_type: Optional[str] = None, + **kwargs: Any, + ) -> None: + + if encoding is None: + if content_type is None: + encoding = "utf-8" + content_type = "text/plain; charset=utf-8" + else: + mimetype = parse_mimetype(content_type) + encoding = mimetype.parameters.get("charset", "utf-8") + else: + if content_type is None: + content_type = "text/plain; charset=%s" % encoding + + super().__init__( + value, + content_type=content_type, + encoding=encoding, + *args, + **kwargs, + ) + + def _read_and_available_len( + self, remaining_content_len: Optional[int] + ) -> Tuple[Optional[int], bytes]: + """ + Read the text file-like object and return both its total size and the first chunk. + + Args: + remaining_content_len: Optional limit on how many bytes to read in this operation. + If None, READ_SIZE will be used as the default chunk size. + + Returns: + A tuple containing: + - The total size of the remaining unread content (None if size cannot be determined) + - The first chunk of bytes read from the file object, encoded using the payload's encoding + + This method is optimized to perform both size calculation and initial read + in a single operation, which is executed in a single executor job to minimize + context switches and file operations when streaming content. + + Note: + TextIOPayload handles encoding of the text content before writing it + to the stream. If no encoding is specified, UTF-8 is used as the default. + + """ + self._set_or_restore_start_position() + size = self.size + chunk = self._value.read( + min(READ_SIZE, size or READ_SIZE, remaining_content_len or READ_SIZE) + ) + return size, chunk.encode(self._encoding) if self._encoding else chunk.encode() + + def _read(self, remaining_content_len: Optional[int]) -> bytes: + """ + Read a chunk of data from the text file-like object. + + Args: + remaining_content_len: Optional maximum number of bytes to read. + If None, READ_SIZE will be used as the default chunk size. + + Returns: + A chunk of bytes read from the file object and encoded using the payload's + encoding. The data is automatically converted from text to bytes. + + This method is used for subsequent reads during streaming after + the initial _read_and_available_len call has been made. It properly + handles text encoding, converting the text content to bytes using + the specified encoding (or UTF-8 if none was provided). + + """ + chunk = self._value.read(remaining_content_len or READ_SIZE) + return chunk.encode(self._encoding) if self._encoding else chunk.encode() + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + """ + Return string representation of the value. + + WARNING: This method does blocking I/O and should not be called in the event loop. + """ + self._set_or_restore_start_position() + return self._value.read() + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """ + Return bytes representation of the value. + + This method reads the entire text file content and returns it as bytes. + It encodes the text content using the specified encoding. + The file reading is performed in an executor to avoid blocking the event loop. + """ + loop = asyncio.get_running_loop() + + # Use instance encoding if available, otherwise use parameter + actual_encoding = self._encoding or encoding + + def _read_and_encode() -> bytes: + self._set_or_restore_start_position() + # TextIO read() always returns the full content + return self._value.read().encode(actual_encoding, errors) + + return await loop.run_in_executor(None, _read_and_encode) + + +class BytesIOPayload(IOBasePayload): + _value: io.BytesIO + _size: int # Always initialized in __init__ + _autoclose = True # BytesIO is in-memory, safe to auto-close + + def __init__(self, value: io.BytesIO, *args: Any, **kwargs: Any) -> None: + super().__init__(value, *args, **kwargs) + # Calculate size once during initialization + self._size = len(self._value.getbuffer()) - self._value.tell() + + @property + def size(self) -> int: + """Size of the payload in bytes. + + Returns the number of bytes in the BytesIO buffer that will be transmitted. + This is calculated once during initialization for efficiency. + """ + return self._size + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + self._set_or_restore_start_position() + return self._value.read().decode(encoding, errors) + + async def write(self, writer: AbstractStreamWriter) -> None: + return await self.write_with_length(writer, None) + + async def write_with_length( + self, writer: AbstractStreamWriter, content_length: Optional[int] + ) -> None: + """ + Write BytesIO payload with a specific content length constraint. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + content_length: Maximum number of bytes to write (None for unlimited) + + This implementation is specifically optimized for BytesIO objects: + + 1. Reads content in chunks to maintain memory efficiency + 2. Yields control back to the event loop periodically to prevent blocking + when dealing with large BytesIO objects + 3. Respects content_length constraints when specified + 4. Properly cleans up by closing the BytesIO object when done or on error + + The periodic yielding to the event loop is important for maintaining + responsiveness when processing large in-memory buffers. + + """ + self._set_or_restore_start_position() + loop_count = 0 + remaining_bytes = content_length + while chunk := self._value.read(READ_SIZE): + if loop_count > 0: + # Avoid blocking the event loop + # if they pass a large BytesIO object + # and we are not in the first iteration + # of the loop + await asyncio.sleep(0) + if remaining_bytes is None: + await writer.write(chunk) + else: + await writer.write(chunk[:remaining_bytes]) + remaining_bytes -= len(chunk) + if remaining_bytes <= 0: + return + loop_count += 1 + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """ + Return bytes representation of the value. + + This method reads the entire BytesIO content and returns it as bytes. + It is equivalent to accessing the _value attribute directly. + """ + self._set_or_restore_start_position() + return self._value.read() + + async def close(self) -> None: + """ + Close the BytesIO payload. + + This does nothing since BytesIO is in-memory and does not require explicit closing. + """ + + +class BufferedReaderPayload(IOBasePayload): + _value: io.BufferedIOBase + # _autoclose = False (inherited) - Has buffered file handle that needs explicit closing + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + self._set_or_restore_start_position() + return self._value.read().decode(encoding, errors) + + +class JsonPayload(BytesPayload): + def __init__( + self, + value: Any, + encoding: str = "utf-8", + content_type: str = "application/json", + dumps: JSONEncoder = json.dumps, + *args: Any, + **kwargs: Any, + ) -> None: + + super().__init__( + dumps(value).encode(encoding), + content_type=content_type, + encoding=encoding, + *args, + **kwargs, + ) + + +if TYPE_CHECKING: + from typing import AsyncIterable, AsyncIterator + + _AsyncIterator = AsyncIterator[bytes] + _AsyncIterable = AsyncIterable[bytes] +else: + from collections.abc import AsyncIterable, AsyncIterator + + _AsyncIterator = AsyncIterator + _AsyncIterable = AsyncIterable + + +class AsyncIterablePayload(Payload): + + _iter: Optional[_AsyncIterator] = None + _value: _AsyncIterable + _cached_chunks: Optional[List[bytes]] = None + # _consumed stays False to allow reuse with cached content + _autoclose = True # Iterator doesn't need explicit closing + + def __init__(self, value: _AsyncIterable, *args: Any, **kwargs: Any) -> None: + if not isinstance(value, AsyncIterable): + raise TypeError( + "value argument must support " + "collections.abc.AsyncIterable interface, " + "got {!r}".format(type(value)) + ) + + if "content_type" not in kwargs: + kwargs["content_type"] = "application/octet-stream" + + super().__init__(value, *args, **kwargs) + + self._iter = value.__aiter__() + + async def write(self, writer: AbstractStreamWriter) -> None: + """ + Write the entire async iterable payload to the writer stream. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + + This method iterates through the async iterable and writes each chunk + to the writer without any length constraint. + + Note: + For new implementations that need length control, use write_with_length() directly. + This method is maintained for backwards compatibility with existing code. + + """ + await self.write_with_length(writer, None) + + async def write_with_length( + self, writer: AbstractStreamWriter, content_length: Optional[int] + ) -> None: + """ + Write async iterable payload with a specific content length constraint. + + Args: + writer: An AbstractStreamWriter instance that handles the actual writing + content_length: Maximum number of bytes to write (None for unlimited) + + This implementation handles streaming of async iterable content with length constraints: + + 1. If cached chunks are available, writes from them + 2. Otherwise iterates through the async iterable one chunk at a time + 3. Respects content_length constraints when specified + 4. Does NOT generate cache - that's done by as_bytes() + + """ + # If we have cached chunks, use them + if self._cached_chunks is not None: + remaining_bytes = content_length + for chunk in self._cached_chunks: + if remaining_bytes is None: + await writer.write(chunk) + elif remaining_bytes > 0: + await writer.write(chunk[:remaining_bytes]) + remaining_bytes -= len(chunk) + else: + break + return + + # If iterator is exhausted and we don't have cached chunks, nothing to write + if self._iter is None: + return + + # Stream from the iterator + remaining_bytes = content_length + + try: + while True: + if sys.version_info >= (3, 10): + chunk = await anext(self._iter) + else: + chunk = await self._iter.__anext__() + if remaining_bytes is None: + await writer.write(chunk) + # If we have a content length limit + elif remaining_bytes > 0: + await writer.write(chunk[:remaining_bytes]) + remaining_bytes -= len(chunk) + # We still want to exhaust the iterator even + # if we have reached the content length limit + # since the file handle may not get closed by + # the iterator if we don't do this + except StopAsyncIteration: + # Iterator is exhausted + self._iter = None + self._consumed = True # Mark as consumed when streamed without caching + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + """Decode the payload content as a string if cached chunks are available.""" + if self._cached_chunks is not None: + return b"".join(self._cached_chunks).decode(encoding, errors) + raise TypeError("Unable to decode - content not cached. Call as_bytes() first.") + + async def as_bytes(self, encoding: str = "utf-8", errors: str = "strict") -> bytes: + """ + Return bytes representation of the value. + + This method reads the entire async iterable content and returns it as bytes. + It generates and caches the chunks for future reuse. + """ + # If we have cached chunks, return them joined + if self._cached_chunks is not None: + return b"".join(self._cached_chunks) + + # If iterator is exhausted and no cache, return empty + if self._iter is None: + return b"" + + # Read all chunks and cache them + chunks: List[bytes] = [] + async for chunk in self._iter: + chunks.append(chunk) + + # Iterator is exhausted, cache the chunks + self._iter = None + self._cached_chunks = chunks + # Keep _consumed as False to allow reuse with cached chunks + + return b"".join(chunks) + + +class StreamReaderPayload(AsyncIterablePayload): + def __init__(self, value: StreamReader, *args: Any, **kwargs: Any) -> None: + super().__init__(value.iter_any(), *args, **kwargs) + + +PAYLOAD_REGISTRY = PayloadRegistry() +PAYLOAD_REGISTRY.register(BytesPayload, (bytes, bytearray, memoryview)) +PAYLOAD_REGISTRY.register(StringPayload, str) +PAYLOAD_REGISTRY.register(StringIOPayload, io.StringIO) +PAYLOAD_REGISTRY.register(TextIOPayload, io.TextIOBase) +PAYLOAD_REGISTRY.register(BytesIOPayload, io.BytesIO) +PAYLOAD_REGISTRY.register(BufferedReaderPayload, (io.BufferedReader, io.BufferedRandom)) +PAYLOAD_REGISTRY.register(IOBasePayload, io.IOBase) +PAYLOAD_REGISTRY.register(StreamReaderPayload, StreamReader) +# try_last for giving a chance to more specialized async interables like +# multipart.BodyPartReaderPayload override the default +PAYLOAD_REGISTRY.register(AsyncIterablePayload, AsyncIterable, order=Order.try_last) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/payload_streamer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/payload_streamer.py new file mode 100644 index 0000000000000000000000000000000000000000..831fdc0a77f302acaf9a000be408fe7c9a9035aa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/payload_streamer.py @@ -0,0 +1,78 @@ +""" +Payload implementation for coroutines as data provider. + +As a simple case, you can upload data from file:: + + @aiohttp.streamer + async def file_sender(writer, file_name=None): + with open(file_name, 'rb') as f: + chunk = f.read(2**16) + while chunk: + await writer.write(chunk) + + chunk = f.read(2**16) + +Then you can use `file_sender` like this: + + async with session.post('http://httpbin.org/post', + data=file_sender(file_name='huge_file')) as resp: + print(await resp.text()) + +..note:: Coroutine must accept `writer` as first argument + +""" + +import types +import warnings +from typing import Any, Awaitable, Callable, Dict, Tuple + +from .abc import AbstractStreamWriter +from .payload import Payload, payload_type + +__all__ = ("streamer",) + + +class _stream_wrapper: + def __init__( + self, + coro: Callable[..., Awaitable[None]], + args: Tuple[Any, ...], + kwargs: Dict[str, Any], + ) -> None: + self.coro = types.coroutine(coro) + self.args = args + self.kwargs = kwargs + + async def __call__(self, writer: AbstractStreamWriter) -> None: + await self.coro(writer, *self.args, **self.kwargs) + + +class streamer: + def __init__(self, coro: Callable[..., Awaitable[None]]) -> None: + warnings.warn( + "@streamer is deprecated, use async generators instead", + DeprecationWarning, + stacklevel=2, + ) + self.coro = coro + + def __call__(self, *args: Any, **kwargs: Any) -> _stream_wrapper: + return _stream_wrapper(self.coro, args, kwargs) + + +@payload_type(_stream_wrapper) +class StreamWrapperPayload(Payload): + async def write(self, writer: AbstractStreamWriter) -> None: + await self._value(writer) + + def decode(self, encoding: str = "utf-8", errors: str = "strict") -> str: + raise TypeError("Unable to decode.") + + +@payload_type(streamer) +class StreamPayload(StreamWrapperPayload): + def __init__(self, value: Any, *args: Any, **kwargs: Any) -> None: + super().__init__(value(), *args, **kwargs) + + async def write(self, writer: AbstractStreamWriter) -> None: + await self._value(writer) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/py.typed b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..f5642f79f21d872f010979dcf6f0c4a415acc19d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/py.typed @@ -0,0 +1 @@ +Marker diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/pytest_plugin.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/pytest_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..7d59fe820d697632c9a3311ff96841ebc0ee735b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/pytest_plugin.py @@ -0,0 +1,444 @@ +import asyncio +import contextlib +import inspect +import warnings +from typing import ( + Any, + Awaitable, + Callable, + Dict, + Iterator, + Optional, + Protocol, + Union, + overload, +) + +import pytest + +from .test_utils import ( + BaseTestServer, + RawTestServer, + TestClient, + TestServer, + loop_context, + setup_test_loop, + teardown_test_loop, + unused_port as _unused_port, +) +from .web import Application, BaseRequest, Request +from .web_protocol import _RequestHandler + +try: + import uvloop +except ImportError: # pragma: no cover + uvloop = None # type: ignore[assignment] + + +class AiohttpClient(Protocol): + @overload + async def __call__( + self, + __param: Application, + *, + server_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> TestClient[Request, Application]: ... + @overload + async def __call__( + self, + __param: BaseTestServer, + *, + server_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> TestClient[BaseRequest, None]: ... + + +class AiohttpServer(Protocol): + def __call__( + self, app: Application, *, port: Optional[int] = None, **kwargs: Any + ) -> Awaitable[TestServer]: ... + + +class AiohttpRawServer(Protocol): + def __call__( + self, handler: _RequestHandler, *, port: Optional[int] = None, **kwargs: Any + ) -> Awaitable[RawTestServer]: ... + + +def pytest_addoption(parser): # type: ignore[no-untyped-def] + parser.addoption( + "--aiohttp-fast", + action="store_true", + default=False, + help="run tests faster by disabling extra checks", + ) + parser.addoption( + "--aiohttp-loop", + action="store", + default="pyloop", + help="run tests with specific loop: pyloop, uvloop or all", + ) + parser.addoption( + "--aiohttp-enable-loop-debug", + action="store_true", + default=False, + help="enable event loop debug mode", + ) + + +def pytest_fixture_setup(fixturedef): # type: ignore[no-untyped-def] + """Set up pytest fixture. + + Allow fixtures to be coroutines. Run coroutine fixtures in an event loop. + """ + func = fixturedef.func + + if inspect.isasyncgenfunction(func): + # async generator fixture + is_async_gen = True + elif inspect.iscoroutinefunction(func): + # regular async fixture + is_async_gen = False + else: + # not an async fixture, nothing to do + return + + strip_request = False + if "request" not in fixturedef.argnames: + fixturedef.argnames += ("request",) + strip_request = True + + def wrapper(*args, **kwargs): # type: ignore[no-untyped-def] + request = kwargs["request"] + if strip_request: + del kwargs["request"] + + # if neither the fixture nor the test use the 'loop' fixture, + # 'getfixturevalue' will fail because the test is not parameterized + # (this can be removed someday if 'loop' is no longer parameterized) + if "loop" not in request.fixturenames: + raise Exception( + "Asynchronous fixtures must depend on the 'loop' fixture or " + "be used in tests depending from it." + ) + + _loop = request.getfixturevalue("loop") + + if is_async_gen: + # for async generators, we need to advance the generator once, + # then advance it again in a finalizer + gen = func(*args, **kwargs) + + def finalizer(): # type: ignore[no-untyped-def] + try: + return _loop.run_until_complete(gen.__anext__()) + except StopAsyncIteration: + pass + + request.addfinalizer(finalizer) + return _loop.run_until_complete(gen.__anext__()) + else: + return _loop.run_until_complete(func(*args, **kwargs)) + + fixturedef.func = wrapper + + +@pytest.fixture +def fast(request): # type: ignore[no-untyped-def] + """--fast config option""" + return request.config.getoption("--aiohttp-fast") + + +@pytest.fixture +def loop_debug(request): # type: ignore[no-untyped-def] + """--enable-loop-debug config option""" + return request.config.getoption("--aiohttp-enable-loop-debug") + + +@contextlib.contextmanager +def _runtime_warning_context(): # type: ignore[no-untyped-def] + """Context manager which checks for RuntimeWarnings. + + This exists specifically to + avoid "coroutine 'X' was never awaited" warnings being missed. + + If RuntimeWarnings occur in the context a RuntimeError is raised. + """ + with warnings.catch_warnings(record=True) as _warnings: + yield + rw = [ + "{w.filename}:{w.lineno}:{w.message}".format(w=w) + for w in _warnings + if w.category == RuntimeWarning + ] + if rw: + raise RuntimeError( + "{} Runtime Warning{},\n{}".format( + len(rw), "" if len(rw) == 1 else "s", "\n".join(rw) + ) + ) + + +@contextlib.contextmanager +def _passthrough_loop_context(loop, fast=False): # type: ignore[no-untyped-def] + """Passthrough loop context. + + Sets up and tears down a loop unless one is passed in via the loop + argument when it's passed straight through. + """ + if loop: + # loop already exists, pass it straight through + yield loop + else: + # this shadows loop_context's standard behavior + loop = setup_test_loop() + yield loop + teardown_test_loop(loop, fast=fast) + + +def pytest_pycollect_makeitem(collector, name, obj): # type: ignore[no-untyped-def] + """Fix pytest collecting for coroutines.""" + if collector.funcnamefilter(name) and inspect.iscoroutinefunction(obj): + return list(collector._genfunctions(name, obj)) + + +def pytest_pyfunc_call(pyfuncitem): # type: ignore[no-untyped-def] + """Run coroutines in an event loop instead of a normal function call.""" + fast = pyfuncitem.config.getoption("--aiohttp-fast") + if inspect.iscoroutinefunction(pyfuncitem.function): + existing_loop = ( + pyfuncitem.funcargs.get("proactor_loop") + or pyfuncitem.funcargs.get("selector_loop") + or pyfuncitem.funcargs.get("uvloop_loop") + or pyfuncitem.funcargs.get("loop", None) + ) + + with _runtime_warning_context(): + with _passthrough_loop_context(existing_loop, fast=fast) as _loop: + testargs = { + arg: pyfuncitem.funcargs[arg] + for arg in pyfuncitem._fixtureinfo.argnames + } + _loop.run_until_complete(pyfuncitem.obj(**testargs)) + + return True + + +def pytest_generate_tests(metafunc): # type: ignore[no-untyped-def] + if "loop_factory" not in metafunc.fixturenames: + return + + loops = metafunc.config.option.aiohttp_loop + avail_factories: dict[str, Callable[[], asyncio.AbstractEventLoop]] + avail_factories = {"pyloop": asyncio.new_event_loop} + + if uvloop is not None: # pragma: no cover + avail_factories["uvloop"] = uvloop.new_event_loop + + if loops == "all": + loops = "pyloop,uvloop?" + + factories = {} # type: ignore[var-annotated] + for name in loops.split(","): + required = not name.endswith("?") + name = name.strip(" ?") + if name not in avail_factories: # pragma: no cover + if required: + raise ValueError( + "Unknown loop '%s', available loops: %s" + % (name, list(factories.keys())) + ) + else: + continue + factories[name] = avail_factories[name] + metafunc.parametrize( + "loop_factory", list(factories.values()), ids=list(factories.keys()) + ) + + +@pytest.fixture +def loop( + loop_factory: Callable[[], asyncio.AbstractEventLoop], + fast: bool, + loop_debug: bool, +) -> Iterator[asyncio.AbstractEventLoop]: + """Return an instance of the event loop.""" + with loop_context(loop_factory, fast=fast) as _loop: + if loop_debug: + _loop.set_debug(True) # pragma: no cover + asyncio.set_event_loop(_loop) + yield _loop + + +@pytest.fixture +def proactor_loop() -> Iterator[asyncio.AbstractEventLoop]: + factory = asyncio.ProactorEventLoop # type: ignore[attr-defined] + + with loop_context(factory) as _loop: + asyncio.set_event_loop(_loop) + yield _loop + + +@pytest.fixture +def unused_port(aiohttp_unused_port: Callable[[], int]) -> Callable[[], int]: + warnings.warn( + "Deprecated, use aiohttp_unused_port fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_unused_port + + +@pytest.fixture +def aiohttp_unused_port() -> Callable[[], int]: + """Return a port that is unused on the current host.""" + return _unused_port + + +@pytest.fixture +def aiohttp_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpServer]: + """Factory to create a TestServer instance, given an app. + + aiohttp_server(app, **kwargs) + """ + servers = [] + + async def go( + app: Application, + *, + host: str = "127.0.0.1", + port: Optional[int] = None, + **kwargs: Any, + ) -> TestServer: + server = TestServer(app, host=host, port=port) + await server.start_server(loop=loop, **kwargs) + servers.append(server) + return server + + yield go + + async def finalize() -> None: + while servers: + await servers.pop().close() + + loop.run_until_complete(finalize()) + + +@pytest.fixture +def test_server(aiohttp_server): # type: ignore[no-untyped-def] # pragma: no cover + warnings.warn( + "Deprecated, use aiohttp_server fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_server + + +@pytest.fixture +def aiohttp_raw_server(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpRawServer]: + """Factory to create a RawTestServer instance, given a web handler. + + aiohttp_raw_server(handler, **kwargs) + """ + servers = [] + + async def go( + handler: _RequestHandler, *, port: Optional[int] = None, **kwargs: Any + ) -> RawTestServer: + server = RawTestServer(handler, port=port) + await server.start_server(loop=loop, **kwargs) + servers.append(server) + return server + + yield go + + async def finalize() -> None: + while servers: + await servers.pop().close() + + loop.run_until_complete(finalize()) + + +@pytest.fixture +def raw_test_server( # type: ignore[no-untyped-def] # pragma: no cover + aiohttp_raw_server, +): + warnings.warn( + "Deprecated, use aiohttp_raw_server fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_raw_server + + +@pytest.fixture +def aiohttp_client(loop: asyncio.AbstractEventLoop) -> Iterator[AiohttpClient]: + """Factory to create a TestClient instance. + + aiohttp_client(app, **kwargs) + aiohttp_client(server, **kwargs) + aiohttp_client(raw_server, **kwargs) + """ + clients = [] + + @overload + async def go( + __param: Application, + *, + server_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> TestClient[Request, Application]: ... + + @overload + async def go( + __param: BaseTestServer, + *, + server_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> TestClient[BaseRequest, None]: ... + + async def go( + __param: Union[Application, BaseTestServer], + *args: Any, + server_kwargs: Optional[Dict[str, Any]] = None, + **kwargs: Any, + ) -> TestClient[Any, Any]: + if isinstance(__param, Callable) and not isinstance( # type: ignore[arg-type] + __param, (Application, BaseTestServer) + ): + __param = __param(loop, *args, **kwargs) + kwargs = {} + else: + assert not args, "args should be empty" + + if isinstance(__param, Application): + server_kwargs = server_kwargs or {} + server = TestServer(__param, loop=loop, **server_kwargs) + client = TestClient(server, loop=loop, **kwargs) + elif isinstance(__param, BaseTestServer): + client = TestClient(__param, loop=loop, **kwargs) + else: + raise ValueError("Unknown argument type: %r" % type(__param)) + + await client.start_server() + clients.append(client) + return client + + yield go + + async def finalize() -> None: + while clients: + await clients.pop().close() + + loop.run_until_complete(finalize()) + + +@pytest.fixture +def test_client(aiohttp_client): # type: ignore[no-untyped-def] # pragma: no cover + warnings.warn( + "Deprecated, use aiohttp_client fixture instead", + DeprecationWarning, + stacklevel=2, + ) + return aiohttp_client diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/resolver.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/resolver.py new file mode 100644 index 0000000000000000000000000000000000000000..b20e5672ce51a1aadd7768301a3a1c8eb6007bf4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/resolver.py @@ -0,0 +1,274 @@ +import asyncio +import socket +import weakref +from typing import Any, Dict, Final, List, Optional, Tuple, Type, Union + +from .abc import AbstractResolver, ResolveResult + +__all__ = ("ThreadedResolver", "AsyncResolver", "DefaultResolver") + + +try: + import aiodns + + aiodns_default = hasattr(aiodns.DNSResolver, "getaddrinfo") +except ImportError: # pragma: no cover + aiodns = None # type: ignore[assignment] + aiodns_default = False + + +_NUMERIC_SOCKET_FLAGS = socket.AI_NUMERICHOST | socket.AI_NUMERICSERV +_NAME_SOCKET_FLAGS = socket.NI_NUMERICHOST | socket.NI_NUMERICSERV +_AI_ADDRCONFIG = socket.AI_ADDRCONFIG +if hasattr(socket, "AI_MASK"): + _AI_ADDRCONFIG &= socket.AI_MASK + + +class ThreadedResolver(AbstractResolver): + """Threaded resolver. + + Uses an Executor for synchronous getaddrinfo() calls. + concurrent.futures.ThreadPoolExecutor is used by default. + """ + + def __init__(self, loop: Optional[asyncio.AbstractEventLoop] = None) -> None: + self._loop = loop or asyncio.get_running_loop() + + async def resolve( + self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET + ) -> List[ResolveResult]: + infos = await self._loop.getaddrinfo( + host, + port, + type=socket.SOCK_STREAM, + family=family, + flags=_AI_ADDRCONFIG, + ) + + hosts: List[ResolveResult] = [] + for family, _, proto, _, address in infos: + if family == socket.AF_INET6: + if len(address) < 3: + # IPv6 is not supported by Python build, + # or IPv6 is not enabled in the host + continue + if address[3]: + # This is essential for link-local IPv6 addresses. + # LL IPv6 is a VERY rare case. Strictly speaking, we should use + # getnameinfo() unconditionally, but performance makes sense. + resolved_host, _port = await self._loop.getnameinfo( + address, _NAME_SOCKET_FLAGS + ) + port = int(_port) + else: + resolved_host, port = address[:2] + else: # IPv4 + assert family == socket.AF_INET + resolved_host, port = address # type: ignore[misc] + hosts.append( + ResolveResult( + hostname=host, + host=resolved_host, + port=port, + family=family, + proto=proto, + flags=_NUMERIC_SOCKET_FLAGS, + ) + ) + + return hosts + + async def close(self) -> None: + pass + + +class AsyncResolver(AbstractResolver): + """Use the `aiodns` package to make asynchronous DNS lookups""" + + def __init__( + self, + loop: Optional[asyncio.AbstractEventLoop] = None, + *args: Any, + **kwargs: Any, + ) -> None: + if aiodns is None: + raise RuntimeError("Resolver requires aiodns library") + + self._loop = loop or asyncio.get_running_loop() + self._manager: Optional[_DNSResolverManager] = None + # If custom args are provided, create a dedicated resolver instance + # This means each AsyncResolver with custom args gets its own + # aiodns.DNSResolver instance + if args or kwargs: + self._resolver = aiodns.DNSResolver(*args, **kwargs) + return + # Use the shared resolver from the manager for default arguments + self._manager = _DNSResolverManager() + self._resolver = self._manager.get_resolver(self, self._loop) + + if not hasattr(self._resolver, "gethostbyname"): + # aiodns 1.1 is not available, fallback to DNSResolver.query + self.resolve = self._resolve_with_query # type: ignore + + async def resolve( + self, host: str, port: int = 0, family: socket.AddressFamily = socket.AF_INET + ) -> List[ResolveResult]: + try: + resp = await self._resolver.getaddrinfo( + host, + port=port, + type=socket.SOCK_STREAM, + family=family, + flags=_AI_ADDRCONFIG, + ) + except aiodns.error.DNSError as exc: + msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" + raise OSError(None, msg) from exc + hosts: List[ResolveResult] = [] + for node in resp.nodes: + address: Union[Tuple[bytes, int], Tuple[bytes, int, int, int]] = node.addr + family = node.family + if family == socket.AF_INET6: + if len(address) > 3 and address[3]: + # This is essential for link-local IPv6 addresses. + # LL IPv6 is a VERY rare case. Strictly speaking, we should use + # getnameinfo() unconditionally, but performance makes sense. + result = await self._resolver.getnameinfo( + (address[0].decode("ascii"), *address[1:]), + _NAME_SOCKET_FLAGS, + ) + resolved_host = result.node + else: + resolved_host = address[0].decode("ascii") + port = address[1] + else: # IPv4 + assert family == socket.AF_INET + resolved_host = address[0].decode("ascii") + port = address[1] + hosts.append( + ResolveResult( + hostname=host, + host=resolved_host, + port=port, + family=family, + proto=0, + flags=_NUMERIC_SOCKET_FLAGS, + ) + ) + + if not hosts: + raise OSError(None, "DNS lookup failed") + + return hosts + + async def _resolve_with_query( + self, host: str, port: int = 0, family: int = socket.AF_INET + ) -> List[Dict[str, Any]]: + qtype: Final = "AAAA" if family == socket.AF_INET6 else "A" + + try: + resp = await self._resolver.query(host, qtype) + except aiodns.error.DNSError as exc: + msg = exc.args[1] if len(exc.args) >= 1 else "DNS lookup failed" + raise OSError(None, msg) from exc + + hosts = [] + for rr in resp: + hosts.append( + { + "hostname": host, + "host": rr.host, + "port": port, + "family": family, + "proto": 0, + "flags": socket.AI_NUMERICHOST, + } + ) + + if not hosts: + raise OSError(None, "DNS lookup failed") + + return hosts + + async def close(self) -> None: + if self._manager: + # Release the resolver from the manager if using the shared resolver + self._manager.release_resolver(self, self._loop) + self._manager = None # Clear reference to manager + self._resolver = None # type: ignore[assignment] # Clear reference to resolver + return + # Otherwise cancel our dedicated resolver + if self._resolver is not None: + self._resolver.cancel() + self._resolver = None # type: ignore[assignment] # Clear reference + + +class _DNSResolverManager: + """Manager for aiodns.DNSResolver objects. + + This class manages shared aiodns.DNSResolver instances + with no custom arguments across different event loops. + """ + + _instance: Optional["_DNSResolverManager"] = None + + def __new__(cls) -> "_DNSResolverManager": + if cls._instance is None: + cls._instance = super().__new__(cls) + cls._instance._init() + return cls._instance + + def _init(self) -> None: + # Use WeakKeyDictionary to allow event loops to be garbage collected + self._loop_data: weakref.WeakKeyDictionary[ + asyncio.AbstractEventLoop, + tuple["aiodns.DNSResolver", weakref.WeakSet["AsyncResolver"]], + ] = weakref.WeakKeyDictionary() + + def get_resolver( + self, client: "AsyncResolver", loop: asyncio.AbstractEventLoop + ) -> "aiodns.DNSResolver": + """Get or create the shared aiodns.DNSResolver instance for a specific event loop. + + Args: + client: The AsyncResolver instance requesting the resolver. + This is required to track resolver usage. + loop: The event loop to use for the resolver. + """ + # Create a new resolver and client set for this loop if it doesn't exist + if loop not in self._loop_data: + resolver = aiodns.DNSResolver(loop=loop) + client_set: weakref.WeakSet["AsyncResolver"] = weakref.WeakSet() + self._loop_data[loop] = (resolver, client_set) + else: + # Get the existing resolver and client set + resolver, client_set = self._loop_data[loop] + + # Register this client with the loop + client_set.add(client) + return resolver + + def release_resolver( + self, client: "AsyncResolver", loop: asyncio.AbstractEventLoop + ) -> None: + """Release the resolver for an AsyncResolver client when it's closed. + + Args: + client: The AsyncResolver instance to release. + loop: The event loop the resolver was using. + """ + # Remove client from its loop's tracking + current_loop_data = self._loop_data.get(loop) + if current_loop_data is None: + return + resolver, client_set = current_loop_data + client_set.discard(client) + # If no more clients for this loop, cancel and remove its resolver + if not client_set: + if resolver is not None: + resolver.cancel() + del self._loop_data[loop] + + +_DefaultType = Type[Union[AsyncResolver, ThreadedResolver]] +DefaultResolver: _DefaultType = AsyncResolver if aiodns_default else ThreadedResolver diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/streams.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/streams.py new file mode 100644 index 0000000000000000000000000000000000000000..7a3f64d12894e9d3158ec2a8415c48c47fed0bcd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/streams.py @@ -0,0 +1,727 @@ +import asyncio +import collections +import warnings +from typing import ( + Awaitable, + Callable, + Deque, + Final, + Generic, + List, + Optional, + Tuple, + TypeVar, +) + +from .base_protocol import BaseProtocol +from .helpers import ( + _EXC_SENTINEL, + BaseTimerContext, + TimerNoop, + set_exception, + set_result, +) +from .log import internal_logger + +__all__ = ( + "EMPTY_PAYLOAD", + "EofStream", + "StreamReader", + "DataQueue", +) + +_T = TypeVar("_T") + + +class EofStream(Exception): + """eof stream indication.""" + + +class AsyncStreamIterator(Generic[_T]): + + __slots__ = ("read_func",) + + def __init__(self, read_func: Callable[[], Awaitable[_T]]) -> None: + self.read_func = read_func + + def __aiter__(self) -> "AsyncStreamIterator[_T]": + return self + + async def __anext__(self) -> _T: + try: + rv = await self.read_func() + except EofStream: + raise StopAsyncIteration + if rv == b"": + raise StopAsyncIteration + return rv + + +class ChunkTupleAsyncStreamIterator: + + __slots__ = ("_stream",) + + def __init__(self, stream: "StreamReader") -> None: + self._stream = stream + + def __aiter__(self) -> "ChunkTupleAsyncStreamIterator": + return self + + async def __anext__(self) -> Tuple[bytes, bool]: + rv = await self._stream.readchunk() + if rv == (b"", False): + raise StopAsyncIteration + return rv + + +class AsyncStreamReaderMixin: + + __slots__ = () + + def __aiter__(self) -> AsyncStreamIterator[bytes]: + return AsyncStreamIterator(self.readline) # type: ignore[attr-defined] + + def iter_chunked(self, n: int) -> AsyncStreamIterator[bytes]: + """Returns an asynchronous iterator that yields chunks of size n.""" + return AsyncStreamIterator(lambda: self.read(n)) # type: ignore[attr-defined] + + def iter_any(self) -> AsyncStreamIterator[bytes]: + """Yield all available data as soon as it is received.""" + return AsyncStreamIterator(self.readany) # type: ignore[attr-defined] + + def iter_chunks(self) -> ChunkTupleAsyncStreamIterator: + """Yield chunks of data as they are received by the server. + + The yielded objects are tuples + of (bytes, bool) as returned by the StreamReader.readchunk method. + """ + return ChunkTupleAsyncStreamIterator(self) # type: ignore[arg-type] + + +class StreamReader(AsyncStreamReaderMixin): + """An enhancement of asyncio.StreamReader. + + Supports asynchronous iteration by line, chunk or as available:: + + async for line in reader: + ... + async for chunk in reader.iter_chunked(1024): + ... + async for slice in reader.iter_any(): + ... + + """ + + __slots__ = ( + "_protocol", + "_low_water", + "_high_water", + "_loop", + "_size", + "_cursor", + "_http_chunk_splits", + "_buffer", + "_buffer_offset", + "_eof", + "_waiter", + "_eof_waiter", + "_exception", + "_timer", + "_eof_callbacks", + "_eof_counter", + "total_bytes", + ) + + def __init__( + self, + protocol: BaseProtocol, + limit: int, + *, + timer: Optional[BaseTimerContext] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + ) -> None: + self._protocol = protocol + self._low_water = limit + self._high_water = limit * 2 + if loop is None: + loop = asyncio.get_event_loop() + self._loop = loop + self._size = 0 + self._cursor = 0 + self._http_chunk_splits: Optional[List[int]] = None + self._buffer: Deque[bytes] = collections.deque() + self._buffer_offset = 0 + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._eof_waiter: Optional[asyncio.Future[None]] = None + self._exception: Optional[BaseException] = None + self._timer = TimerNoop() if timer is None else timer + self._eof_callbacks: List[Callable[[], None]] = [] + self._eof_counter = 0 + self.total_bytes = 0 + + def __repr__(self) -> str: + info = [self.__class__.__name__] + if self._size: + info.append("%d bytes" % self._size) + if self._eof: + info.append("eof") + if self._low_water != 2**16: # default limit + info.append("low=%d high=%d" % (self._low_water, self._high_water)) + if self._waiter: + info.append("w=%r" % self._waiter) + if self._exception: + info.append("e=%r" % self._exception) + return "<%s>" % " ".join(info) + + def get_read_buffer_limits(self) -> Tuple[int, int]: + return (self._low_water, self._high_water) + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + self._exception = exc + self._eof_callbacks.clear() + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + waiter = self._eof_waiter + if waiter is not None: + self._eof_waiter = None + set_exception(waiter, exc, exc_cause) + + def on_eof(self, callback: Callable[[], None]) -> None: + if self._eof: + try: + callback() + except Exception: + internal_logger.exception("Exception in eof callback") + else: + self._eof_callbacks.append(callback) + + def feed_eof(self) -> None: + self._eof = True + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + waiter = self._eof_waiter + if waiter is not None: + self._eof_waiter = None + set_result(waiter, None) + + if self._protocol._reading_paused: + self._protocol.resume_reading() + + for cb in self._eof_callbacks: + try: + cb() + except Exception: + internal_logger.exception("Exception in eof callback") + + self._eof_callbacks.clear() + + def is_eof(self) -> bool: + """Return True if 'feed_eof' was called.""" + return self._eof + + def at_eof(self) -> bool: + """Return True if the buffer is empty and 'feed_eof' was called.""" + return self._eof and not self._buffer + + async def wait_eof(self) -> None: + if self._eof: + return + + assert self._eof_waiter is None + self._eof_waiter = self._loop.create_future() + try: + await self._eof_waiter + finally: + self._eof_waiter = None + + def unread_data(self, data: bytes) -> None: + """rollback reading some data from stream, inserting it to buffer head.""" + warnings.warn( + "unread_data() is deprecated " + "and will be removed in future releases (#3260)", + DeprecationWarning, + stacklevel=2, + ) + if not data: + return + + if self._buffer_offset: + self._buffer[0] = self._buffer[0][self._buffer_offset :] + self._buffer_offset = 0 + self._size += len(data) + self._cursor -= len(data) + self._buffer.appendleft(data) + self._eof_counter = 0 + + # TODO: size is ignored, remove the param later + def feed_data(self, data: bytes, size: int = 0) -> None: + assert not self._eof, "feed_data after feed_eof" + + if not data: + return + + data_len = len(data) + self._size += data_len + self._buffer.append(data) + self.total_bytes += data_len + + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + if self._size > self._high_water and not self._protocol._reading_paused: + self._protocol.pause_reading() + + def begin_http_chunk_receiving(self) -> None: + if self._http_chunk_splits is None: + if self.total_bytes: + raise RuntimeError( + "Called begin_http_chunk_receiving when some data was already fed" + ) + self._http_chunk_splits = [] + + def end_http_chunk_receiving(self) -> None: + if self._http_chunk_splits is None: + raise RuntimeError( + "Called end_chunk_receiving without calling " + "begin_chunk_receiving first" + ) + + # self._http_chunk_splits contains logical byte offsets from start of + # the body transfer. Each offset is the offset of the end of a chunk. + # "Logical" means bytes, accessible for a user. + # If no chunks containing logical data were received, current position + # is difinitely zero. + pos = self._http_chunk_splits[-1] if self._http_chunk_splits else 0 + + if self.total_bytes == pos: + # We should not add empty chunks here. So we check for that. + # Note, when chunked + gzip is used, we can receive a chunk + # of compressed data, but that data may not be enough for gzip FSM + # to yield any uncompressed data. That's why current position may + # not change after receiving a chunk. + return + + self._http_chunk_splits.append(self.total_bytes) + + # wake up readchunk when end of http chunk received + waiter = self._waiter + if waiter is not None: + self._waiter = None + set_result(waiter, None) + + async def _wait(self, func_name: str) -> None: + if not self._protocol.connected: + raise RuntimeError("Connection closed.") + + # StreamReader uses a future to link the protocol feed_data() method + # to a read coroutine. Running two read coroutines at the same time + # would have an unexpected behaviour. It would not possible to know + # which coroutine would get the next data. + if self._waiter is not None: + raise RuntimeError( + "%s() called while another coroutine is " + "already waiting for incoming data" % func_name + ) + + waiter = self._waiter = self._loop.create_future() + try: + with self._timer: + await waiter + finally: + self._waiter = None + + async def readline(self) -> bytes: + return await self.readuntil() + + async def readuntil(self, separator: bytes = b"\n") -> bytes: + seplen = len(separator) + if seplen == 0: + raise ValueError("Separator should be at least one-byte string") + + if self._exception is not None: + raise self._exception + + chunk = b"" + chunk_size = 0 + not_enough = True + + while not_enough: + while self._buffer and not_enough: + offset = self._buffer_offset + ichar = self._buffer[0].find(separator, offset) + 1 + # Read from current offset to found separator or to the end. + data = self._read_nowait_chunk( + ichar - offset + seplen - 1 if ichar else -1 + ) + chunk += data + chunk_size += len(data) + if ichar: + not_enough = False + + if chunk_size > self._high_water: + raise ValueError("Chunk too big") + + if self._eof: + break + + if not_enough: + await self._wait("readuntil") + + return chunk + + async def read(self, n: int = -1) -> bytes: + if self._exception is not None: + raise self._exception + + # migration problem; with DataQueue you have to catch + # EofStream exception, so common way is to run payload.read() inside + # infinite loop. what can cause real infinite loop with StreamReader + # lets keep this code one major release. + if __debug__: + if self._eof and not self._buffer: + self._eof_counter = getattr(self, "_eof_counter", 0) + 1 + if self._eof_counter > 5: + internal_logger.warning( + "Multiple access to StreamReader in eof state, " + "might be infinite loop.", + stack_info=True, + ) + + if not n: + return b"" + + if n < 0: + # This used to just loop creating a new waiter hoping to + # collect everything in self._buffer, but that would + # deadlock if the subprocess sends more than self.limit + # bytes. So just call self.readany() until EOF. + blocks = [] + while True: + block = await self.readany() + if not block: + break + blocks.append(block) + return b"".join(blocks) + + # TODO: should be `if` instead of `while` + # because waiter maybe triggered on chunk end, + # without feeding any data + while not self._buffer and not self._eof: + await self._wait("read") + + return self._read_nowait(n) + + async def readany(self) -> bytes: + if self._exception is not None: + raise self._exception + + # TODO: should be `if` instead of `while` + # because waiter maybe triggered on chunk end, + # without feeding any data + while not self._buffer and not self._eof: + await self._wait("readany") + + return self._read_nowait(-1) + + async def readchunk(self) -> Tuple[bytes, bool]: + """Returns a tuple of (data, end_of_http_chunk). + + When chunked transfer + encoding is used, end_of_http_chunk is a boolean indicating if the end + of the data corresponds to the end of a HTTP chunk , otherwise it is + always False. + """ + while True: + if self._exception is not None: + raise self._exception + + while self._http_chunk_splits: + pos = self._http_chunk_splits.pop(0) + if pos == self._cursor: + return (b"", True) + if pos > self._cursor: + return (self._read_nowait(pos - self._cursor), True) + internal_logger.warning( + "Skipping HTTP chunk end due to data " + "consumption beyond chunk boundary" + ) + + if self._buffer: + return (self._read_nowait_chunk(-1), False) + # return (self._read_nowait(-1), False) + + if self._eof: + # Special case for signifying EOF. + # (b'', True) is not a final return value actually. + return (b"", False) + + await self._wait("readchunk") + + async def readexactly(self, n: int) -> bytes: + if self._exception is not None: + raise self._exception + + blocks: List[bytes] = [] + while n > 0: + block = await self.read(n) + if not block: + partial = b"".join(blocks) + raise asyncio.IncompleteReadError(partial, len(partial) + n) + blocks.append(block) + n -= len(block) + + return b"".join(blocks) + + def read_nowait(self, n: int = -1) -> bytes: + # default was changed to be consistent with .read(-1) + # + # I believe the most users don't know about the method and + # they are not affected. + if self._exception is not None: + raise self._exception + + if self._waiter and not self._waiter.done(): + raise RuntimeError( + "Called while some coroutine is waiting for incoming data." + ) + + return self._read_nowait(n) + + def _read_nowait_chunk(self, n: int) -> bytes: + first_buffer = self._buffer[0] + offset = self._buffer_offset + if n != -1 and len(first_buffer) - offset > n: + data = first_buffer[offset : offset + n] + self._buffer_offset += n + + elif offset: + self._buffer.popleft() + data = first_buffer[offset:] + self._buffer_offset = 0 + + else: + data = self._buffer.popleft() + + data_len = len(data) + self._size -= data_len + self._cursor += data_len + + chunk_splits = self._http_chunk_splits + # Prevent memory leak: drop useless chunk splits + while chunk_splits and chunk_splits[0] < self._cursor: + chunk_splits.pop(0) + + if self._size < self._low_water and self._protocol._reading_paused: + self._protocol.resume_reading() + return data + + def _read_nowait(self, n: int) -> bytes: + """Read not more than n bytes, or whole buffer if n == -1""" + self._timer.assert_timeout() + + chunks = [] + while self._buffer: + chunk = self._read_nowait_chunk(n) + chunks.append(chunk) + if n != -1: + n -= len(chunk) + if n == 0: + break + + return b"".join(chunks) if chunks else b"" + + +class EmptyStreamReader(StreamReader): # lgtm [py/missing-call-to-init] + + __slots__ = ("_read_eof_chunk",) + + def __init__(self) -> None: + self._read_eof_chunk = False + self.total_bytes = 0 + + def __repr__(self) -> str: + return "<%s>" % self.__class__.__name__ + + def exception(self) -> Optional[BaseException]: + return None + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + pass + + def on_eof(self, callback: Callable[[], None]) -> None: + try: + callback() + except Exception: + internal_logger.exception("Exception in eof callback") + + def feed_eof(self) -> None: + pass + + def is_eof(self) -> bool: + return True + + def at_eof(self) -> bool: + return True + + async def wait_eof(self) -> None: + return + + def feed_data(self, data: bytes, n: int = 0) -> None: + pass + + async def readline(self) -> bytes: + return b"" + + async def read(self, n: int = -1) -> bytes: + return b"" + + # TODO add async def readuntil + + async def readany(self) -> bytes: + return b"" + + async def readchunk(self) -> Tuple[bytes, bool]: + if not self._read_eof_chunk: + self._read_eof_chunk = True + return (b"", False) + + return (b"", True) + + async def readexactly(self, n: int) -> bytes: + raise asyncio.IncompleteReadError(b"", n) + + def read_nowait(self, n: int = -1) -> bytes: + return b"" + + +EMPTY_PAYLOAD: Final[StreamReader] = EmptyStreamReader() + + +class DataQueue(Generic[_T]): + """DataQueue is a general-purpose blocking queue with one reader.""" + + def __init__(self, loop: asyncio.AbstractEventLoop) -> None: + self._loop = loop + self._eof = False + self._waiter: Optional[asyncio.Future[None]] = None + self._exception: Optional[BaseException] = None + self._buffer: Deque[Tuple[_T, int]] = collections.deque() + + def __len__(self) -> int: + return len(self._buffer) + + def is_eof(self) -> bool: + return self._eof + + def at_eof(self) -> bool: + return self._eof and not self._buffer + + def exception(self) -> Optional[BaseException]: + return self._exception + + def set_exception( + self, + exc: BaseException, + exc_cause: BaseException = _EXC_SENTINEL, + ) -> None: + self._eof = True + self._exception = exc + if (waiter := self._waiter) is not None: + self._waiter = None + set_exception(waiter, exc, exc_cause) + + def feed_data(self, data: _T, size: int = 0) -> None: + self._buffer.append((data, size)) + if (waiter := self._waiter) is not None: + self._waiter = None + set_result(waiter, None) + + def feed_eof(self) -> None: + self._eof = True + if (waiter := self._waiter) is not None: + self._waiter = None + set_result(waiter, None) + + async def read(self) -> _T: + if not self._buffer and not self._eof: + assert not self._waiter + self._waiter = self._loop.create_future() + try: + await self._waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._waiter = None + raise + if self._buffer: + data, _ = self._buffer.popleft() + return data + if self._exception is not None: + raise self._exception + raise EofStream + + def __aiter__(self) -> AsyncStreamIterator[_T]: + return AsyncStreamIterator(self.read) + + +class FlowControlDataQueue(DataQueue[_T]): + """FlowControlDataQueue resumes and pauses an underlying stream. + + It is a destination for parsed data. + + This class is deprecated and will be removed in version 4.0. + """ + + def __init__( + self, protocol: BaseProtocol, limit: int, *, loop: asyncio.AbstractEventLoop + ) -> None: + super().__init__(loop=loop) + self._size = 0 + self._protocol = protocol + self._limit = limit * 2 + + def feed_data(self, data: _T, size: int = 0) -> None: + super().feed_data(data, size) + self._size += size + + if self._size > self._limit and not self._protocol._reading_paused: + self._protocol.pause_reading() + + async def read(self) -> _T: + if not self._buffer and not self._eof: + assert not self._waiter + self._waiter = self._loop.create_future() + try: + await self._waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._waiter = None + raise + if self._buffer: + data, size = self._buffer.popleft() + self._size -= size + if self._size < self._limit and self._protocol._reading_paused: + self._protocol.resume_reading() + return data + if self._exception is not None: + raise self._exception + raise EofStream diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/tcp_helpers.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/tcp_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..88b244223741ad2decb6cb612eae644fae88b2b2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/tcp_helpers.py @@ -0,0 +1,37 @@ +"""Helper methods to tune a TCP connection""" + +import asyncio +import socket +from contextlib import suppress +from typing import Optional # noqa + +__all__ = ("tcp_keepalive", "tcp_nodelay") + + +if hasattr(socket, "SO_KEEPALIVE"): + + def tcp_keepalive(transport: asyncio.Transport) -> None: + sock = transport.get_extra_info("socket") + if sock is not None: + sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) + +else: + + def tcp_keepalive(transport: asyncio.Transport) -> None: # pragma: no cover + pass + + +def tcp_nodelay(transport: asyncio.Transport, value: bool) -> None: + sock = transport.get_extra_info("socket") + + if sock is None: + return + + if sock.family not in (socket.AF_INET, socket.AF_INET6): + return + + value = bool(value) + + # socket may be closed already, on windows OSError get raised + with suppress(OSError): + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, value) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/test_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..87c31427867f90244c11c8440a5e1f47fc5a079f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/test_utils.py @@ -0,0 +1,774 @@ +"""Utilities shared by tests.""" + +import asyncio +import contextlib +import gc +import inspect +import ipaddress +import os +import socket +import sys +import warnings +from abc import ABC, abstractmethod +from types import TracebackType +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Generic, + Iterator, + List, + Optional, + Type, + TypeVar, + cast, + overload, +) +from unittest import IsolatedAsyncioTestCase, mock + +from aiosignal import Signal +from multidict import CIMultiDict, CIMultiDictProxy +from yarl import URL + +import aiohttp +from aiohttp.client import ( + _RequestContextManager, + _RequestOptions, + _WSRequestContextManager, +) + +from . import ClientSession, hdrs +from .abc import AbstractCookieJar +from .client_reqrep import ClientResponse +from .client_ws import ClientWebSocketResponse +from .helpers import sentinel +from .http import HttpVersion, RawRequestMessage +from .streams import EMPTY_PAYLOAD, StreamReader +from .typedefs import StrOrURL +from .web import ( + Application, + AppRunner, + BaseRequest, + BaseRunner, + Request, + Server, + ServerRunner, + SockSite, + UrlMappingMatchInfo, +) +from .web_protocol import _RequestHandler + +if TYPE_CHECKING: + from ssl import SSLContext +else: + SSLContext = None + +if sys.version_info >= (3, 11) and TYPE_CHECKING: + from typing import Unpack + +if sys.version_info >= (3, 11): + from typing import Self +else: + Self = Any + +_ApplicationNone = TypeVar("_ApplicationNone", Application, None) +_Request = TypeVar("_Request", bound=BaseRequest) + +REUSE_ADDRESS = os.name == "posix" and sys.platform != "cygwin" + + +def get_unused_port_socket( + host: str, family: socket.AddressFamily = socket.AF_INET +) -> socket.socket: + return get_port_socket(host, 0, family) + + +def get_port_socket( + host: str, port: int, family: socket.AddressFamily +) -> socket.socket: + s = socket.socket(family, socket.SOCK_STREAM) + if REUSE_ADDRESS: + # Windows has different semantics for SO_REUSEADDR, + # so don't set it. Ref: + # https://docs.microsoft.com/en-us/windows/win32/winsock/using-so-reuseaddr-and-so-exclusiveaddruse + s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + s.bind((host, port)) + return s + + +def unused_port() -> int: + """Return a port that is unused on the current host.""" + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + s.bind(("127.0.0.1", 0)) + return cast(int, s.getsockname()[1]) + + +class BaseTestServer(ABC): + __test__ = False + + def __init__( + self, + *, + scheme: str = "", + loop: Optional[asyncio.AbstractEventLoop] = None, + host: str = "127.0.0.1", + port: Optional[int] = None, + skip_url_asserts: bool = False, + socket_factory: Callable[ + [str, int, socket.AddressFamily], socket.socket + ] = get_port_socket, + **kwargs: Any, + ) -> None: + self._loop = loop + self.runner: Optional[BaseRunner] = None + self._root: Optional[URL] = None + self.host = host + self.port = port + self._closed = False + self.scheme = scheme + self.skip_url_asserts = skip_url_asserts + self.socket_factory = socket_factory + + async def start_server( + self, loop: Optional[asyncio.AbstractEventLoop] = None, **kwargs: Any + ) -> None: + if self.runner: + return + self._loop = loop + self._ssl = kwargs.pop("ssl", None) + self.runner = await self._make_runner(handler_cancellation=True, **kwargs) + await self.runner.setup() + if not self.port: + self.port = 0 + absolute_host = self.host + try: + version = ipaddress.ip_address(self.host).version + except ValueError: + version = 4 + if version == 6: + absolute_host = f"[{self.host}]" + family = socket.AF_INET6 if version == 6 else socket.AF_INET + _sock = self.socket_factory(self.host, self.port, family) + self.host, self.port = _sock.getsockname()[:2] + site = SockSite(self.runner, sock=_sock, ssl_context=self._ssl) + await site.start() + server = site._server + assert server is not None + sockets = server.sockets # type: ignore[attr-defined] + assert sockets is not None + self.port = sockets[0].getsockname()[1] + if not self.scheme: + self.scheme = "https" if self._ssl else "http" + self._root = URL(f"{self.scheme}://{absolute_host}:{self.port}") + + @abstractmethod # pragma: no cover + async def _make_runner(self, **kwargs: Any) -> BaseRunner: + pass + + def make_url(self, path: StrOrURL) -> URL: + assert self._root is not None + url = URL(path) + if not self.skip_url_asserts: + assert not url.absolute + return self._root.join(url) + else: + return URL(str(self._root) + str(path)) + + @property + def started(self) -> bool: + return self.runner is not None + + @property + def closed(self) -> bool: + return self._closed + + @property + def handler(self) -> Server: + # for backward compatibility + # web.Server instance + runner = self.runner + assert runner is not None + assert runner.server is not None + return runner.server + + async def close(self) -> None: + """Close all fixtures created by the test client. + + After that point, the TestClient is no longer usable. + + This is an idempotent function: running close multiple times + will not have any additional effects. + + close is also run when the object is garbage collected, and on + exit when used as a context manager. + + """ + if self.started and not self.closed: + assert self.runner is not None + await self.runner.cleanup() + self._root = None + self.port = None + self._closed = True + + def __enter__(self) -> None: + raise TypeError("Use async with instead") + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + # __exit__ should exist in pair with __enter__ but never executed + pass # pragma: no cover + + async def __aenter__(self) -> "BaseTestServer": + await self.start_server(loop=self._loop) + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + await self.close() + + +class TestServer(BaseTestServer): + def __init__( + self, + app: Application, + *, + scheme: str = "", + host: str = "127.0.0.1", + port: Optional[int] = None, + **kwargs: Any, + ): + self.app = app + super().__init__(scheme=scheme, host=host, port=port, **kwargs) + + async def _make_runner(self, **kwargs: Any) -> BaseRunner: + return AppRunner(self.app, **kwargs) + + +class RawTestServer(BaseTestServer): + def __init__( + self, + handler: _RequestHandler, + *, + scheme: str = "", + host: str = "127.0.0.1", + port: Optional[int] = None, + **kwargs: Any, + ) -> None: + self._handler = handler + super().__init__(scheme=scheme, host=host, port=port, **kwargs) + + async def _make_runner(self, debug: bool = True, **kwargs: Any) -> ServerRunner: + srv = Server(self._handler, loop=self._loop, debug=debug, **kwargs) + return ServerRunner(srv, debug=debug, **kwargs) + + +class TestClient(Generic[_Request, _ApplicationNone]): + """ + A test client implementation. + + To write functional tests for aiohttp based servers. + + """ + + __test__ = False + + @overload + def __init__( + self: "TestClient[Request, Application]", + server: TestServer, + *, + cookie_jar: Optional[AbstractCookieJar] = None, + **kwargs: Any, + ) -> None: ... + @overload + def __init__( + self: "TestClient[_Request, None]", + server: BaseTestServer, + *, + cookie_jar: Optional[AbstractCookieJar] = None, + **kwargs: Any, + ) -> None: ... + def __init__( + self, + server: BaseTestServer, + *, + cookie_jar: Optional[AbstractCookieJar] = None, + loop: Optional[asyncio.AbstractEventLoop] = None, + **kwargs: Any, + ) -> None: + if not isinstance(server, BaseTestServer): + raise TypeError( + "server must be TestServer instance, found type: %r" % type(server) + ) + self._server = server + self._loop = loop + if cookie_jar is None: + cookie_jar = aiohttp.CookieJar(unsafe=True, loop=loop) + self._session = ClientSession(loop=loop, cookie_jar=cookie_jar, **kwargs) + self._session._retry_connection = False + self._closed = False + self._responses: List[ClientResponse] = [] + self._websockets: List[ClientWebSocketResponse] = [] + + async def start_server(self) -> None: + await self._server.start_server(loop=self._loop) + + @property + def host(self) -> str: + return self._server.host + + @property + def port(self) -> Optional[int]: + return self._server.port + + @property + def server(self) -> BaseTestServer: + return self._server + + @property + def app(self) -> _ApplicationNone: + return getattr(self._server, "app", None) # type: ignore[return-value] + + @property + def session(self) -> ClientSession: + """An internal aiohttp.ClientSession. + + Unlike the methods on the TestClient, client session requests + do not automatically include the host in the url queried, and + will require an absolute path to the resource. + + """ + return self._session + + def make_url(self, path: StrOrURL) -> URL: + return self._server.make_url(path) + + async def _request( + self, method: str, path: StrOrURL, **kwargs: Any + ) -> ClientResponse: + resp = await self._session.request(method, self.make_url(path), **kwargs) + # save it to close later + self._responses.append(resp) + return resp + + if sys.version_info >= (3, 11) and TYPE_CHECKING: + + def request( + self, method: str, path: StrOrURL, **kwargs: Unpack[_RequestOptions] + ) -> _RequestContextManager: ... + + def get( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def options( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def head( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def post( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def put( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def patch( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + def delete( + self, + path: StrOrURL, + **kwargs: Unpack[_RequestOptions], + ) -> _RequestContextManager: ... + + else: + + def request( + self, method: str, path: StrOrURL, **kwargs: Any + ) -> _RequestContextManager: + """Routes a request to tested http server. + + The interface is identical to aiohttp.ClientSession.request, + except the loop kwarg is overridden by the instance used by the + test server. + + """ + return _RequestContextManager(self._request(method, path, **kwargs)) + + def get(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP GET request.""" + return _RequestContextManager(self._request(hdrs.METH_GET, path, **kwargs)) + + def post(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP POST request.""" + return _RequestContextManager(self._request(hdrs.METH_POST, path, **kwargs)) + + def options(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP OPTIONS request.""" + return _RequestContextManager( + self._request(hdrs.METH_OPTIONS, path, **kwargs) + ) + + def head(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP HEAD request.""" + return _RequestContextManager(self._request(hdrs.METH_HEAD, path, **kwargs)) + + def put(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP PUT request.""" + return _RequestContextManager(self._request(hdrs.METH_PUT, path, **kwargs)) + + def patch(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP PATCH request.""" + return _RequestContextManager( + self._request(hdrs.METH_PATCH, path, **kwargs) + ) + + def delete(self, path: StrOrURL, **kwargs: Any) -> _RequestContextManager: + """Perform an HTTP PATCH request.""" + return _RequestContextManager( + self._request(hdrs.METH_DELETE, path, **kwargs) + ) + + def ws_connect(self, path: StrOrURL, **kwargs: Any) -> _WSRequestContextManager: + """Initiate websocket connection. + + The api corresponds to aiohttp.ClientSession.ws_connect. + + """ + return _WSRequestContextManager(self._ws_connect(path, **kwargs)) + + async def _ws_connect( + self, path: StrOrURL, **kwargs: Any + ) -> ClientWebSocketResponse: + ws = await self._session.ws_connect(self.make_url(path), **kwargs) + self._websockets.append(ws) + return ws + + async def close(self) -> None: + """Close all fixtures created by the test client. + + After that point, the TestClient is no longer usable. + + This is an idempotent function: running close multiple times + will not have any additional effects. + + close is also run on exit when used as a(n) (asynchronous) + context manager. + + """ + if not self._closed: + for resp in self._responses: + resp.close() + for ws in self._websockets: + await ws.close() + await self._session.close() + await self._server.close() + self._closed = True + + def __enter__(self) -> None: + raise TypeError("Use async with instead") + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + # __exit__ should exist in pair with __enter__ but never executed + pass # pragma: no cover + + async def __aenter__(self) -> Self: + await self.start_server() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc: Optional[BaseException], + tb: Optional[TracebackType], + ) -> None: + await self.close() + + +class AioHTTPTestCase(IsolatedAsyncioTestCase): + """A base class to allow for unittest web applications using aiohttp. + + Provides the following: + + * self.client (aiohttp.test_utils.TestClient): an aiohttp test client. + * self.loop (asyncio.BaseEventLoop): the event loop in which the + application and server are running. + * self.app (aiohttp.web.Application): the application returned by + self.get_application() + + Note that the TestClient's methods are asynchronous: you have to + execute function on the test client using asynchronous methods. + """ + + async def get_application(self) -> Application: + """Get application. + + This method should be overridden + to return the aiohttp.web.Application + object to test. + """ + return self.get_app() + + def get_app(self) -> Application: + """Obsolete method used to constructing web application. + + Use .get_application() coroutine instead. + """ + raise RuntimeError("Did you forget to define get_application()?") + + async def asyncSetUp(self) -> None: + self.loop = asyncio.get_running_loop() + return await self.setUpAsync() + + async def setUpAsync(self) -> None: + self.app = await self.get_application() + self.server = await self.get_server(self.app) + self.client = await self.get_client(self.server) + + await self.client.start_server() + + async def asyncTearDown(self) -> None: + return await self.tearDownAsync() + + async def tearDownAsync(self) -> None: + await self.client.close() + + async def get_server(self, app: Application) -> TestServer: + """Return a TestServer instance.""" + return TestServer(app, loop=self.loop) + + async def get_client(self, server: TestServer) -> TestClient[Request, Application]: + """Return a TestClient instance.""" + return TestClient(server, loop=self.loop) + + +def unittest_run_loop(func: Any, *args: Any, **kwargs: Any) -> Any: + """ + A decorator dedicated to use with asynchronous AioHTTPTestCase test methods. + + In 3.8+, this does nothing. + """ + warnings.warn( + "Decorator `@unittest_run_loop` is no longer needed in aiohttp 3.8+", + DeprecationWarning, + stacklevel=2, + ) + return func + + +_LOOP_FACTORY = Callable[[], asyncio.AbstractEventLoop] + + +@contextlib.contextmanager +def loop_context( + loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, fast: bool = False +) -> Iterator[asyncio.AbstractEventLoop]: + """A contextmanager that creates an event_loop, for test purposes. + + Handles the creation and cleanup of a test loop. + """ + loop = setup_test_loop(loop_factory) + yield loop + teardown_test_loop(loop, fast=fast) + + +def setup_test_loop( + loop_factory: _LOOP_FACTORY = asyncio.new_event_loop, +) -> asyncio.AbstractEventLoop: + """Create and return an asyncio.BaseEventLoop instance. + + The caller should also call teardown_test_loop, + once they are done with the loop. + """ + loop = loop_factory() + asyncio.set_event_loop(loop) + return loop + + +def teardown_test_loop(loop: asyncio.AbstractEventLoop, fast: bool = False) -> None: + """Teardown and cleanup an event_loop created by setup_test_loop.""" + closed = loop.is_closed() + if not closed: + loop.call_soon(loop.stop) + loop.run_forever() + loop.close() + + if not fast: + gc.collect() + + asyncio.set_event_loop(None) + + +def _create_app_mock() -> mock.MagicMock: + def get_dict(app: Any, key: str) -> Any: + return app.__app_dict[key] + + def set_dict(app: Any, key: str, value: Any) -> None: + app.__app_dict[key] = value + + app = mock.MagicMock(spec=Application) + app.__app_dict = {} + app.__getitem__ = get_dict + app.__setitem__ = set_dict + + app._debug = False + app.on_response_prepare = Signal(app) + app.on_response_prepare.freeze() + return app + + +def _create_transport(sslcontext: Optional[SSLContext] = None) -> mock.Mock: + transport = mock.Mock() + + def get_extra_info(key: str) -> Optional[SSLContext]: + if key == "sslcontext": + return sslcontext + else: + return None + + transport.get_extra_info.side_effect = get_extra_info + return transport + + +def make_mocked_request( + method: str, + path: str, + headers: Any = None, + *, + match_info: Any = sentinel, + version: HttpVersion = HttpVersion(1, 1), + closing: bool = False, + app: Any = None, + writer: Any = sentinel, + protocol: Any = sentinel, + transport: Any = sentinel, + payload: StreamReader = EMPTY_PAYLOAD, + sslcontext: Optional[SSLContext] = None, + client_max_size: int = 1024**2, + loop: Any = ..., +) -> Request: + """Creates mocked web.Request testing purposes. + + Useful in unit tests, when spinning full web server is overkill or + specific conditions and errors are hard to trigger. + """ + task = mock.Mock() + if loop is ...: + # no loop passed, try to get the current one if + # its is running as we need a real loop to create + # executor jobs to be able to do testing + # with a real executor + try: + loop = asyncio.get_running_loop() + except RuntimeError: + loop = mock.Mock() + loop.create_future.return_value = () + + if version < HttpVersion(1, 1): + closing = True + + if headers: + headers = CIMultiDictProxy(CIMultiDict(headers)) + raw_hdrs = tuple( + (k.encode("utf-8"), v.encode("utf-8")) for k, v in headers.items() + ) + else: + headers = CIMultiDictProxy(CIMultiDict()) + raw_hdrs = () + + chunked = "chunked" in headers.get(hdrs.TRANSFER_ENCODING, "").lower() + + message = RawRequestMessage( + method, + path, + version, + headers, + raw_hdrs, + closing, + None, + False, + chunked, + URL(path), + ) + if app is None: + app = _create_app_mock() + + if transport is sentinel: + transport = _create_transport(sslcontext) + + if protocol is sentinel: + protocol = mock.Mock() + protocol.transport = transport + type(protocol).peername = mock.PropertyMock( + return_value=transport.get_extra_info("peername") + ) + type(protocol).ssl_context = mock.PropertyMock(return_value=sslcontext) + + if writer is sentinel: + writer = mock.Mock() + writer.write_headers = make_mocked_coro(None) + writer.write = make_mocked_coro(None) + writer.write_eof = make_mocked_coro(None) + writer.drain = make_mocked_coro(None) + writer.transport = transport + + protocol.transport = transport + protocol.writer = writer + + req = Request( + message, payload, protocol, writer, task, loop, client_max_size=client_max_size + ) + + match_info = UrlMappingMatchInfo( + {} if match_info is sentinel else match_info, mock.Mock() + ) + match_info.add_app(app) + req._match_info = match_info + + return req + + +def make_mocked_coro( + return_value: Any = sentinel, raise_exception: Any = sentinel +) -> Any: + """Creates a coroutine mock.""" + + async def mock_coro(*args: Any, **kwargs: Any) -> Any: + if raise_exception is not sentinel: + raise raise_exception + if not inspect.isawaitable(return_value): + return return_value + await return_value + + return mock.Mock(wraps=mock_coro) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/tracing.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/tracing.py new file mode 100644 index 0000000000000000000000000000000000000000..568fa7f9e38090e0c0a4738db4d51656ce31b99a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/tracing.py @@ -0,0 +1,455 @@ +from types import SimpleNamespace +from typing import TYPE_CHECKING, Mapping, Optional, Type, TypeVar + +import attr +from aiosignal import Signal +from multidict import CIMultiDict +from yarl import URL + +from .client_reqrep import ClientResponse + +if TYPE_CHECKING: + from .client import ClientSession + + _ParamT_contra = TypeVar("_ParamT_contra", contravariant=True) + _TracingSignal = Signal[ClientSession, SimpleNamespace, _ParamT_contra] + + +__all__ = ( + "TraceConfig", + "TraceRequestStartParams", + "TraceRequestEndParams", + "TraceRequestExceptionParams", + "TraceConnectionQueuedStartParams", + "TraceConnectionQueuedEndParams", + "TraceConnectionCreateStartParams", + "TraceConnectionCreateEndParams", + "TraceConnectionReuseconnParams", + "TraceDnsResolveHostStartParams", + "TraceDnsResolveHostEndParams", + "TraceDnsCacheHitParams", + "TraceDnsCacheMissParams", + "TraceRequestRedirectParams", + "TraceRequestChunkSentParams", + "TraceResponseChunkReceivedParams", + "TraceRequestHeadersSentParams", +) + + +class TraceConfig: + """First-class used to trace requests launched via ClientSession objects.""" + + def __init__( + self, trace_config_ctx_factory: Type[SimpleNamespace] = SimpleNamespace + ) -> None: + self._on_request_start: _TracingSignal[TraceRequestStartParams] = Signal(self) + self._on_request_chunk_sent: _TracingSignal[TraceRequestChunkSentParams] = ( + Signal(self) + ) + self._on_response_chunk_received: _TracingSignal[ + TraceResponseChunkReceivedParams + ] = Signal(self) + self._on_request_end: _TracingSignal[TraceRequestEndParams] = Signal(self) + self._on_request_exception: _TracingSignal[TraceRequestExceptionParams] = ( + Signal(self) + ) + self._on_request_redirect: _TracingSignal[TraceRequestRedirectParams] = Signal( + self + ) + self._on_connection_queued_start: _TracingSignal[ + TraceConnectionQueuedStartParams + ] = Signal(self) + self._on_connection_queued_end: _TracingSignal[ + TraceConnectionQueuedEndParams + ] = Signal(self) + self._on_connection_create_start: _TracingSignal[ + TraceConnectionCreateStartParams + ] = Signal(self) + self._on_connection_create_end: _TracingSignal[ + TraceConnectionCreateEndParams + ] = Signal(self) + self._on_connection_reuseconn: _TracingSignal[ + TraceConnectionReuseconnParams + ] = Signal(self) + self._on_dns_resolvehost_start: _TracingSignal[ + TraceDnsResolveHostStartParams + ] = Signal(self) + self._on_dns_resolvehost_end: _TracingSignal[TraceDnsResolveHostEndParams] = ( + Signal(self) + ) + self._on_dns_cache_hit: _TracingSignal[TraceDnsCacheHitParams] = Signal(self) + self._on_dns_cache_miss: _TracingSignal[TraceDnsCacheMissParams] = Signal(self) + self._on_request_headers_sent: _TracingSignal[TraceRequestHeadersSentParams] = ( + Signal(self) + ) + + self._trace_config_ctx_factory = trace_config_ctx_factory + + def trace_config_ctx( + self, trace_request_ctx: Optional[Mapping[str, str]] = None + ) -> SimpleNamespace: + """Return a new trace_config_ctx instance""" + return self._trace_config_ctx_factory(trace_request_ctx=trace_request_ctx) + + def freeze(self) -> None: + self._on_request_start.freeze() + self._on_request_chunk_sent.freeze() + self._on_response_chunk_received.freeze() + self._on_request_end.freeze() + self._on_request_exception.freeze() + self._on_request_redirect.freeze() + self._on_connection_queued_start.freeze() + self._on_connection_queued_end.freeze() + self._on_connection_create_start.freeze() + self._on_connection_create_end.freeze() + self._on_connection_reuseconn.freeze() + self._on_dns_resolvehost_start.freeze() + self._on_dns_resolvehost_end.freeze() + self._on_dns_cache_hit.freeze() + self._on_dns_cache_miss.freeze() + self._on_request_headers_sent.freeze() + + @property + def on_request_start(self) -> "_TracingSignal[TraceRequestStartParams]": + return self._on_request_start + + @property + def on_request_chunk_sent( + self, + ) -> "_TracingSignal[TraceRequestChunkSentParams]": + return self._on_request_chunk_sent + + @property + def on_response_chunk_received( + self, + ) -> "_TracingSignal[TraceResponseChunkReceivedParams]": + return self._on_response_chunk_received + + @property + def on_request_end(self) -> "_TracingSignal[TraceRequestEndParams]": + return self._on_request_end + + @property + def on_request_exception( + self, + ) -> "_TracingSignal[TraceRequestExceptionParams]": + return self._on_request_exception + + @property + def on_request_redirect( + self, + ) -> "_TracingSignal[TraceRequestRedirectParams]": + return self._on_request_redirect + + @property + def on_connection_queued_start( + self, + ) -> "_TracingSignal[TraceConnectionQueuedStartParams]": + return self._on_connection_queued_start + + @property + def on_connection_queued_end( + self, + ) -> "_TracingSignal[TraceConnectionQueuedEndParams]": + return self._on_connection_queued_end + + @property + def on_connection_create_start( + self, + ) -> "_TracingSignal[TraceConnectionCreateStartParams]": + return self._on_connection_create_start + + @property + def on_connection_create_end( + self, + ) -> "_TracingSignal[TraceConnectionCreateEndParams]": + return self._on_connection_create_end + + @property + def on_connection_reuseconn( + self, + ) -> "_TracingSignal[TraceConnectionReuseconnParams]": + return self._on_connection_reuseconn + + @property + def on_dns_resolvehost_start( + self, + ) -> "_TracingSignal[TraceDnsResolveHostStartParams]": + return self._on_dns_resolvehost_start + + @property + def on_dns_resolvehost_end( + self, + ) -> "_TracingSignal[TraceDnsResolveHostEndParams]": + return self._on_dns_resolvehost_end + + @property + def on_dns_cache_hit(self) -> "_TracingSignal[TraceDnsCacheHitParams]": + return self._on_dns_cache_hit + + @property + def on_dns_cache_miss(self) -> "_TracingSignal[TraceDnsCacheMissParams]": + return self._on_dns_cache_miss + + @property + def on_request_headers_sent( + self, + ) -> "_TracingSignal[TraceRequestHeadersSentParams]": + return self._on_request_headers_sent + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestStartParams: + """Parameters sent by the `on_request_start` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestChunkSentParams: + """Parameters sent by the `on_request_chunk_sent` signal""" + + method: str + url: URL + chunk: bytes + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceResponseChunkReceivedParams: + """Parameters sent by the `on_response_chunk_received` signal""" + + method: str + url: URL + chunk: bytes + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestEndParams: + """Parameters sent by the `on_request_end` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + response: ClientResponse + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestExceptionParams: + """Parameters sent by the `on_request_exception` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + exception: BaseException + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestRedirectParams: + """Parameters sent by the `on_request_redirect` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + response: ClientResponse + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionQueuedStartParams: + """Parameters sent by the `on_connection_queued_start` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionQueuedEndParams: + """Parameters sent by the `on_connection_queued_end` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionCreateStartParams: + """Parameters sent by the `on_connection_create_start` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionCreateEndParams: + """Parameters sent by the `on_connection_create_end` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceConnectionReuseconnParams: + """Parameters sent by the `on_connection_reuseconn` signal""" + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsResolveHostStartParams: + """Parameters sent by the `on_dns_resolvehost_start` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsResolveHostEndParams: + """Parameters sent by the `on_dns_resolvehost_end` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsCacheHitParams: + """Parameters sent by the `on_dns_cache_hit` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceDnsCacheMissParams: + """Parameters sent by the `on_dns_cache_miss` signal""" + + host: str + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class TraceRequestHeadersSentParams: + """Parameters sent by the `on_request_headers_sent` signal""" + + method: str + url: URL + headers: "CIMultiDict[str]" + + +class Trace: + """Internal dependency holder class. + + Used to keep together the main dependencies used + at the moment of send a signal. + """ + + def __init__( + self, + session: "ClientSession", + trace_config: TraceConfig, + trace_config_ctx: SimpleNamespace, + ) -> None: + self._trace_config = trace_config + self._trace_config_ctx = trace_config_ctx + self._session = session + + async def send_request_start( + self, method: str, url: URL, headers: "CIMultiDict[str]" + ) -> None: + return await self._trace_config.on_request_start.send( + self._session, + self._trace_config_ctx, + TraceRequestStartParams(method, url, headers), + ) + + async def send_request_chunk_sent( + self, method: str, url: URL, chunk: bytes + ) -> None: + return await self._trace_config.on_request_chunk_sent.send( + self._session, + self._trace_config_ctx, + TraceRequestChunkSentParams(method, url, chunk), + ) + + async def send_response_chunk_received( + self, method: str, url: URL, chunk: bytes + ) -> None: + return await self._trace_config.on_response_chunk_received.send( + self._session, + self._trace_config_ctx, + TraceResponseChunkReceivedParams(method, url, chunk), + ) + + async def send_request_end( + self, + method: str, + url: URL, + headers: "CIMultiDict[str]", + response: ClientResponse, + ) -> None: + return await self._trace_config.on_request_end.send( + self._session, + self._trace_config_ctx, + TraceRequestEndParams(method, url, headers, response), + ) + + async def send_request_exception( + self, + method: str, + url: URL, + headers: "CIMultiDict[str]", + exception: BaseException, + ) -> None: + return await self._trace_config.on_request_exception.send( + self._session, + self._trace_config_ctx, + TraceRequestExceptionParams(method, url, headers, exception), + ) + + async def send_request_redirect( + self, + method: str, + url: URL, + headers: "CIMultiDict[str]", + response: ClientResponse, + ) -> None: + return await self._trace_config._on_request_redirect.send( + self._session, + self._trace_config_ctx, + TraceRequestRedirectParams(method, url, headers, response), + ) + + async def send_connection_queued_start(self) -> None: + return await self._trace_config.on_connection_queued_start.send( + self._session, self._trace_config_ctx, TraceConnectionQueuedStartParams() + ) + + async def send_connection_queued_end(self) -> None: + return await self._trace_config.on_connection_queued_end.send( + self._session, self._trace_config_ctx, TraceConnectionQueuedEndParams() + ) + + async def send_connection_create_start(self) -> None: + return await self._trace_config.on_connection_create_start.send( + self._session, self._trace_config_ctx, TraceConnectionCreateStartParams() + ) + + async def send_connection_create_end(self) -> None: + return await self._trace_config.on_connection_create_end.send( + self._session, self._trace_config_ctx, TraceConnectionCreateEndParams() + ) + + async def send_connection_reuseconn(self) -> None: + return await self._trace_config.on_connection_reuseconn.send( + self._session, self._trace_config_ctx, TraceConnectionReuseconnParams() + ) + + async def send_dns_resolvehost_start(self, host: str) -> None: + return await self._trace_config.on_dns_resolvehost_start.send( + self._session, self._trace_config_ctx, TraceDnsResolveHostStartParams(host) + ) + + async def send_dns_resolvehost_end(self, host: str) -> None: + return await self._trace_config.on_dns_resolvehost_end.send( + self._session, self._trace_config_ctx, TraceDnsResolveHostEndParams(host) + ) + + async def send_dns_cache_hit(self, host: str) -> None: + return await self._trace_config.on_dns_cache_hit.send( + self._session, self._trace_config_ctx, TraceDnsCacheHitParams(host) + ) + + async def send_dns_cache_miss(self, host: str) -> None: + return await self._trace_config.on_dns_cache_miss.send( + self._session, self._trace_config_ctx, TraceDnsCacheMissParams(host) + ) + + async def send_request_headers( + self, method: str, url: URL, headers: "CIMultiDict[str]" + ) -> None: + return await self._trace_config._on_request_headers_sent.send( + self._session, + self._trace_config_ctx, + TraceRequestHeadersSentParams(method, url, headers), + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/typedefs.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/typedefs.py new file mode 100644 index 0000000000000000000000000000000000000000..cc8c0825b4e522f7d1b6cf0058564f322fb5a905 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/typedefs.py @@ -0,0 +1,69 @@ +import json +import os +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Iterable, + Mapping, + Protocol, + Tuple, + Union, +) + +from multidict import CIMultiDict, CIMultiDictProxy, MultiDict, MultiDictProxy, istr +from yarl import URL, Query as _Query + +Query = _Query + +DEFAULT_JSON_ENCODER = json.dumps +DEFAULT_JSON_DECODER = json.loads + +if TYPE_CHECKING: + _CIMultiDict = CIMultiDict[str] + _CIMultiDictProxy = CIMultiDictProxy[str] + _MultiDict = MultiDict[str] + _MultiDictProxy = MultiDictProxy[str] + from http.cookies import BaseCookie, Morsel + + from .web import Request, StreamResponse +else: + _CIMultiDict = CIMultiDict + _CIMultiDictProxy = CIMultiDictProxy + _MultiDict = MultiDict + _MultiDictProxy = MultiDictProxy + +Byteish = Union[bytes, bytearray, memoryview] +JSONEncoder = Callable[[Any], str] +JSONDecoder = Callable[[str], Any] +LooseHeaders = Union[ + Mapping[str, str], + Mapping[istr, str], + _CIMultiDict, + _CIMultiDictProxy, + Iterable[Tuple[Union[str, istr], str]], +] +RawHeaders = Tuple[Tuple[bytes, bytes], ...] +StrOrURL = Union[str, URL] + +LooseCookiesMappings = Mapping[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]] +LooseCookiesIterables = Iterable[ + Tuple[str, Union[str, "BaseCookie[str]", "Morsel[Any]"]] +] +LooseCookies = Union[ + LooseCookiesMappings, + LooseCookiesIterables, + "BaseCookie[str]", +] + +Handler = Callable[["Request"], Awaitable["StreamResponse"]] + + +class Middleware(Protocol): + def __call__( + self, request: "Request", handler: Handler + ) -> Awaitable["StreamResponse"]: ... + + +PathLike = Union[str, "os.PathLike[str]"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web.py new file mode 100644 index 0000000000000000000000000000000000000000..8307ff405caa9cfcad90da96713a0477cd9a1608 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web.py @@ -0,0 +1,605 @@ +import asyncio +import logging +import os +import socket +import sys +import warnings +from argparse import ArgumentParser +from collections.abc import Iterable +from contextlib import suppress +from importlib import import_module +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Iterable as TypingIterable, + List, + Optional, + Set, + Type, + Union, + cast, +) + +from .abc import AbstractAccessLogger +from .helpers import AppKey as AppKey +from .log import access_logger +from .typedefs import PathLike +from .web_app import Application as Application, CleanupError as CleanupError +from .web_exceptions import ( + HTTPAccepted as HTTPAccepted, + HTTPBadGateway as HTTPBadGateway, + HTTPBadRequest as HTTPBadRequest, + HTTPClientError as HTTPClientError, + HTTPConflict as HTTPConflict, + HTTPCreated as HTTPCreated, + HTTPError as HTTPError, + HTTPException as HTTPException, + HTTPExpectationFailed as HTTPExpectationFailed, + HTTPFailedDependency as HTTPFailedDependency, + HTTPForbidden as HTTPForbidden, + HTTPFound as HTTPFound, + HTTPGatewayTimeout as HTTPGatewayTimeout, + HTTPGone as HTTPGone, + HTTPInsufficientStorage as HTTPInsufficientStorage, + HTTPInternalServerError as HTTPInternalServerError, + HTTPLengthRequired as HTTPLengthRequired, + HTTPMethodNotAllowed as HTTPMethodNotAllowed, + HTTPMisdirectedRequest as HTTPMisdirectedRequest, + HTTPMove as HTTPMove, + HTTPMovedPermanently as HTTPMovedPermanently, + HTTPMultipleChoices as HTTPMultipleChoices, + HTTPNetworkAuthenticationRequired as HTTPNetworkAuthenticationRequired, + HTTPNoContent as HTTPNoContent, + HTTPNonAuthoritativeInformation as HTTPNonAuthoritativeInformation, + HTTPNotAcceptable as HTTPNotAcceptable, + HTTPNotExtended as HTTPNotExtended, + HTTPNotFound as HTTPNotFound, + HTTPNotImplemented as HTTPNotImplemented, + HTTPNotModified as HTTPNotModified, + HTTPOk as HTTPOk, + HTTPPartialContent as HTTPPartialContent, + HTTPPaymentRequired as HTTPPaymentRequired, + HTTPPermanentRedirect as HTTPPermanentRedirect, + HTTPPreconditionFailed as HTTPPreconditionFailed, + HTTPPreconditionRequired as HTTPPreconditionRequired, + HTTPProxyAuthenticationRequired as HTTPProxyAuthenticationRequired, + HTTPRedirection as HTTPRedirection, + HTTPRequestEntityTooLarge as HTTPRequestEntityTooLarge, + HTTPRequestHeaderFieldsTooLarge as HTTPRequestHeaderFieldsTooLarge, + HTTPRequestRangeNotSatisfiable as HTTPRequestRangeNotSatisfiable, + HTTPRequestTimeout as HTTPRequestTimeout, + HTTPRequestURITooLong as HTTPRequestURITooLong, + HTTPResetContent as HTTPResetContent, + HTTPSeeOther as HTTPSeeOther, + HTTPServerError as HTTPServerError, + HTTPServiceUnavailable as HTTPServiceUnavailable, + HTTPSuccessful as HTTPSuccessful, + HTTPTemporaryRedirect as HTTPTemporaryRedirect, + HTTPTooManyRequests as HTTPTooManyRequests, + HTTPUnauthorized as HTTPUnauthorized, + HTTPUnavailableForLegalReasons as HTTPUnavailableForLegalReasons, + HTTPUnprocessableEntity as HTTPUnprocessableEntity, + HTTPUnsupportedMediaType as HTTPUnsupportedMediaType, + HTTPUpgradeRequired as HTTPUpgradeRequired, + HTTPUseProxy as HTTPUseProxy, + HTTPVariantAlsoNegotiates as HTTPVariantAlsoNegotiates, + HTTPVersionNotSupported as HTTPVersionNotSupported, + NotAppKeyWarning as NotAppKeyWarning, +) +from .web_fileresponse import FileResponse as FileResponse +from .web_log import AccessLogger +from .web_middlewares import ( + middleware as middleware, + normalize_path_middleware as normalize_path_middleware, +) +from .web_protocol import ( + PayloadAccessError as PayloadAccessError, + RequestHandler as RequestHandler, + RequestPayloadError as RequestPayloadError, +) +from .web_request import ( + BaseRequest as BaseRequest, + FileField as FileField, + Request as Request, +) +from .web_response import ( + ContentCoding as ContentCoding, + Response as Response, + StreamResponse as StreamResponse, + json_response as json_response, +) +from .web_routedef import ( + AbstractRouteDef as AbstractRouteDef, + RouteDef as RouteDef, + RouteTableDef as RouteTableDef, + StaticDef as StaticDef, + delete as delete, + get as get, + head as head, + options as options, + patch as patch, + post as post, + put as put, + route as route, + static as static, + view as view, +) +from .web_runner import ( + AppRunner as AppRunner, + BaseRunner as BaseRunner, + BaseSite as BaseSite, + GracefulExit as GracefulExit, + NamedPipeSite as NamedPipeSite, + ServerRunner as ServerRunner, + SockSite as SockSite, + TCPSite as TCPSite, + UnixSite as UnixSite, +) +from .web_server import Server as Server +from .web_urldispatcher import ( + AbstractResource as AbstractResource, + AbstractRoute as AbstractRoute, + DynamicResource as DynamicResource, + PlainResource as PlainResource, + PrefixedSubAppResource as PrefixedSubAppResource, + Resource as Resource, + ResourceRoute as ResourceRoute, + StaticResource as StaticResource, + UrlDispatcher as UrlDispatcher, + UrlMappingMatchInfo as UrlMappingMatchInfo, + View as View, +) +from .web_ws import ( + WebSocketReady as WebSocketReady, + WebSocketResponse as WebSocketResponse, + WSMsgType as WSMsgType, +) + +__all__ = ( + # web_app + "AppKey", + "Application", + "CleanupError", + # web_exceptions + "NotAppKeyWarning", + "HTTPAccepted", + "HTTPBadGateway", + "HTTPBadRequest", + "HTTPClientError", + "HTTPConflict", + "HTTPCreated", + "HTTPError", + "HTTPException", + "HTTPExpectationFailed", + "HTTPFailedDependency", + "HTTPForbidden", + "HTTPFound", + "HTTPGatewayTimeout", + "HTTPGone", + "HTTPInsufficientStorage", + "HTTPInternalServerError", + "HTTPLengthRequired", + "HTTPMethodNotAllowed", + "HTTPMisdirectedRequest", + "HTTPMove", + "HTTPMovedPermanently", + "HTTPMultipleChoices", + "HTTPNetworkAuthenticationRequired", + "HTTPNoContent", + "HTTPNonAuthoritativeInformation", + "HTTPNotAcceptable", + "HTTPNotExtended", + "HTTPNotFound", + "HTTPNotImplemented", + "HTTPNotModified", + "HTTPOk", + "HTTPPartialContent", + "HTTPPaymentRequired", + "HTTPPermanentRedirect", + "HTTPPreconditionFailed", + "HTTPPreconditionRequired", + "HTTPProxyAuthenticationRequired", + "HTTPRedirection", + "HTTPRequestEntityTooLarge", + "HTTPRequestHeaderFieldsTooLarge", + "HTTPRequestRangeNotSatisfiable", + "HTTPRequestTimeout", + "HTTPRequestURITooLong", + "HTTPResetContent", + "HTTPSeeOther", + "HTTPServerError", + "HTTPServiceUnavailable", + "HTTPSuccessful", + "HTTPTemporaryRedirect", + "HTTPTooManyRequests", + "HTTPUnauthorized", + "HTTPUnavailableForLegalReasons", + "HTTPUnprocessableEntity", + "HTTPUnsupportedMediaType", + "HTTPUpgradeRequired", + "HTTPUseProxy", + "HTTPVariantAlsoNegotiates", + "HTTPVersionNotSupported", + # web_fileresponse + "FileResponse", + # web_middlewares + "middleware", + "normalize_path_middleware", + # web_protocol + "PayloadAccessError", + "RequestHandler", + "RequestPayloadError", + # web_request + "BaseRequest", + "FileField", + "Request", + # web_response + "ContentCoding", + "Response", + "StreamResponse", + "json_response", + # web_routedef + "AbstractRouteDef", + "RouteDef", + "RouteTableDef", + "StaticDef", + "delete", + "get", + "head", + "options", + "patch", + "post", + "put", + "route", + "static", + "view", + # web_runner + "AppRunner", + "BaseRunner", + "BaseSite", + "GracefulExit", + "ServerRunner", + "SockSite", + "TCPSite", + "UnixSite", + "NamedPipeSite", + # web_server + "Server", + # web_urldispatcher + "AbstractResource", + "AbstractRoute", + "DynamicResource", + "PlainResource", + "PrefixedSubAppResource", + "Resource", + "ResourceRoute", + "StaticResource", + "UrlDispatcher", + "UrlMappingMatchInfo", + "View", + # web_ws + "WebSocketReady", + "WebSocketResponse", + "WSMsgType", + # web + "run_app", +) + + +if TYPE_CHECKING: + from ssl import SSLContext +else: + try: + from ssl import SSLContext + except ImportError: # pragma: no cover + SSLContext = object # type: ignore[misc,assignment] + +# Only display warning when using -Wdefault, -We, -X dev or similar. +warnings.filterwarnings("ignore", category=NotAppKeyWarning, append=True) + +HostSequence = TypingIterable[str] + + +async def _run_app( + app: Union[Application, Awaitable[Application]], + *, + host: Optional[Union[str, HostSequence]] = None, + port: Optional[int] = None, + path: Union[PathLike, TypingIterable[PathLike], None] = None, + sock: Optional[Union[socket.socket, TypingIterable[socket.socket]]] = None, + shutdown_timeout: float = 60.0, + keepalive_timeout: float = 75.0, + ssl_context: Optional[SSLContext] = None, + print: Optional[Callable[..., None]] = print, + backlog: int = 128, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + access_log_format: str = AccessLogger.LOG_FORMAT, + access_log: Optional[logging.Logger] = access_logger, + handle_signals: bool = True, + reuse_address: Optional[bool] = None, + reuse_port: Optional[bool] = None, + handler_cancellation: bool = False, +) -> None: + # An internal function to actually do all dirty job for application running + if asyncio.iscoroutine(app): + app = await app + + app = cast(Application, app) + + runner = AppRunner( + app, + handle_signals=handle_signals, + access_log_class=access_log_class, + access_log_format=access_log_format, + access_log=access_log, + keepalive_timeout=keepalive_timeout, + shutdown_timeout=shutdown_timeout, + handler_cancellation=handler_cancellation, + ) + + await runner.setup() + + sites: List[BaseSite] = [] + + try: + if host is not None: + if isinstance(host, str): + sites.append( + TCPSite( + runner, + host, + port, + ssl_context=ssl_context, + backlog=backlog, + reuse_address=reuse_address, + reuse_port=reuse_port, + ) + ) + else: + for h in host: + sites.append( + TCPSite( + runner, + h, + port, + ssl_context=ssl_context, + backlog=backlog, + reuse_address=reuse_address, + reuse_port=reuse_port, + ) + ) + elif path is None and sock is None or port is not None: + sites.append( + TCPSite( + runner, + port=port, + ssl_context=ssl_context, + backlog=backlog, + reuse_address=reuse_address, + reuse_port=reuse_port, + ) + ) + + if path is not None: + if isinstance(path, (str, os.PathLike)): + sites.append( + UnixSite( + runner, + path, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + else: + for p in path: + sites.append( + UnixSite( + runner, + p, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + + if sock is not None: + if not isinstance(sock, Iterable): + sites.append( + SockSite( + runner, + sock, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + else: + for s in sock: + sites.append( + SockSite( + runner, + s, + ssl_context=ssl_context, + backlog=backlog, + ) + ) + for site in sites: + await site.start() + + if print: # pragma: no branch + names = sorted(str(s.name) for s in runner.sites) + print( + "======== Running on {} ========\n" + "(Press CTRL+C to quit)".format(", ".join(names)) + ) + + # sleep forever by 1 hour intervals, + while True: + await asyncio.sleep(3600) + finally: + await runner.cleanup() + + +def _cancel_tasks( + to_cancel: Set["asyncio.Task[Any]"], loop: asyncio.AbstractEventLoop +) -> None: + if not to_cancel: + return + + for task in to_cancel: + task.cancel() + + loop.run_until_complete(asyncio.gather(*to_cancel, return_exceptions=True)) + + for task in to_cancel: + if task.cancelled(): + continue + if task.exception() is not None: + loop.call_exception_handler( + { + "message": "unhandled exception during asyncio.run() shutdown", + "exception": task.exception(), + "task": task, + } + ) + + +def run_app( + app: Union[Application, Awaitable[Application]], + *, + host: Optional[Union[str, HostSequence]] = None, + port: Optional[int] = None, + path: Union[PathLike, TypingIterable[PathLike], None] = None, + sock: Optional[Union[socket.socket, TypingIterable[socket.socket]]] = None, + shutdown_timeout: float = 60.0, + keepalive_timeout: float = 75.0, + ssl_context: Optional[SSLContext] = None, + print: Optional[Callable[..., None]] = print, + backlog: int = 128, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + access_log_format: str = AccessLogger.LOG_FORMAT, + access_log: Optional[logging.Logger] = access_logger, + handle_signals: bool = True, + reuse_address: Optional[bool] = None, + reuse_port: Optional[bool] = None, + handler_cancellation: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, +) -> None: + """Run an app locally""" + if loop is None: + loop = asyncio.new_event_loop() + + # Configure if and only if in debugging mode and using the default logger + if loop.get_debug() and access_log and access_log.name == "aiohttp.access": + if access_log.level == logging.NOTSET: + access_log.setLevel(logging.DEBUG) + if not access_log.hasHandlers(): + access_log.addHandler(logging.StreamHandler()) + + main_task = loop.create_task( + _run_app( + app, + host=host, + port=port, + path=path, + sock=sock, + shutdown_timeout=shutdown_timeout, + keepalive_timeout=keepalive_timeout, + ssl_context=ssl_context, + print=print, + backlog=backlog, + access_log_class=access_log_class, + access_log_format=access_log_format, + access_log=access_log, + handle_signals=handle_signals, + reuse_address=reuse_address, + reuse_port=reuse_port, + handler_cancellation=handler_cancellation, + ) + ) + + try: + asyncio.set_event_loop(loop) + loop.run_until_complete(main_task) + except (GracefulExit, KeyboardInterrupt): # pragma: no cover + pass + finally: + try: + main_task.cancel() + with suppress(asyncio.CancelledError): + loop.run_until_complete(main_task) + finally: + _cancel_tasks(asyncio.all_tasks(loop), loop) + loop.run_until_complete(loop.shutdown_asyncgens()) + loop.close() + + +def main(argv: List[str]) -> None: + arg_parser = ArgumentParser( + description="aiohttp.web Application server", prog="aiohttp.web" + ) + arg_parser.add_argument( + "entry_func", + help=( + "Callable returning the `aiohttp.web.Application` instance to " + "run. Should be specified in the 'module:function' syntax." + ), + metavar="entry-func", + ) + arg_parser.add_argument( + "-H", + "--hostname", + help="TCP/IP hostname to serve on (default: localhost)", + default=None, + ) + arg_parser.add_argument( + "-P", + "--port", + help="TCP/IP port to serve on (default: %(default)r)", + type=int, + default=8080, + ) + arg_parser.add_argument( + "-U", + "--path", + help="Unix file system path to serve on. Can be combined with hostname " + "to serve on both Unix and TCP.", + ) + args, extra_argv = arg_parser.parse_known_args(argv) + + # Import logic + mod_str, _, func_str = args.entry_func.partition(":") + if not func_str or not mod_str: + arg_parser.error("'entry-func' not in 'module:function' syntax") + if mod_str.startswith("."): + arg_parser.error("relative module names not supported") + try: + module = import_module(mod_str) + except ImportError as ex: + arg_parser.error(f"unable to import {mod_str}: {ex}") + try: + func = getattr(module, func_str) + except AttributeError: + arg_parser.error(f"module {mod_str!r} has no attribute {func_str!r}") + + # Compatibility logic + if args.path is not None and not hasattr(socket, "AF_UNIX"): + arg_parser.error( + "file system paths not supported by your operating environment" + ) + + logging.basicConfig(level=logging.DEBUG) + + if args.path and args.hostname is None: + host = port = None + else: + host = args.hostname or "localhost" + port = args.port + + app = func(extra_argv) + run_app(app, host=host, port=port, path=args.path) + arg_parser.exit(message="Stopped\n") + + +if __name__ == "__main__": # pragma: no branch + main(sys.argv[1:]) # pragma: no cover diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_app.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_app.py new file mode 100644 index 0000000000000000000000000000000000000000..619c0085da1985b97f7e222d30c1870cb010a128 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_app.py @@ -0,0 +1,620 @@ +import asyncio +import logging +import warnings +from functools import lru_cache, partial, update_wrapper +from typing import ( + TYPE_CHECKING, + Any, + AsyncIterator, + Awaitable, + Callable, + Dict, + Iterable, + Iterator, + List, + Mapping, + MutableMapping, + Optional, + Sequence, + Tuple, + Type, + TypeVar, + Union, + cast, + overload, +) + +from aiosignal import Signal +from frozenlist import FrozenList + +from . import hdrs +from .abc import ( + AbstractAccessLogger, + AbstractMatchInfo, + AbstractRouter, + AbstractStreamWriter, +) +from .helpers import DEBUG, AppKey +from .http_parser import RawRequestMessage +from .log import web_logger +from .streams import StreamReader +from .typedefs import Handler, Middleware +from .web_exceptions import NotAppKeyWarning +from .web_log import AccessLogger +from .web_middlewares import _fix_request_current_app +from .web_protocol import RequestHandler +from .web_request import Request +from .web_response import StreamResponse +from .web_routedef import AbstractRouteDef +from .web_server import Server +from .web_urldispatcher import ( + AbstractResource, + AbstractRoute, + Domain, + MaskDomain, + MatchedSubAppResource, + PrefixedSubAppResource, + SystemRoute, + UrlDispatcher, +) + +__all__ = ("Application", "CleanupError") + + +if TYPE_CHECKING: + _AppSignal = Signal["Application"] + _RespPrepareSignal = Signal[Request, StreamResponse] + _Middlewares = FrozenList[Middleware] + _MiddlewaresHandlers = Optional[Sequence[Tuple[Middleware, bool]]] + _Subapps = List["Application"] +else: + # No type checker mode, skip types + _AppSignal = Signal + _RespPrepareSignal = Signal + _Middlewares = FrozenList + _MiddlewaresHandlers = Optional[Sequence] + _Subapps = List + +_T = TypeVar("_T") +_U = TypeVar("_U") +_Resource = TypeVar("_Resource", bound=AbstractResource) + + +def _build_middlewares( + handler: Handler, apps: Tuple["Application", ...] +) -> Callable[[Request], Awaitable[StreamResponse]]: + """Apply middlewares to handler.""" + for app in apps[::-1]: + for m, _ in app._middlewares_handlers: # type: ignore[union-attr] + handler = update_wrapper(partial(m, handler=handler), handler) + return handler + + +_cached_build_middleware = lru_cache(maxsize=1024)(_build_middlewares) + + +class Application(MutableMapping[Union[str, AppKey[Any]], Any]): + ATTRS = frozenset( + [ + "logger", + "_debug", + "_router", + "_loop", + "_handler_args", + "_middlewares", + "_middlewares_handlers", + "_has_legacy_middlewares", + "_run_middlewares", + "_state", + "_frozen", + "_pre_frozen", + "_subapps", + "_on_response_prepare", + "_on_startup", + "_on_shutdown", + "_on_cleanup", + "_client_max_size", + "_cleanup_ctx", + ] + ) + + def __init__( + self, + *, + logger: logging.Logger = web_logger, + router: Optional[UrlDispatcher] = None, + middlewares: Iterable[Middleware] = (), + handler_args: Optional[Mapping[str, Any]] = None, + client_max_size: int = 1024**2, + loop: Optional[asyncio.AbstractEventLoop] = None, + debug: Any = ..., # mypy doesn't support ellipsis + ) -> None: + if router is None: + router = UrlDispatcher() + else: + warnings.warn( + "router argument is deprecated", DeprecationWarning, stacklevel=2 + ) + assert isinstance(router, AbstractRouter), router + + if loop is not None: + warnings.warn( + "loop argument is deprecated", DeprecationWarning, stacklevel=2 + ) + + if debug is not ...: + warnings.warn( + "debug argument is deprecated", DeprecationWarning, stacklevel=2 + ) + self._debug = debug + self._router: UrlDispatcher = router + self._loop = loop + self._handler_args = handler_args + self.logger = logger + + self._middlewares: _Middlewares = FrozenList(middlewares) + + # initialized on freezing + self._middlewares_handlers: _MiddlewaresHandlers = None + # initialized on freezing + self._run_middlewares: Optional[bool] = None + self._has_legacy_middlewares: bool = True + + self._state: Dict[Union[AppKey[Any], str], object] = {} + self._frozen = False + self._pre_frozen = False + self._subapps: _Subapps = [] + + self._on_response_prepare: _RespPrepareSignal = Signal(self) + self._on_startup: _AppSignal = Signal(self) + self._on_shutdown: _AppSignal = Signal(self) + self._on_cleanup: _AppSignal = Signal(self) + self._cleanup_ctx = CleanupContext() + self._on_startup.append(self._cleanup_ctx._on_startup) + self._on_cleanup.append(self._cleanup_ctx._on_cleanup) + self._client_max_size = client_max_size + + def __init_subclass__(cls: Type["Application"]) -> None: + warnings.warn( + "Inheritance class {} from web.Application " + "is discouraged".format(cls.__name__), + DeprecationWarning, + stacklevel=3, + ) + + if DEBUG: # pragma: no cover + + def __setattr__(self, name: str, val: Any) -> None: + if name not in self.ATTRS: + warnings.warn( + "Setting custom web.Application.{} attribute " + "is discouraged".format(name), + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(name, val) + + # MutableMapping API + + def __eq__(self, other: object) -> bool: + return self is other + + @overload # type: ignore[override] + def __getitem__(self, key: AppKey[_T]) -> _T: ... + + @overload + def __getitem__(self, key: str) -> Any: ... + + def __getitem__(self, key: Union[str, AppKey[_T]]) -> Any: + return self._state[key] + + def _check_frozen(self) -> None: + if self._frozen: + warnings.warn( + "Changing state of started or joined application is deprecated", + DeprecationWarning, + stacklevel=3, + ) + + @overload # type: ignore[override] + def __setitem__(self, key: AppKey[_T], value: _T) -> None: ... + + @overload + def __setitem__(self, key: str, value: Any) -> None: ... + + def __setitem__(self, key: Union[str, AppKey[_T]], value: Any) -> None: + self._check_frozen() + if not isinstance(key, AppKey): + warnings.warn( + "It is recommended to use web.AppKey instances for keys.\n" + + "https://docs.aiohttp.org/en/stable/web_advanced.html" + + "#application-s-config", + category=NotAppKeyWarning, + stacklevel=2, + ) + self._state[key] = value + + def __delitem__(self, key: Union[str, AppKey[_T]]) -> None: + self._check_frozen() + del self._state[key] + + def __len__(self) -> int: + return len(self._state) + + def __iter__(self) -> Iterator[Union[str, AppKey[Any]]]: + return iter(self._state) + + def __hash__(self) -> int: + return id(self) + + @overload # type: ignore[override] + def get(self, key: AppKey[_T], default: None = ...) -> Optional[_T]: ... + + @overload + def get(self, key: AppKey[_T], default: _U) -> Union[_T, _U]: ... + + @overload + def get(self, key: str, default: Any = ...) -> Any: ... + + def get(self, key: Union[str, AppKey[_T]], default: Any = None) -> Any: + return self._state.get(key, default) + + ######## + @property + def loop(self) -> asyncio.AbstractEventLoop: + # Technically the loop can be None + # but we mask it by explicit type cast + # to provide more convenient type annotation + warnings.warn("loop property is deprecated", DeprecationWarning, stacklevel=2) + return cast(asyncio.AbstractEventLoop, self._loop) + + def _set_loop(self, loop: Optional[asyncio.AbstractEventLoop]) -> None: + if loop is None: + loop = asyncio.get_event_loop() + if self._loop is not None and self._loop is not loop: + raise RuntimeError( + "web.Application instance initialized with different loop" + ) + + self._loop = loop + + # set loop debug + if self._debug is ...: + self._debug = loop.get_debug() + + # set loop to sub applications + for subapp in self._subapps: + subapp._set_loop(loop) + + @property + def pre_frozen(self) -> bool: + return self._pre_frozen + + def pre_freeze(self) -> None: + if self._pre_frozen: + return + + self._pre_frozen = True + self._middlewares.freeze() + self._router.freeze() + self._on_response_prepare.freeze() + self._cleanup_ctx.freeze() + self._on_startup.freeze() + self._on_shutdown.freeze() + self._on_cleanup.freeze() + self._middlewares_handlers = tuple(self._prepare_middleware()) + self._has_legacy_middlewares = any( + not new_style for _, new_style in self._middlewares_handlers + ) + + # If current app and any subapp do not have middlewares avoid run all + # of the code footprint that it implies, which have a middleware + # hardcoded per app that sets up the current_app attribute. If no + # middlewares are configured the handler will receive the proper + # current_app without needing all of this code. + self._run_middlewares = True if self.middlewares else False + + for subapp in self._subapps: + subapp.pre_freeze() + self._run_middlewares = self._run_middlewares or subapp._run_middlewares + + @property + def frozen(self) -> bool: + return self._frozen + + def freeze(self) -> None: + if self._frozen: + return + + self.pre_freeze() + self._frozen = True + for subapp in self._subapps: + subapp.freeze() + + @property + def debug(self) -> bool: + warnings.warn("debug property is deprecated", DeprecationWarning, stacklevel=2) + return self._debug # type: ignore[no-any-return] + + def _reg_subapp_signals(self, subapp: "Application") -> None: + def reg_handler(signame: str) -> None: + subsig = getattr(subapp, signame) + + async def handler(app: "Application") -> None: + await subsig.send(subapp) + + appsig = getattr(self, signame) + appsig.append(handler) + + reg_handler("on_startup") + reg_handler("on_shutdown") + reg_handler("on_cleanup") + + def add_subapp(self, prefix: str, subapp: "Application") -> PrefixedSubAppResource: + if not isinstance(prefix, str): + raise TypeError("Prefix must be str") + prefix = prefix.rstrip("/") + if not prefix: + raise ValueError("Prefix cannot be empty") + factory = partial(PrefixedSubAppResource, prefix, subapp) + return self._add_subapp(factory, subapp) + + def _add_subapp( + self, resource_factory: Callable[[], _Resource], subapp: "Application" + ) -> _Resource: + if self.frozen: + raise RuntimeError("Cannot add sub application to frozen application") + if subapp.frozen: + raise RuntimeError("Cannot add frozen application") + resource = resource_factory() + self.router.register_resource(resource) + self._reg_subapp_signals(subapp) + self._subapps.append(subapp) + subapp.pre_freeze() + if self._loop is not None: + subapp._set_loop(self._loop) + return resource + + def add_domain(self, domain: str, subapp: "Application") -> MatchedSubAppResource: + if not isinstance(domain, str): + raise TypeError("Domain must be str") + elif "*" in domain: + rule: Domain = MaskDomain(domain) + else: + rule = Domain(domain) + factory = partial(MatchedSubAppResource, rule, subapp) + return self._add_subapp(factory, subapp) + + def add_routes(self, routes: Iterable[AbstractRouteDef]) -> List[AbstractRoute]: + return self.router.add_routes(routes) + + @property + def on_response_prepare(self) -> _RespPrepareSignal: + return self._on_response_prepare + + @property + def on_startup(self) -> _AppSignal: + return self._on_startup + + @property + def on_shutdown(self) -> _AppSignal: + return self._on_shutdown + + @property + def on_cleanup(self) -> _AppSignal: + return self._on_cleanup + + @property + def cleanup_ctx(self) -> "CleanupContext": + return self._cleanup_ctx + + @property + def router(self) -> UrlDispatcher: + return self._router + + @property + def middlewares(self) -> _Middlewares: + return self._middlewares + + def _make_handler( + self, + *, + loop: Optional[asyncio.AbstractEventLoop] = None, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + **kwargs: Any, + ) -> Server: + + if not issubclass(access_log_class, AbstractAccessLogger): + raise TypeError( + "access_log_class must be subclass of " + "aiohttp.abc.AbstractAccessLogger, got {}".format(access_log_class) + ) + + self._set_loop(loop) + self.freeze() + + kwargs["debug"] = self._debug + kwargs["access_log_class"] = access_log_class + if self._handler_args: + for k, v in self._handler_args.items(): + kwargs[k] = v + + return Server( + self._handle, # type: ignore[arg-type] + request_factory=self._make_request, + loop=self._loop, + **kwargs, + ) + + def make_handler( + self, + *, + loop: Optional[asyncio.AbstractEventLoop] = None, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + **kwargs: Any, + ) -> Server: + + warnings.warn( + "Application.make_handler(...) is deprecated, use AppRunner API instead", + DeprecationWarning, + stacklevel=2, + ) + + return self._make_handler( + loop=loop, access_log_class=access_log_class, **kwargs + ) + + async def startup(self) -> None: + """Causes on_startup signal + + Should be called in the event loop along with the request handler. + """ + await self.on_startup.send(self) + + async def shutdown(self) -> None: + """Causes on_shutdown signal + + Should be called before cleanup() + """ + await self.on_shutdown.send(self) + + async def cleanup(self) -> None: + """Causes on_cleanup signal + + Should be called after shutdown() + """ + if self.on_cleanup.frozen: + await self.on_cleanup.send(self) + else: + # If an exception occurs in startup, ensure cleanup contexts are completed. + await self._cleanup_ctx._on_cleanup(self) + + def _make_request( + self, + message: RawRequestMessage, + payload: StreamReader, + protocol: RequestHandler, + writer: AbstractStreamWriter, + task: "asyncio.Task[None]", + _cls: Type[Request] = Request, + ) -> Request: + if TYPE_CHECKING: + assert self._loop is not None + return _cls( + message, + payload, + protocol, + writer, + task, + self._loop, + client_max_size=self._client_max_size, + ) + + def _prepare_middleware(self) -> Iterator[Tuple[Middleware, bool]]: + for m in reversed(self._middlewares): + if getattr(m, "__middleware_version__", None) == 1: + yield m, True + else: + warnings.warn( + f'old-style middleware "{m!r}" deprecated, see #2252', + DeprecationWarning, + stacklevel=2, + ) + yield m, False + + yield _fix_request_current_app(self), True + + async def _handle(self, request: Request) -> StreamResponse: + loop = asyncio.get_event_loop() + debug = loop.get_debug() + match_info = await self._router.resolve(request) + if debug: # pragma: no cover + if not isinstance(match_info, AbstractMatchInfo): + raise TypeError( + "match_info should be AbstractMatchInfo " + "instance, not {!r}".format(match_info) + ) + match_info.add_app(self) + + match_info.freeze() + + request._match_info = match_info + + if request.headers.get(hdrs.EXPECT): + resp = await match_info.expect_handler(request) + await request.writer.drain() + if resp is not None: + return resp + + handler = match_info.handler + + if self._run_middlewares: + # If its a SystemRoute, don't cache building the middlewares since + # they are constructed for every MatchInfoError as a new handler + # is made each time. + if not self._has_legacy_middlewares and not isinstance( + match_info.route, SystemRoute + ): + handler = _cached_build_middleware(handler, match_info.apps) + else: + for app in match_info.apps[::-1]: + for m, new_style in app._middlewares_handlers: # type: ignore[union-attr] + if new_style: + handler = update_wrapper( + partial(m, handler=handler), handler + ) + else: + handler = await m(app, handler) # type: ignore[arg-type,assignment] + + return await handler(request) + + def __call__(self) -> "Application": + """gunicorn compatibility""" + return self + + def __repr__(self) -> str: + return f"" + + def __bool__(self) -> bool: + return True + + +class CleanupError(RuntimeError): + @property + def exceptions(self) -> List[BaseException]: + return cast(List[BaseException], self.args[1]) + + +if TYPE_CHECKING: + _CleanupContextBase = FrozenList[Callable[[Application], AsyncIterator[None]]] +else: + _CleanupContextBase = FrozenList + + +class CleanupContext(_CleanupContextBase): + def __init__(self) -> None: + super().__init__() + self._exits: List[AsyncIterator[None]] = [] + + async def _on_startup(self, app: Application) -> None: + for cb in self: + it = cb(app).__aiter__() + await it.__anext__() + self._exits.append(it) + + async def _on_cleanup(self, app: Application) -> None: + errors = [] + for it in reversed(self._exits): + try: + await it.__anext__() + except StopAsyncIteration: + pass + except (Exception, asyncio.CancelledError) as exc: + errors.append(exc) + else: + errors.append(RuntimeError(f"{it!r} has more than one 'yield'")) + if errors: + if len(errors) == 1: + raise errors[0] + else: + raise CleanupError("Multiple errors on cleanup stage", errors) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_exceptions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..ee2c1e72d40ac93c00cbfcef6c84888a336855a3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_exceptions.py @@ -0,0 +1,452 @@ +import warnings +from typing import Any, Dict, Iterable, List, Optional, Set # noqa + +from yarl import URL + +from .typedefs import LooseHeaders, StrOrURL +from .web_response import Response + +__all__ = ( + "HTTPException", + "HTTPError", + "HTTPRedirection", + "HTTPSuccessful", + "HTTPOk", + "HTTPCreated", + "HTTPAccepted", + "HTTPNonAuthoritativeInformation", + "HTTPNoContent", + "HTTPResetContent", + "HTTPPartialContent", + "HTTPMove", + "HTTPMultipleChoices", + "HTTPMovedPermanently", + "HTTPFound", + "HTTPSeeOther", + "HTTPNotModified", + "HTTPUseProxy", + "HTTPTemporaryRedirect", + "HTTPPermanentRedirect", + "HTTPClientError", + "HTTPBadRequest", + "HTTPUnauthorized", + "HTTPPaymentRequired", + "HTTPForbidden", + "HTTPNotFound", + "HTTPMethodNotAllowed", + "HTTPNotAcceptable", + "HTTPProxyAuthenticationRequired", + "HTTPRequestTimeout", + "HTTPConflict", + "HTTPGone", + "HTTPLengthRequired", + "HTTPPreconditionFailed", + "HTTPRequestEntityTooLarge", + "HTTPRequestURITooLong", + "HTTPUnsupportedMediaType", + "HTTPRequestRangeNotSatisfiable", + "HTTPExpectationFailed", + "HTTPMisdirectedRequest", + "HTTPUnprocessableEntity", + "HTTPFailedDependency", + "HTTPUpgradeRequired", + "HTTPPreconditionRequired", + "HTTPTooManyRequests", + "HTTPRequestHeaderFieldsTooLarge", + "HTTPUnavailableForLegalReasons", + "HTTPServerError", + "HTTPInternalServerError", + "HTTPNotImplemented", + "HTTPBadGateway", + "HTTPServiceUnavailable", + "HTTPGatewayTimeout", + "HTTPVersionNotSupported", + "HTTPVariantAlsoNegotiates", + "HTTPInsufficientStorage", + "HTTPNotExtended", + "HTTPNetworkAuthenticationRequired", +) + + +class NotAppKeyWarning(UserWarning): + """Warning when not using AppKey in Application.""" + + +############################################################ +# HTTP Exceptions +############################################################ + + +class HTTPException(Response, Exception): + + # You should set in subclasses: + # status = 200 + + status_code = -1 + empty_body = False + + __http_exception__ = True + + def __init__( + self, + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + if body is not None: + warnings.warn( + "body argument is deprecated for http web exceptions", + DeprecationWarning, + ) + Response.__init__( + self, + status=self.status_code, + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + Exception.__init__(self, self.reason) + if self.body is None and not self.empty_body: + self.text = f"{self.status}: {self.reason}" + + def __bool__(self) -> bool: + return True + + +class HTTPError(HTTPException): + """Base class for exceptions with status codes in the 400s and 500s.""" + + +class HTTPRedirection(HTTPException): + """Base class for exceptions with status codes in the 300s.""" + + +class HTTPSuccessful(HTTPException): + """Base class for exceptions with status codes in the 200s.""" + + +class HTTPOk(HTTPSuccessful): + status_code = 200 + + +class HTTPCreated(HTTPSuccessful): + status_code = 201 + + +class HTTPAccepted(HTTPSuccessful): + status_code = 202 + + +class HTTPNonAuthoritativeInformation(HTTPSuccessful): + status_code = 203 + + +class HTTPNoContent(HTTPSuccessful): + status_code = 204 + empty_body = True + + +class HTTPResetContent(HTTPSuccessful): + status_code = 205 + empty_body = True + + +class HTTPPartialContent(HTTPSuccessful): + status_code = 206 + + +############################################################ +# 3xx redirection +############################################################ + + +class HTTPMove(HTTPRedirection): + def __init__( + self, + location: StrOrURL, + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + if not location: + raise ValueError("HTTP redirects need a location to redirect to.") + super().__init__( + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + self.headers["Location"] = str(URL(location)) + self.location = location + + +class HTTPMultipleChoices(HTTPMove): + status_code = 300 + + +class HTTPMovedPermanently(HTTPMove): + status_code = 301 + + +class HTTPFound(HTTPMove): + status_code = 302 + + +# This one is safe after a POST (the redirected location will be +# retrieved with GET): +class HTTPSeeOther(HTTPMove): + status_code = 303 + + +class HTTPNotModified(HTTPRedirection): + # FIXME: this should include a date or etag header + status_code = 304 + empty_body = True + + +class HTTPUseProxy(HTTPMove): + # Not a move, but looks a little like one + status_code = 305 + + +class HTTPTemporaryRedirect(HTTPMove): + status_code = 307 + + +class HTTPPermanentRedirect(HTTPMove): + status_code = 308 + + +############################################################ +# 4xx client error +############################################################ + + +class HTTPClientError(HTTPError): + pass + + +class HTTPBadRequest(HTTPClientError): + status_code = 400 + + +class HTTPUnauthorized(HTTPClientError): + status_code = 401 + + +class HTTPPaymentRequired(HTTPClientError): + status_code = 402 + + +class HTTPForbidden(HTTPClientError): + status_code = 403 + + +class HTTPNotFound(HTTPClientError): + status_code = 404 + + +class HTTPMethodNotAllowed(HTTPClientError): + status_code = 405 + + def __init__( + self, + method: str, + allowed_methods: Iterable[str], + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + allow = ",".join(sorted(allowed_methods)) + super().__init__( + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + self.headers["Allow"] = allow + self.allowed_methods: Set[str] = set(allowed_methods) + self.method = method.upper() + + +class HTTPNotAcceptable(HTTPClientError): + status_code = 406 + + +class HTTPProxyAuthenticationRequired(HTTPClientError): + status_code = 407 + + +class HTTPRequestTimeout(HTTPClientError): + status_code = 408 + + +class HTTPConflict(HTTPClientError): + status_code = 409 + + +class HTTPGone(HTTPClientError): + status_code = 410 + + +class HTTPLengthRequired(HTTPClientError): + status_code = 411 + + +class HTTPPreconditionFailed(HTTPClientError): + status_code = 412 + + +class HTTPRequestEntityTooLarge(HTTPClientError): + status_code = 413 + + def __init__(self, max_size: float, actual_size: float, **kwargs: Any) -> None: + kwargs.setdefault( + "text", + "Maximum request body size {} exceeded, " + "actual body size {}".format(max_size, actual_size), + ) + super().__init__(**kwargs) + + +class HTTPRequestURITooLong(HTTPClientError): + status_code = 414 + + +class HTTPUnsupportedMediaType(HTTPClientError): + status_code = 415 + + +class HTTPRequestRangeNotSatisfiable(HTTPClientError): + status_code = 416 + + +class HTTPExpectationFailed(HTTPClientError): + status_code = 417 + + +class HTTPMisdirectedRequest(HTTPClientError): + status_code = 421 + + +class HTTPUnprocessableEntity(HTTPClientError): + status_code = 422 + + +class HTTPFailedDependency(HTTPClientError): + status_code = 424 + + +class HTTPUpgradeRequired(HTTPClientError): + status_code = 426 + + +class HTTPPreconditionRequired(HTTPClientError): + status_code = 428 + + +class HTTPTooManyRequests(HTTPClientError): + status_code = 429 + + +class HTTPRequestHeaderFieldsTooLarge(HTTPClientError): + status_code = 431 + + +class HTTPUnavailableForLegalReasons(HTTPClientError): + status_code = 451 + + def __init__( + self, + link: Optional[StrOrURL], + *, + headers: Optional[LooseHeaders] = None, + reason: Optional[str] = None, + body: Any = None, + text: Optional[str] = None, + content_type: Optional[str] = None, + ) -> None: + super().__init__( + headers=headers, + reason=reason, + body=body, + text=text, + content_type=content_type, + ) + self._link = None + if link: + self._link = URL(link) + self.headers["Link"] = f'<{str(self._link)}>; rel="blocked-by"' + + @property + def link(self) -> Optional[URL]: + return self._link + + +############################################################ +# 5xx Server Error +############################################################ +# Response status codes beginning with the digit "5" indicate cases in +# which the server is aware that it has erred or is incapable of +# performing the request. Except when responding to a HEAD request, the +# server SHOULD include an entity containing an explanation of the error +# situation, and whether it is a temporary or permanent condition. User +# agents SHOULD display any included entity to the user. These response +# codes are applicable to any request method. + + +class HTTPServerError(HTTPError): + pass + + +class HTTPInternalServerError(HTTPServerError): + status_code = 500 + + +class HTTPNotImplemented(HTTPServerError): + status_code = 501 + + +class HTTPBadGateway(HTTPServerError): + status_code = 502 + + +class HTTPServiceUnavailable(HTTPServerError): + status_code = 503 + + +class HTTPGatewayTimeout(HTTPServerError): + status_code = 504 + + +class HTTPVersionNotSupported(HTTPServerError): + status_code = 505 + + +class HTTPVariantAlsoNegotiates(HTTPServerError): + status_code = 506 + + +class HTTPInsufficientStorage(HTTPServerError): + status_code = 507 + + +class HTTPNotExtended(HTTPServerError): + status_code = 510 + + +class HTTPNetworkAuthenticationRequired(HTTPServerError): + status_code = 511 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_fileresponse.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_fileresponse.py new file mode 100644 index 0000000000000000000000000000000000000000..344611cc4951b6ea63a49155c40ece8d3499b8fb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_fileresponse.py @@ -0,0 +1,418 @@ +import asyncio +import io +import os +import pathlib +import sys +from contextlib import suppress +from enum import Enum, auto +from mimetypes import MimeTypes +from stat import S_ISREG +from types import MappingProxyType +from typing import ( # noqa + IO, + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Final, + Iterator, + List, + Optional, + Set, + Tuple, + Union, + cast, +) + +from . import hdrs +from .abc import AbstractStreamWriter +from .helpers import ETAG_ANY, ETag, must_be_empty_body +from .typedefs import LooseHeaders, PathLike +from .web_exceptions import ( + HTTPForbidden, + HTTPNotFound, + HTTPNotModified, + HTTPPartialContent, + HTTPPreconditionFailed, + HTTPRequestRangeNotSatisfiable, +) +from .web_response import StreamResponse + +__all__ = ("FileResponse",) + +if TYPE_CHECKING: + from .web_request import BaseRequest + + +_T_OnChunkSent = Optional[Callable[[bytes], Awaitable[None]]] + + +NOSENDFILE: Final[bool] = bool(os.environ.get("AIOHTTP_NOSENDFILE")) + +CONTENT_TYPES: Final[MimeTypes] = MimeTypes() + +# File extension to IANA encodings map that will be checked in the order defined. +ENCODING_EXTENSIONS = MappingProxyType( + {ext: CONTENT_TYPES.encodings_map[ext] for ext in (".br", ".gz")} +) + +FALLBACK_CONTENT_TYPE = "application/octet-stream" + +# Provide additional MIME type/extension pairs to be recognized. +# https://en.wikipedia.org/wiki/List_of_archive_formats#Compression_only +ADDITIONAL_CONTENT_TYPES = MappingProxyType( + { + "application/gzip": ".gz", + "application/x-brotli": ".br", + "application/x-bzip2": ".bz2", + "application/x-compress": ".Z", + "application/x-xz": ".xz", + } +) + + +class _FileResponseResult(Enum): + """The result of the file response.""" + + SEND_FILE = auto() # Ie a regular file to send + NOT_ACCEPTABLE = auto() # Ie a socket, or non-regular file + PRE_CONDITION_FAILED = auto() # Ie If-Match or If-None-Match failed + NOT_MODIFIED = auto() # 304 Not Modified + + +# Add custom pairs and clear the encodings map so guess_type ignores them. +CONTENT_TYPES.encodings_map.clear() +for content_type, extension in ADDITIONAL_CONTENT_TYPES.items(): + CONTENT_TYPES.add_type(content_type, extension) + + +_CLOSE_FUTURES: Set[asyncio.Future[None]] = set() + + +class FileResponse(StreamResponse): + """A response object can be used to send files.""" + + def __init__( + self, + path: PathLike, + chunk_size: int = 256 * 1024, + status: int = 200, + reason: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + ) -> None: + super().__init__(status=status, reason=reason, headers=headers) + + self._path = pathlib.Path(path) + self._chunk_size = chunk_size + + def _seek_and_read(self, fobj: IO[Any], offset: int, chunk_size: int) -> bytes: + fobj.seek(offset) + return fobj.read(chunk_size) # type: ignore[no-any-return] + + async def _sendfile_fallback( + self, writer: AbstractStreamWriter, fobj: IO[Any], offset: int, count: int + ) -> AbstractStreamWriter: + # To keep memory usage low,fobj is transferred in chunks + # controlled by the constructor's chunk_size argument. + + chunk_size = self._chunk_size + loop = asyncio.get_event_loop() + chunk = await loop.run_in_executor( + None, self._seek_and_read, fobj, offset, chunk_size + ) + while chunk: + await writer.write(chunk) + count = count - chunk_size + if count <= 0: + break + chunk = await loop.run_in_executor(None, fobj.read, min(chunk_size, count)) + + await writer.drain() + return writer + + async def _sendfile( + self, request: "BaseRequest", fobj: IO[Any], offset: int, count: int + ) -> AbstractStreamWriter: + writer = await super().prepare(request) + assert writer is not None + + if NOSENDFILE or self.compression: + return await self._sendfile_fallback(writer, fobj, offset, count) + + loop = request._loop + transport = request.transport + assert transport is not None + + try: + await loop.sendfile(transport, fobj, offset, count) + except NotImplementedError: + return await self._sendfile_fallback(writer, fobj, offset, count) + + await super().write_eof() + return writer + + @staticmethod + def _etag_match(etag_value: str, etags: Tuple[ETag, ...], *, weak: bool) -> bool: + if len(etags) == 1 and etags[0].value == ETAG_ANY: + return True + return any( + etag.value == etag_value for etag in etags if weak or not etag.is_weak + ) + + async def _not_modified( + self, request: "BaseRequest", etag_value: str, last_modified: float + ) -> Optional[AbstractStreamWriter]: + self.set_status(HTTPNotModified.status_code) + self._length_check = False + self.etag = etag_value # type: ignore[assignment] + self.last_modified = last_modified # type: ignore[assignment] + # Delete any Content-Length headers provided by user. HTTP 304 + # should always have empty response body + return await super().prepare(request) + + async def _precondition_failed( + self, request: "BaseRequest" + ) -> Optional[AbstractStreamWriter]: + self.set_status(HTTPPreconditionFailed.status_code) + self.content_length = 0 + return await super().prepare(request) + + def _make_response( + self, request: "BaseRequest", accept_encoding: str + ) -> Tuple[ + _FileResponseResult, Optional[io.BufferedReader], os.stat_result, Optional[str] + ]: + """Return the response result, io object, stat result, and encoding. + + If an uncompressed file is returned, the encoding is set to + :py:data:`None`. + + This method should be called from a thread executor + since it calls os.stat which may block. + """ + file_path, st, file_encoding = self._get_file_path_stat_encoding( + accept_encoding + ) + if not file_path: + return _FileResponseResult.NOT_ACCEPTABLE, None, st, None + + etag_value = f"{st.st_mtime_ns:x}-{st.st_size:x}" + + # https://www.rfc-editor.org/rfc/rfc9110#section-13.1.1-2 + if (ifmatch := request.if_match) is not None and not self._etag_match( + etag_value, ifmatch, weak=False + ): + return _FileResponseResult.PRE_CONDITION_FAILED, None, st, file_encoding + + if ( + (unmodsince := request.if_unmodified_since) is not None + and ifmatch is None + and st.st_mtime > unmodsince.timestamp() + ): + return _FileResponseResult.PRE_CONDITION_FAILED, None, st, file_encoding + + # https://www.rfc-editor.org/rfc/rfc9110#section-13.1.2-2 + if (ifnonematch := request.if_none_match) is not None and self._etag_match( + etag_value, ifnonematch, weak=True + ): + return _FileResponseResult.NOT_MODIFIED, None, st, file_encoding + + if ( + (modsince := request.if_modified_since) is not None + and ifnonematch is None + and st.st_mtime <= modsince.timestamp() + ): + return _FileResponseResult.NOT_MODIFIED, None, st, file_encoding + + fobj = file_path.open("rb") + with suppress(OSError): + # fstat() may not be available on all platforms + # Once we open the file, we want the fstat() to ensure + # the file has not changed between the first stat() + # and the open(). + st = os.stat(fobj.fileno()) + return _FileResponseResult.SEND_FILE, fobj, st, file_encoding + + def _get_file_path_stat_encoding( + self, accept_encoding: str + ) -> Tuple[Optional[pathlib.Path], os.stat_result, Optional[str]]: + file_path = self._path + for file_extension, file_encoding in ENCODING_EXTENSIONS.items(): + if file_encoding not in accept_encoding: + continue + + compressed_path = file_path.with_suffix(file_path.suffix + file_extension) + with suppress(OSError): + # Do not follow symlinks and ignore any non-regular files. + st = compressed_path.lstat() + if S_ISREG(st.st_mode): + return compressed_path, st, file_encoding + + # Fallback to the uncompressed file + st = file_path.stat() + return file_path if S_ISREG(st.st_mode) else None, st, None + + async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]: + loop = asyncio.get_running_loop() + # Encoding comparisons should be case-insensitive + # https://www.rfc-editor.org/rfc/rfc9110#section-8.4.1 + accept_encoding = request.headers.get(hdrs.ACCEPT_ENCODING, "").lower() + try: + response_result, fobj, st, file_encoding = await loop.run_in_executor( + None, self._make_response, request, accept_encoding + ) + except PermissionError: + self.set_status(HTTPForbidden.status_code) + return await super().prepare(request) + except OSError: + # Most likely to be FileNotFoundError or OSError for circular + # symlinks in python >= 3.13, so respond with 404. + self.set_status(HTTPNotFound.status_code) + return await super().prepare(request) + + # Forbid special files like sockets, pipes, devices, etc. + if response_result is _FileResponseResult.NOT_ACCEPTABLE: + self.set_status(HTTPForbidden.status_code) + return await super().prepare(request) + + if response_result is _FileResponseResult.PRE_CONDITION_FAILED: + return await self._precondition_failed(request) + + if response_result is _FileResponseResult.NOT_MODIFIED: + etag_value = f"{st.st_mtime_ns:x}-{st.st_size:x}" + last_modified = st.st_mtime + return await self._not_modified(request, etag_value, last_modified) + + assert fobj is not None + try: + return await self._prepare_open_file(request, fobj, st, file_encoding) + finally: + # We do not await here because we do not want to wait + # for the executor to finish before returning the response + # so the connection can begin servicing another request + # as soon as possible. + close_future = loop.run_in_executor(None, fobj.close) + # Hold a strong reference to the future to prevent it from being + # garbage collected before it completes. + _CLOSE_FUTURES.add(close_future) + close_future.add_done_callback(_CLOSE_FUTURES.remove) + + async def _prepare_open_file( + self, + request: "BaseRequest", + fobj: io.BufferedReader, + st: os.stat_result, + file_encoding: Optional[str], + ) -> Optional[AbstractStreamWriter]: + status = self._status + file_size: int = st.st_size + file_mtime: float = st.st_mtime + count: int = file_size + start: Optional[int] = None + + if (ifrange := request.if_range) is None or file_mtime <= ifrange.timestamp(): + # If-Range header check: + # condition = cached date >= last modification date + # return 206 if True else 200. + # if False: + # Range header would not be processed, return 200 + # if True but Range header missing + # return 200 + try: + rng = request.http_range + start = rng.start + end: Optional[int] = rng.stop + except ValueError: + # https://tools.ietf.org/html/rfc7233: + # A server generating a 416 (Range Not Satisfiable) response to + # a byte-range request SHOULD send a Content-Range header field + # with an unsatisfied-range value. + # The complete-length in a 416 response indicates the current + # length of the selected representation. + # + # Will do the same below. Many servers ignore this and do not + # send a Content-Range header with HTTP 416 + self._headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" + self.set_status(HTTPRequestRangeNotSatisfiable.status_code) + return await super().prepare(request) + + # If a range request has been made, convert start, end slice + # notation into file pointer offset and count + if start is not None: + if start < 0 and end is None: # return tail of file + start += file_size + if start < 0: + # if Range:bytes=-1000 in request header but file size + # is only 200, there would be trouble without this + start = 0 + count = file_size - start + else: + # rfc7233:If the last-byte-pos value is + # absent, or if the value is greater than or equal to + # the current length of the representation data, + # the byte range is interpreted as the remainder + # of the representation (i.e., the server replaces the + # value of last-byte-pos with a value that is one less than + # the current length of the selected representation). + count = ( + min(end if end is not None else file_size, file_size) - start + ) + + if start >= file_size: + # HTTP 416 should be returned in this case. + # + # According to https://tools.ietf.org/html/rfc7233: + # If a valid byte-range-set includes at least one + # byte-range-spec with a first-byte-pos that is less than + # the current length of the representation, or at least one + # suffix-byte-range-spec with a non-zero suffix-length, + # then the byte-range-set is satisfiable. Otherwise, the + # byte-range-set is unsatisfiable. + self._headers[hdrs.CONTENT_RANGE] = f"bytes */{file_size}" + self.set_status(HTTPRequestRangeNotSatisfiable.status_code) + return await super().prepare(request) + + status = HTTPPartialContent.status_code + # Even though you are sending the whole file, you should still + # return a HTTP 206 for a Range request. + self.set_status(status) + + # If the Content-Type header is not already set, guess it based on the + # extension of the request path. The encoding returned by guess_type + # can be ignored since the map was cleared above. + if hdrs.CONTENT_TYPE not in self._headers: + if sys.version_info >= (3, 13): + guesser = CONTENT_TYPES.guess_file_type + else: + guesser = CONTENT_TYPES.guess_type + self.content_type = guesser(self._path)[0] or FALLBACK_CONTENT_TYPE + + if file_encoding: + self._headers[hdrs.CONTENT_ENCODING] = file_encoding + self._headers[hdrs.VARY] = hdrs.ACCEPT_ENCODING + # Disable compression if we are already sending + # a compressed file since we don't want to double + # compress. + self._compression = False + + self.etag = f"{st.st_mtime_ns:x}-{st.st_size:x}" # type: ignore[assignment] + self.last_modified = file_mtime # type: ignore[assignment] + self.content_length = count + + self._headers[hdrs.ACCEPT_RANGES] = "bytes" + + if status == HTTPPartialContent.status_code: + real_start = start + assert real_start is not None + self._headers[hdrs.CONTENT_RANGE] = "bytes {}-{}/{}".format( + real_start, real_start + count - 1, file_size + ) + + # If we are sending 0 bytes calling sendfile() will throw a ValueError + if count == 0 or must_be_empty_body(request.method, status): + return await super().prepare(request) + + # be aware that start could be None or int=0 here. + offset = start or 0 + + return await self._sendfile(request, fobj, offset, count) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_log.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_log.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ea2beeb152974ce5dd9f3e7990133ce04f7980 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_log.py @@ -0,0 +1,216 @@ +import datetime +import functools +import logging +import os +import re +import time as time_mod +from collections import namedtuple +from typing import Any, Callable, Dict, Iterable, List, Tuple # noqa + +from .abc import AbstractAccessLogger +from .web_request import BaseRequest +from .web_response import StreamResponse + +KeyMethod = namedtuple("KeyMethod", "key method") + + +class AccessLogger(AbstractAccessLogger): + """Helper object to log access. + + Usage: + log = logging.getLogger("spam") + log_format = "%a %{User-Agent}i" + access_logger = AccessLogger(log, log_format) + access_logger.log(request, response, time) + + Format: + %% The percent sign + %a Remote IP-address (IP-address of proxy if using reverse proxy) + %t Time when the request was started to process + %P The process ID of the child that serviced the request + %r First line of request + %s Response status code + %b Size of response in bytes, including HTTP headers + %T Time taken to serve the request, in seconds + %Tf Time taken to serve the request, in seconds with floating fraction + in .06f format + %D Time taken to serve the request, in microseconds + %{FOO}i request.headers['FOO'] + %{FOO}o response.headers['FOO'] + %{FOO}e os.environ['FOO'] + + """ + + LOG_FORMAT_MAP = { + "a": "remote_address", + "t": "request_start_time", + "P": "process_id", + "r": "first_request_line", + "s": "response_status", + "b": "response_size", + "T": "request_time", + "Tf": "request_time_frac", + "D": "request_time_micro", + "i": "request_header", + "o": "response_header", + } + + LOG_FORMAT = '%a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"' + FORMAT_RE = re.compile(r"%(\{([A-Za-z0-9\-_]+)\}([ioe])|[atPrsbOD]|Tf?)") + CLEANUP_RE = re.compile(r"(%[^s])") + _FORMAT_CACHE: Dict[str, Tuple[str, List[KeyMethod]]] = {} + + def __init__(self, logger: logging.Logger, log_format: str = LOG_FORMAT) -> None: + """Initialise the logger. + + logger is a logger object to be used for logging. + log_format is a string with apache compatible log format description. + + """ + super().__init__(logger, log_format=log_format) + + _compiled_format = AccessLogger._FORMAT_CACHE.get(log_format) + if not _compiled_format: + _compiled_format = self.compile_format(log_format) + AccessLogger._FORMAT_CACHE[log_format] = _compiled_format + + self._log_format, self._methods = _compiled_format + + def compile_format(self, log_format: str) -> Tuple[str, List[KeyMethod]]: + """Translate log_format into form usable by modulo formatting + + All known atoms will be replaced with %s + Also methods for formatting of those atoms will be added to + _methods in appropriate order + + For example we have log_format = "%a %t" + This format will be translated to "%s %s" + Also contents of _methods will be + [self._format_a, self._format_t] + These method will be called and results will be passed + to translated string format. + + Each _format_* method receive 'args' which is list of arguments + given to self.log + + Exceptions are _format_e, _format_i and _format_o methods which + also receive key name (by functools.partial) + + """ + # list of (key, method) tuples, we don't use an OrderedDict as users + # can repeat the same key more than once + methods = list() + + for atom in self.FORMAT_RE.findall(log_format): + if atom[1] == "": + format_key1 = self.LOG_FORMAT_MAP[atom[0]] + m = getattr(AccessLogger, "_format_%s" % atom[0]) + key_method = KeyMethod(format_key1, m) + else: + format_key2 = (self.LOG_FORMAT_MAP[atom[2]], atom[1]) + m = getattr(AccessLogger, "_format_%s" % atom[2]) + key_method = KeyMethod(format_key2, functools.partial(m, atom[1])) + + methods.append(key_method) + + log_format = self.FORMAT_RE.sub(r"%s", log_format) + log_format = self.CLEANUP_RE.sub(r"%\1", log_format) + return log_format, methods + + @staticmethod + def _format_i( + key: str, request: BaseRequest, response: StreamResponse, time: float + ) -> str: + if request is None: + return "(no headers)" + + # suboptimal, make istr(key) once + return request.headers.get(key, "-") + + @staticmethod + def _format_o( + key: str, request: BaseRequest, response: StreamResponse, time: float + ) -> str: + # suboptimal, make istr(key) once + return response.headers.get(key, "-") + + @staticmethod + def _format_a(request: BaseRequest, response: StreamResponse, time: float) -> str: + if request is None: + return "-" + ip = request.remote + return ip if ip is not None else "-" + + @staticmethod + def _format_t(request: BaseRequest, response: StreamResponse, time: float) -> str: + tz = datetime.timezone(datetime.timedelta(seconds=-time_mod.timezone)) + now = datetime.datetime.now(tz) + start_time = now - datetime.timedelta(seconds=time) + return start_time.strftime("[%d/%b/%Y:%H:%M:%S %z]") + + @staticmethod + def _format_P(request: BaseRequest, response: StreamResponse, time: float) -> str: + return "<%s>" % os.getpid() + + @staticmethod + def _format_r(request: BaseRequest, response: StreamResponse, time: float) -> str: + if request is None: + return "-" + return "{} {} HTTP/{}.{}".format( + request.method, + request.path_qs, + request.version.major, + request.version.minor, + ) + + @staticmethod + def _format_s(request: BaseRequest, response: StreamResponse, time: float) -> int: + return response.status + + @staticmethod + def _format_b(request: BaseRequest, response: StreamResponse, time: float) -> int: + return response.body_length + + @staticmethod + def _format_T(request: BaseRequest, response: StreamResponse, time: float) -> str: + return str(round(time)) + + @staticmethod + def _format_Tf(request: BaseRequest, response: StreamResponse, time: float) -> str: + return "%06f" % time + + @staticmethod + def _format_D(request: BaseRequest, response: StreamResponse, time: float) -> str: + return str(round(time * 1000000)) + + def _format_line( + self, request: BaseRequest, response: StreamResponse, time: float + ) -> Iterable[Tuple[str, Callable[[BaseRequest, StreamResponse, float], str]]]: + return [(key, method(request, response, time)) for key, method in self._methods] + + @property + def enabled(self) -> bool: + """Check if logger is enabled.""" + # Avoid formatting the log line if it will not be emitted. + return self.logger.isEnabledFor(logging.INFO) + + def log(self, request: BaseRequest, response: StreamResponse, time: float) -> None: + try: + fmt_info = self._format_line(request, response, time) + + values = list() + extra = dict() + for key, value in fmt_info: + values.append(value) + + if key.__class__ is str: + extra[key] = value + else: + k1, k2 = key # type: ignore[misc] + dct = extra.get(k1, {}) # type: ignore[var-annotated,has-type] + dct[k2] = value # type: ignore[index,has-type] + extra[k1] = dct # type: ignore[has-type,assignment] + + self.logger.info(self._log_format % tuple(values), extra=extra) + except Exception: + self.logger.exception("Error in logging") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_middlewares.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_middlewares.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1f5f58e6e38845d4d2d4ffdd2748fc519fa5bf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_middlewares.py @@ -0,0 +1,121 @@ +import re +from typing import TYPE_CHECKING, Tuple, Type, TypeVar + +from .typedefs import Handler, Middleware +from .web_exceptions import HTTPMove, HTTPPermanentRedirect +from .web_request import Request +from .web_response import StreamResponse +from .web_urldispatcher import SystemRoute + +__all__ = ( + "middleware", + "normalize_path_middleware", +) + +if TYPE_CHECKING: + from .web_app import Application + +_Func = TypeVar("_Func") + + +async def _check_request_resolves(request: Request, path: str) -> Tuple[bool, Request]: + alt_request = request.clone(rel_url=path) + + match_info = await request.app.router.resolve(alt_request) + alt_request._match_info = match_info + + if match_info.http_exception is None: + return True, alt_request + + return False, request + + +def middleware(f: _Func) -> _Func: + f.__middleware_version__ = 1 # type: ignore[attr-defined] + return f + + +def normalize_path_middleware( + *, + append_slash: bool = True, + remove_slash: bool = False, + merge_slashes: bool = True, + redirect_class: Type[HTTPMove] = HTTPPermanentRedirect, +) -> Middleware: + """Factory for producing a middleware that normalizes the path of a request. + + Normalizing means: + - Add or remove a trailing slash to the path. + - Double slashes are replaced by one. + + The middleware returns as soon as it finds a path that resolves + correctly. The order if both merge and append/remove are enabled is + 1) merge slashes + 2) append/remove slash + 3) both merge slashes and append/remove slash. + If the path resolves with at least one of those conditions, it will + redirect to the new path. + + Only one of `append_slash` and `remove_slash` can be enabled. If both + are `True` the factory will raise an assertion error + + If `append_slash` is `True` the middleware will append a slash when + needed. If a resource is defined with trailing slash and the request + comes without it, it will append it automatically. + + If `remove_slash` is `True`, `append_slash` must be `False`. When enabled + the middleware will remove trailing slashes and redirect if the resource + is defined + + If merge_slashes is True, merge multiple consecutive slashes in the + path into one. + """ + correct_configuration = not (append_slash and remove_slash) + assert correct_configuration, "Cannot both remove and append slash" + + @middleware + async def impl(request: Request, handler: Handler) -> StreamResponse: + if isinstance(request.match_info.route, SystemRoute): + paths_to_check = [] + if "?" in request.raw_path: + path, query = request.raw_path.split("?", 1) + query = "?" + query + else: + query = "" + path = request.raw_path + + if merge_slashes: + paths_to_check.append(re.sub("//+", "/", path)) + if append_slash and not request.path.endswith("/"): + paths_to_check.append(path + "/") + if remove_slash and request.path.endswith("/"): + paths_to_check.append(path[:-1]) + if merge_slashes and append_slash: + paths_to_check.append(re.sub("//+", "/", path + "/")) + if merge_slashes and remove_slash: + merged_slashes = re.sub("//+", "/", path) + paths_to_check.append(merged_slashes[:-1]) + + for path in paths_to_check: + path = re.sub("^//+", "/", path) # SECURITY: GHSA-v6wp-4m6f-gcjg + resolves, request = await _check_request_resolves(request, path) + if resolves: + raise redirect_class(request.raw_path + query) + + return await handler(request) + + return impl + + +def _fix_request_current_app(app: "Application") -> Middleware: + @middleware + async def impl(request: Request, handler: Handler) -> StreamResponse: + match_info = request.match_info + prev = match_info.current_app + match_info.current_app = app + try: + return await handler(request) + finally: + match_info.current_app = prev + + return impl diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_protocol.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..e1923aac24bdc7f2c7697b061a6bf68ae6509c6f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_protocol.py @@ -0,0 +1,792 @@ +import asyncio +import asyncio.streams +import sys +import traceback +import warnings +from collections import deque +from contextlib import suppress +from html import escape as html_escape +from http import HTTPStatus +from logging import Logger +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Deque, + Optional, + Sequence, + Tuple, + Type, + Union, + cast, +) + +import attr +import yarl +from propcache import under_cached_property + +from .abc import AbstractAccessLogger, AbstractStreamWriter +from .base_protocol import BaseProtocol +from .helpers import ceil_timeout +from .http import ( + HttpProcessingError, + HttpRequestParser, + HttpVersion10, + RawRequestMessage, + StreamWriter, +) +from .http_exceptions import BadHttpMethod +from .log import access_logger, server_logger +from .streams import EMPTY_PAYLOAD, StreamReader +from .tcp_helpers import tcp_keepalive +from .web_exceptions import HTTPException, HTTPInternalServerError +from .web_log import AccessLogger +from .web_request import BaseRequest +from .web_response import Response, StreamResponse + +__all__ = ("RequestHandler", "RequestPayloadError", "PayloadAccessError") + +if TYPE_CHECKING: + import ssl + + from .web_server import Server + + +_RequestFactory = Callable[ + [ + RawRequestMessage, + StreamReader, + "RequestHandler", + AbstractStreamWriter, + "asyncio.Task[None]", + ], + BaseRequest, +] + +_RequestHandler = Callable[[BaseRequest], Awaitable[StreamResponse]] + +ERROR = RawRequestMessage( + "UNKNOWN", + "/", + HttpVersion10, + {}, # type: ignore[arg-type] + {}, # type: ignore[arg-type] + True, + None, + False, + False, + yarl.URL("/"), +) + + +class RequestPayloadError(Exception): + """Payload parsing error.""" + + +class PayloadAccessError(Exception): + """Payload was accessed after response was sent.""" + + +_PAYLOAD_ACCESS_ERROR = PayloadAccessError() + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class _ErrInfo: + status: int + exc: BaseException + message: str + + +_MsgType = Tuple[Union[RawRequestMessage, _ErrInfo], StreamReader] + + +class RequestHandler(BaseProtocol): + """HTTP protocol implementation. + + RequestHandler handles incoming HTTP request. It reads request line, + request headers and request payload and calls handle_request() method. + By default it always returns with 404 response. + + RequestHandler handles errors in incoming request, like bad + status line, bad headers or incomplete payload. If any error occurs, + connection gets closed. + + keepalive_timeout -- number of seconds before closing + keep-alive connection + + tcp_keepalive -- TCP keep-alive is on, default is on + + debug -- enable debug mode + + logger -- custom logger object + + access_log_class -- custom class for access_logger + + access_log -- custom logging object + + access_log_format -- access log format string + + loop -- Optional event loop + + max_line_size -- Optional maximum header line size + + max_field_size -- Optional maximum header field size + + max_headers -- Optional maximum header size + + timeout_ceil_threshold -- Optional value to specify + threshold to ceil() timeout + values + + """ + + __slots__ = ( + "_request_count", + "_keepalive", + "_manager", + "_request_handler", + "_request_factory", + "_tcp_keepalive", + "_next_keepalive_close_time", + "_keepalive_handle", + "_keepalive_timeout", + "_lingering_time", + "_messages", + "_message_tail", + "_handler_waiter", + "_waiter", + "_task_handler", + "_upgrade", + "_payload_parser", + "_request_parser", + "_reading_paused", + "logger", + "debug", + "access_log", + "access_logger", + "_close", + "_force_close", + "_current_request", + "_timeout_ceil_threshold", + "_request_in_progress", + "_logging_enabled", + "_cache", + ) + + def __init__( + self, + manager: "Server", + *, + loop: asyncio.AbstractEventLoop, + # Default should be high enough that it's likely longer than a reverse proxy. + keepalive_timeout: float = 3630, + tcp_keepalive: bool = True, + logger: Logger = server_logger, + access_log_class: Type[AbstractAccessLogger] = AccessLogger, + access_log: Logger = access_logger, + access_log_format: str = AccessLogger.LOG_FORMAT, + debug: bool = False, + max_line_size: int = 8190, + max_headers: int = 32768, + max_field_size: int = 8190, + lingering_time: float = 10.0, + read_bufsize: int = 2**16, + auto_decompress: bool = True, + timeout_ceil_threshold: float = 5, + ): + super().__init__(loop) + + # _request_count is the number of requests processed with the same connection. + self._request_count = 0 + self._keepalive = False + self._current_request: Optional[BaseRequest] = None + self._manager: Optional[Server] = manager + self._request_handler: Optional[_RequestHandler] = manager.request_handler + self._request_factory: Optional[_RequestFactory] = manager.request_factory + + self._tcp_keepalive = tcp_keepalive + # placeholder to be replaced on keepalive timeout setup + self._next_keepalive_close_time = 0.0 + self._keepalive_handle: Optional[asyncio.Handle] = None + self._keepalive_timeout = keepalive_timeout + self._lingering_time = float(lingering_time) + + self._messages: Deque[_MsgType] = deque() + self._message_tail = b"" + + self._waiter: Optional[asyncio.Future[None]] = None + self._handler_waiter: Optional[asyncio.Future[None]] = None + self._task_handler: Optional[asyncio.Task[None]] = None + + self._upgrade = False + self._payload_parser: Any = None + self._request_parser: Optional[HttpRequestParser] = HttpRequestParser( + self, + loop, + read_bufsize, + max_line_size=max_line_size, + max_field_size=max_field_size, + max_headers=max_headers, + payload_exception=RequestPayloadError, + auto_decompress=auto_decompress, + ) + + self._timeout_ceil_threshold: float = 5 + try: + self._timeout_ceil_threshold = float(timeout_ceil_threshold) + except (TypeError, ValueError): + pass + + self.logger = logger + self.debug = debug + self.access_log = access_log + if access_log: + self.access_logger: Optional[AbstractAccessLogger] = access_log_class( + access_log, access_log_format + ) + self._logging_enabled = self.access_logger.enabled + else: + self.access_logger = None + self._logging_enabled = False + + self._close = False + self._force_close = False + self._request_in_progress = False + self._cache: dict[str, Any] = {} + + def __repr__(self) -> str: + return "<{} {}>".format( + self.__class__.__name__, + "connected" if self.transport is not None else "disconnected", + ) + + @under_cached_property + def ssl_context(self) -> Optional["ssl.SSLContext"]: + """Return SSLContext if available.""" + return ( + None + if self.transport is None + else self.transport.get_extra_info("sslcontext") + ) + + @under_cached_property + def peername( + self, + ) -> Optional[Union[str, Tuple[str, int, int, int], Tuple[str, int]]]: + """Return peername if available.""" + return ( + None + if self.transport is None + else self.transport.get_extra_info("peername") + ) + + @property + def keepalive_timeout(self) -> float: + return self._keepalive_timeout + + async def shutdown(self, timeout: Optional[float] = 15.0) -> None: + """Do worker process exit preparations. + + We need to clean up everything and stop accepting requests. + It is especially important for keep-alive connections. + """ + self._force_close = True + + if self._keepalive_handle is not None: + self._keepalive_handle.cancel() + + # Wait for graceful handler completion + if self._request_in_progress: + # The future is only created when we are shutting + # down while the handler is still processing a request + # to avoid creating a future for every request. + self._handler_waiter = self._loop.create_future() + try: + async with ceil_timeout(timeout): + await self._handler_waiter + except (asyncio.CancelledError, asyncio.TimeoutError): + self._handler_waiter = None + if ( + sys.version_info >= (3, 11) + and (task := asyncio.current_task()) + and task.cancelling() + ): + raise + # Then cancel handler and wait + try: + async with ceil_timeout(timeout): + if self._current_request is not None: + self._current_request._cancel(asyncio.CancelledError()) + + if self._task_handler is not None and not self._task_handler.done(): + await asyncio.shield(self._task_handler) + except (asyncio.CancelledError, asyncio.TimeoutError): + if ( + sys.version_info >= (3, 11) + and (task := asyncio.current_task()) + and task.cancelling() + ): + raise + + # force-close non-idle handler + if self._task_handler is not None: + self._task_handler.cancel() + + self.force_close() + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + super().connection_made(transport) + + real_transport = cast(asyncio.Transport, transport) + if self._tcp_keepalive: + tcp_keepalive(real_transport) + + assert self._manager is not None + self._manager.connection_made(self, real_transport) + + loop = self._loop + if sys.version_info >= (3, 12): + task = asyncio.Task(self.start(), loop=loop, eager_start=True) + else: + task = loop.create_task(self.start()) + self._task_handler = task + + def connection_lost(self, exc: Optional[BaseException]) -> None: + if self._manager is None: + return + self._manager.connection_lost(self, exc) + + # Grab value before setting _manager to None. + handler_cancellation = self._manager.handler_cancellation + + self.force_close() + super().connection_lost(exc) + self._manager = None + self._request_factory = None + self._request_handler = None + self._request_parser = None + + if self._keepalive_handle is not None: + self._keepalive_handle.cancel() + + if self._current_request is not None: + if exc is None: + exc = ConnectionResetError("Connection lost") + self._current_request._cancel(exc) + + if handler_cancellation and self._task_handler is not None: + self._task_handler.cancel() + + self._task_handler = None + + if self._payload_parser is not None: + self._payload_parser.feed_eof() + self._payload_parser = None + + def set_parser(self, parser: Any) -> None: + # Actual type is WebReader + assert self._payload_parser is None + + self._payload_parser = parser + + if self._message_tail: + self._payload_parser.feed_data(self._message_tail) + self._message_tail = b"" + + def eof_received(self) -> None: + pass + + def data_received(self, data: bytes) -> None: + if self._force_close or self._close: + return + # parse http messages + messages: Sequence[_MsgType] + if self._payload_parser is None and not self._upgrade: + assert self._request_parser is not None + try: + messages, upgraded, tail = self._request_parser.feed_data(data) + except HttpProcessingError as exc: + messages = [ + (_ErrInfo(status=400, exc=exc, message=exc.message), EMPTY_PAYLOAD) + ] + upgraded = False + tail = b"" + + for msg, payload in messages or (): + self._request_count += 1 + self._messages.append((msg, payload)) + + waiter = self._waiter + if messages and waiter is not None and not waiter.done(): + # don't set result twice + waiter.set_result(None) + + self._upgrade = upgraded + if upgraded and tail: + self._message_tail = tail + + # no parser, just store + elif self._payload_parser is None and self._upgrade and data: + self._message_tail += data + + # feed payload + elif data: + eof, tail = self._payload_parser.feed_data(data) + if eof: + self.close() + + def keep_alive(self, val: bool) -> None: + """Set keep-alive connection mode. + + :param bool val: new state. + """ + self._keepalive = val + if self._keepalive_handle: + self._keepalive_handle.cancel() + self._keepalive_handle = None + + def close(self) -> None: + """Close connection. + + Stop accepting new pipelining messages and close + connection when handlers done processing messages. + """ + self._close = True + if self._waiter: + self._waiter.cancel() + + def force_close(self) -> None: + """Forcefully close connection.""" + self._force_close = True + if self._waiter: + self._waiter.cancel() + if self.transport is not None: + self.transport.close() + self.transport = None + + def log_access( + self, request: BaseRequest, response: StreamResponse, time: Optional[float] + ) -> None: + if self.access_logger is not None and self.access_logger.enabled: + if TYPE_CHECKING: + assert time is not None + self.access_logger.log(request, response, self._loop.time() - time) + + def log_debug(self, *args: Any, **kw: Any) -> None: + if self.debug: + self.logger.debug(*args, **kw) + + def log_exception(self, *args: Any, **kw: Any) -> None: + self.logger.exception(*args, **kw) + + def _process_keepalive(self) -> None: + self._keepalive_handle = None + if self._force_close or not self._keepalive: + return + + loop = self._loop + now = loop.time() + close_time = self._next_keepalive_close_time + if now < close_time: + # Keep alive close check fired too early, reschedule + self._keepalive_handle = loop.call_at(close_time, self._process_keepalive) + return + + # handler in idle state + if self._waiter and not self._waiter.done(): + self.force_close() + + async def _handle_request( + self, + request: BaseRequest, + start_time: Optional[float], + request_handler: Callable[[BaseRequest], Awaitable[StreamResponse]], + ) -> Tuple[StreamResponse, bool]: + self._request_in_progress = True + try: + try: + self._current_request = request + resp = await request_handler(request) + finally: + self._current_request = None + except HTTPException as exc: + resp = exc + resp, reset = await self.finish_response(request, resp, start_time) + except asyncio.CancelledError: + raise + except asyncio.TimeoutError as exc: + self.log_debug("Request handler timed out.", exc_info=exc) + resp = self.handle_error(request, 504) + resp, reset = await self.finish_response(request, resp, start_time) + except Exception as exc: + resp = self.handle_error(request, 500, exc) + resp, reset = await self.finish_response(request, resp, start_time) + else: + # Deprecation warning (See #2415) + if getattr(resp, "__http_exception__", False): + warnings.warn( + "returning HTTPException object is deprecated " + "(#2415) and will be removed, " + "please raise the exception instead", + DeprecationWarning, + ) + + resp, reset = await self.finish_response(request, resp, start_time) + finally: + self._request_in_progress = False + if self._handler_waiter is not None: + self._handler_waiter.set_result(None) + + return resp, reset + + async def start(self) -> None: + """Process incoming request. + + It reads request line, request headers and request payload, then + calls handle_request() method. Subclass has to override + handle_request(). start() handles various exceptions in request + or response handling. Connection is being closed always unless + keep_alive(True) specified. + """ + loop = self._loop + manager = self._manager + assert manager is not None + keepalive_timeout = self._keepalive_timeout + resp = None + assert self._request_factory is not None + assert self._request_handler is not None + + while not self._force_close: + if not self._messages: + try: + # wait for next request + self._waiter = loop.create_future() + await self._waiter + finally: + self._waiter = None + + message, payload = self._messages.popleft() + + # time is only fetched if logging is enabled as otherwise + # its thrown away and never used. + start = loop.time() if self._logging_enabled else None + + manager.requests_count += 1 + writer = StreamWriter(self, loop) + if isinstance(message, _ErrInfo): + # make request_factory work + request_handler = self._make_error_handler(message) + message = ERROR + else: + request_handler = self._request_handler + + # Important don't hold a reference to the current task + # as on traceback it will prevent the task from being + # collected and will cause a memory leak. + request = self._request_factory( + message, + payload, + self, + writer, + self._task_handler or asyncio.current_task(loop), # type: ignore[arg-type] + ) + try: + # a new task is used for copy context vars (#3406) + coro = self._handle_request(request, start, request_handler) + if sys.version_info >= (3, 12): + task = asyncio.Task(coro, loop=loop, eager_start=True) + else: + task = loop.create_task(coro) + try: + resp, reset = await task + except ConnectionError: + self.log_debug("Ignored premature client disconnection") + break + + # Drop the processed task from asyncio.Task.all_tasks() early + del task + if reset: + self.log_debug("Ignored premature client disconnection 2") + break + + # notify server about keep-alive + self._keepalive = bool(resp.keep_alive) + + # check payload + if not payload.is_eof(): + lingering_time = self._lingering_time + if not self._force_close and lingering_time: + self.log_debug( + "Start lingering close timer for %s sec.", lingering_time + ) + + now = loop.time() + end_t = now + lingering_time + + try: + while not payload.is_eof() and now < end_t: + async with ceil_timeout(end_t - now): + # read and ignore + await payload.readany() + now = loop.time() + except (asyncio.CancelledError, asyncio.TimeoutError): + if ( + sys.version_info >= (3, 11) + and (t := asyncio.current_task()) + and t.cancelling() + ): + raise + + # if payload still uncompleted + if not payload.is_eof() and not self._force_close: + self.log_debug("Uncompleted request.") + self.close() + + payload.set_exception(_PAYLOAD_ACCESS_ERROR) + + except asyncio.CancelledError: + self.log_debug("Ignored premature client disconnection") + self.force_close() + raise + except Exception as exc: + self.log_exception("Unhandled exception", exc_info=exc) + self.force_close() + except BaseException: + self.force_close() + raise + finally: + request._task = None # type: ignore[assignment] # Break reference cycle in case of exception + if self.transport is None and resp is not None: + self.log_debug("Ignored premature client disconnection.") + + if self._keepalive and not self._close and not self._force_close: + # start keep-alive timer + close_time = loop.time() + keepalive_timeout + self._next_keepalive_close_time = close_time + if self._keepalive_handle is None: + self._keepalive_handle = loop.call_at( + close_time, self._process_keepalive + ) + else: + break + + # remove handler, close transport if no handlers left + if not self._force_close: + self._task_handler = None + if self.transport is not None: + self.transport.close() + + async def finish_response( + self, request: BaseRequest, resp: StreamResponse, start_time: Optional[float] + ) -> Tuple[StreamResponse, bool]: + """Prepare the response and write_eof, then log access. + + This has to + be called within the context of any exception so the access logger + can get exception information. Returns True if the client disconnects + prematurely. + """ + request._finish() + if self._request_parser is not None: + self._request_parser.set_upgraded(False) + self._upgrade = False + if self._message_tail: + self._request_parser.feed_data(self._message_tail) + self._message_tail = b"" + try: + prepare_meth = resp.prepare + except AttributeError: + if resp is None: + self.log_exception("Missing return statement on request handler") + else: + self.log_exception( + "Web-handler should return a response instance, " + "got {!r}".format(resp) + ) + exc = HTTPInternalServerError() + resp = Response( + status=exc.status, reason=exc.reason, text=exc.text, headers=exc.headers + ) + prepare_meth = resp.prepare + try: + await prepare_meth(request) + await resp.write_eof() + except ConnectionError: + self.log_access(request, resp, start_time) + return resp, True + + self.log_access(request, resp, start_time) + return resp, False + + def handle_error( + self, + request: BaseRequest, + status: int = 500, + exc: Optional[BaseException] = None, + message: Optional[str] = None, + ) -> StreamResponse: + """Handle errors. + + Returns HTTP response with specific status code. Logs additional + information. It always closes current connection. + """ + if self._request_count == 1 and isinstance(exc, BadHttpMethod): + # BadHttpMethod is common when a client sends non-HTTP + # or encrypted traffic to an HTTP port. This is expected + # to happen when connected to the public internet so we log + # it at the debug level as to not fill logs with noise. + self.logger.debug( + "Error handling request from %s", request.remote, exc_info=exc + ) + else: + self.log_exception( + "Error handling request from %s", request.remote, exc_info=exc + ) + + # some data already got sent, connection is broken + if request.writer.output_size > 0: + raise ConnectionError( + "Response is sent already, cannot send another response " + "with the error message" + ) + + ct = "text/plain" + if status == HTTPStatus.INTERNAL_SERVER_ERROR: + title = "{0.value} {0.phrase}".format(HTTPStatus.INTERNAL_SERVER_ERROR) + msg = HTTPStatus.INTERNAL_SERVER_ERROR.description + tb = None + if self.debug: + with suppress(Exception): + tb = traceback.format_exc() + + if "text/html" in request.headers.get("Accept", ""): + if tb: + tb = html_escape(tb) + msg = f"

Traceback:

\n
{tb}
" + message = ( + "" + "{title}" + "\n

{title}

" + "\n{msg}\n\n" + ).format(title=title, msg=msg) + ct = "text/html" + else: + if tb: + msg = tb + message = title + "\n\n" + msg + + resp = Response(status=status, text=message, content_type=ct) + resp.force_close() + + return resp + + def _make_error_handler( + self, err_info: _ErrInfo + ) -> Callable[[BaseRequest], Awaitable[StreamResponse]]: + async def handler(request: BaseRequest) -> StreamResponse: + return self.handle_error( + request, err_info.status, err_info.exc, err_info.message + ) + + return handler diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_request.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_request.py new file mode 100644 index 0000000000000000000000000000000000000000..0bc69b74db94f388fec4035ff5789bbf9ff98445 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_request.py @@ -0,0 +1,916 @@ +import asyncio +import datetime +import io +import re +import socket +import string +import tempfile +import types +import warnings +from types import MappingProxyType +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Final, + Iterator, + Mapping, + MutableMapping, + Optional, + Pattern, + Tuple, + Union, + cast, +) +from urllib.parse import parse_qsl + +import attr +from multidict import ( + CIMultiDict, + CIMultiDictProxy, + MultiDict, + MultiDictProxy, + MultiMapping, +) +from yarl import URL + +from . import hdrs +from ._cookie_helpers import parse_cookie_header +from .abc import AbstractStreamWriter +from .helpers import ( + _SENTINEL, + DEBUG, + ETAG_ANY, + LIST_QUOTED_ETAG_RE, + ChainMapProxy, + ETag, + HeadersMixin, + parse_http_date, + reify, + sentinel, + set_exception, +) +from .http_parser import RawRequestMessage +from .http_writer import HttpVersion +from .multipart import BodyPartReader, MultipartReader +from .streams import EmptyStreamReader, StreamReader +from .typedefs import ( + DEFAULT_JSON_DECODER, + JSONDecoder, + LooseHeaders, + RawHeaders, + StrOrURL, +) +from .web_exceptions import HTTPRequestEntityTooLarge +from .web_response import StreamResponse + +__all__ = ("BaseRequest", "FileField", "Request") + + +if TYPE_CHECKING: + from .web_app import Application + from .web_protocol import RequestHandler + from .web_urldispatcher import UrlMappingMatchInfo + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class FileField: + name: str + filename: str + file: io.BufferedReader + content_type: str + headers: CIMultiDictProxy[str] + + +_TCHAR: Final[str] = string.digits + string.ascii_letters + r"!#$%&'*+.^_`|~-" +# '-' at the end to prevent interpretation as range in a char class + +_TOKEN: Final[str] = rf"[{_TCHAR}]+" + +_QDTEXT: Final[str] = r"[{}]".format( + r"".join(chr(c) for c in (0x09, 0x20, 0x21) + tuple(range(0x23, 0x7F))) +) +# qdtext includes 0x5C to escape 0x5D ('\]') +# qdtext excludes obs-text (because obsoleted, and encoding not specified) + +_QUOTED_PAIR: Final[str] = r"\\[\t !-~]" + +_QUOTED_STRING: Final[str] = r'"(?:{quoted_pair}|{qdtext})*"'.format( + qdtext=_QDTEXT, quoted_pair=_QUOTED_PAIR +) + +_FORWARDED_PAIR: Final[str] = ( + r"({token})=({token}|{quoted_string})(:\d{{1,4}})?".format( + token=_TOKEN, quoted_string=_QUOTED_STRING + ) +) + +_QUOTED_PAIR_REPLACE_RE: Final[Pattern[str]] = re.compile(r"\\([\t !-~])") +# same pattern as _QUOTED_PAIR but contains a capture group + +_FORWARDED_PAIR_RE: Final[Pattern[str]] = re.compile(_FORWARDED_PAIR) + +############################################################ +# HTTP Request +############################################################ + + +class BaseRequest(MutableMapping[str, Any], HeadersMixin): + + POST_METHODS = { + hdrs.METH_PATCH, + hdrs.METH_POST, + hdrs.METH_PUT, + hdrs.METH_TRACE, + hdrs.METH_DELETE, + } + + ATTRS = HeadersMixin.ATTRS | frozenset( + [ + "_message", + "_protocol", + "_payload_writer", + "_payload", + "_headers", + "_method", + "_version", + "_rel_url", + "_post", + "_read_bytes", + "_state", + "_cache", + "_task", + "_client_max_size", + "_loop", + "_transport_sslcontext", + "_transport_peername", + ] + ) + _post: Optional[MultiDictProxy[Union[str, bytes, FileField]]] = None + _read_bytes: Optional[bytes] = None + + def __init__( + self, + message: RawRequestMessage, + payload: StreamReader, + protocol: "RequestHandler", + payload_writer: AbstractStreamWriter, + task: "asyncio.Task[None]", + loop: asyncio.AbstractEventLoop, + *, + client_max_size: int = 1024**2, + state: Optional[Dict[str, Any]] = None, + scheme: Optional[str] = None, + host: Optional[str] = None, + remote: Optional[str] = None, + ) -> None: + self._message = message + self._protocol = protocol + self._payload_writer = payload_writer + + self._payload = payload + self._headers: CIMultiDictProxy[str] = message.headers + self._method = message.method + self._version = message.version + self._cache: Dict[str, Any] = {} + url = message.url + if url.absolute: + if scheme is not None: + url = url.with_scheme(scheme) + if host is not None: + url = url.with_host(host) + # absolute URL is given, + # override auto-calculating url, host, and scheme + # all other properties should be good + self._cache["url"] = url + self._cache["host"] = url.host + self._cache["scheme"] = url.scheme + self._rel_url = url.relative() + else: + self._rel_url = url + if scheme is not None: + self._cache["scheme"] = scheme + if host is not None: + self._cache["host"] = host + + self._state = {} if state is None else state + self._task = task + self._client_max_size = client_max_size + self._loop = loop + + self._transport_sslcontext = protocol.ssl_context + self._transport_peername = protocol.peername + + if remote is not None: + self._cache["remote"] = remote + + def clone( + self, + *, + method: Union[str, _SENTINEL] = sentinel, + rel_url: Union[StrOrURL, _SENTINEL] = sentinel, + headers: Union[LooseHeaders, _SENTINEL] = sentinel, + scheme: Union[str, _SENTINEL] = sentinel, + host: Union[str, _SENTINEL] = sentinel, + remote: Union[str, _SENTINEL] = sentinel, + client_max_size: Union[int, _SENTINEL] = sentinel, + ) -> "BaseRequest": + """Clone itself with replacement some attributes. + + Creates and returns a new instance of Request object. If no parameters + are given, an exact copy is returned. If a parameter is not passed, it + will reuse the one from the current request object. + """ + if self._read_bytes: + raise RuntimeError("Cannot clone request after reading its content") + + dct: Dict[str, Any] = {} + if method is not sentinel: + dct["method"] = method + if rel_url is not sentinel: + new_url: URL = URL(rel_url) + dct["url"] = new_url + dct["path"] = str(new_url) + if headers is not sentinel: + # a copy semantic + dct["headers"] = CIMultiDictProxy(CIMultiDict(headers)) + dct["raw_headers"] = tuple( + (k.encode("utf-8"), v.encode("utf-8")) + for k, v in dct["headers"].items() + ) + + message = self._message._replace(**dct) + + kwargs = {} + if scheme is not sentinel: + kwargs["scheme"] = scheme + if host is not sentinel: + kwargs["host"] = host + if remote is not sentinel: + kwargs["remote"] = remote + if client_max_size is sentinel: + client_max_size = self._client_max_size + + return self.__class__( + message, + self._payload, + self._protocol, + self._payload_writer, + self._task, + self._loop, + client_max_size=client_max_size, + state=self._state.copy(), + **kwargs, + ) + + @property + def task(self) -> "asyncio.Task[None]": + return self._task + + @property + def protocol(self) -> "RequestHandler": + return self._protocol + + @property + def transport(self) -> Optional[asyncio.Transport]: + if self._protocol is None: + return None + return self._protocol.transport + + @property + def writer(self) -> AbstractStreamWriter: + return self._payload_writer + + @property + def client_max_size(self) -> int: + return self._client_max_size + + @reify + def message(self) -> RawRequestMessage: + warnings.warn("Request.message is deprecated", DeprecationWarning, stacklevel=3) + return self._message + + @reify + def rel_url(self) -> URL: + return self._rel_url + + @reify + def loop(self) -> asyncio.AbstractEventLoop: + warnings.warn( + "request.loop property is deprecated", DeprecationWarning, stacklevel=2 + ) + return self._loop + + # MutableMapping API + + def __getitem__(self, key: str) -> Any: + return self._state[key] + + def __setitem__(self, key: str, value: Any) -> None: + self._state[key] = value + + def __delitem__(self, key: str) -> None: + del self._state[key] + + def __len__(self) -> int: + return len(self._state) + + def __iter__(self) -> Iterator[str]: + return iter(self._state) + + ######## + + @reify + def secure(self) -> bool: + """A bool indicating if the request is handled with SSL.""" + return self.scheme == "https" + + @reify + def forwarded(self) -> Tuple[Mapping[str, str], ...]: + """A tuple containing all parsed Forwarded header(s). + + Makes an effort to parse Forwarded headers as specified by RFC 7239: + + - It adds one (immutable) dictionary per Forwarded 'field-value', ie + per proxy. The element corresponds to the data in the Forwarded + field-value added by the first proxy encountered by the client. Each + subsequent item corresponds to those added by later proxies. + - It checks that every value has valid syntax in general as specified + in section 4: either a 'token' or a 'quoted-string'. + - It un-escapes found escape sequences. + - It does NOT validate 'by' and 'for' contents as specified in section + 6. + - It does NOT validate 'host' contents (Host ABNF). + - It does NOT validate 'proto' contents for valid URI scheme names. + + Returns a tuple containing one or more immutable dicts + """ + elems = [] + for field_value in self._message.headers.getall(hdrs.FORWARDED, ()): + length = len(field_value) + pos = 0 + need_separator = False + elem: Dict[str, str] = {} + elems.append(types.MappingProxyType(elem)) + while 0 <= pos < length: + match = _FORWARDED_PAIR_RE.match(field_value, pos) + if match is not None: # got a valid forwarded-pair + if need_separator: + # bad syntax here, skip to next comma + pos = field_value.find(",", pos) + else: + name, value, port = match.groups() + if value[0] == '"': + # quoted string: remove quotes and unescape + value = _QUOTED_PAIR_REPLACE_RE.sub(r"\1", value[1:-1]) + if port: + value += port + elem[name.lower()] = value + pos += len(match.group(0)) + need_separator = True + elif field_value[pos] == ",": # next forwarded-element + need_separator = False + elem = {} + elems.append(types.MappingProxyType(elem)) + pos += 1 + elif field_value[pos] == ";": # next forwarded-pair + need_separator = False + pos += 1 + elif field_value[pos] in " \t": + # Allow whitespace even between forwarded-pairs, though + # RFC 7239 doesn't. This simplifies code and is in line + # with Postel's law. + pos += 1 + else: + # bad syntax here, skip to next comma + pos = field_value.find(",", pos) + return tuple(elems) + + @reify + def scheme(self) -> str: + """A string representing the scheme of the request. + + Hostname is resolved in this order: + + - overridden value by .clone(scheme=new_scheme) call. + - type of connection to peer: HTTPS if socket is SSL, HTTP otherwise. + + 'http' or 'https'. + """ + if self._transport_sslcontext: + return "https" + else: + return "http" + + @reify + def method(self) -> str: + """Read only property for getting HTTP method. + + The value is upper-cased str like 'GET', 'POST', 'PUT' etc. + """ + return self._method + + @reify + def version(self) -> HttpVersion: + """Read only property for getting HTTP version of request. + + Returns aiohttp.protocol.HttpVersion instance. + """ + return self._version + + @reify + def host(self) -> str: + """Hostname of the request. + + Hostname is resolved in this order: + + - overridden value by .clone(host=new_host) call. + - HOST HTTP header + - socket.getfqdn() value + + For example, 'example.com' or 'localhost:8080'. + + For historical reasons, the port number may be included. + """ + host = self._message.headers.get(hdrs.HOST) + if host is not None: + return host + return socket.getfqdn() + + @reify + def remote(self) -> Optional[str]: + """Remote IP of client initiated HTTP request. + + The IP is resolved in this order: + + - overridden value by .clone(remote=new_remote) call. + - peername of opened socket + """ + if self._transport_peername is None: + return None + if isinstance(self._transport_peername, (list, tuple)): + return str(self._transport_peername[0]) + return str(self._transport_peername) + + @reify + def url(self) -> URL: + """The full URL of the request.""" + # authority is used here because it may include the port number + # and we want yarl to parse it correctly + return URL.build(scheme=self.scheme, authority=self.host).join(self._rel_url) + + @reify + def path(self) -> str: + """The URL including *PATH INFO* without the host or scheme. + + E.g., ``/app/blog`` + """ + return self._rel_url.path + + @reify + def path_qs(self) -> str: + """The URL including PATH_INFO and the query string. + + E.g, /app/blog?id=10 + """ + return str(self._rel_url) + + @reify + def raw_path(self) -> str: + """The URL including raw *PATH INFO* without the host or scheme. + + Warning, the path is unquoted and may contains non valid URL characters + + E.g., ``/my%2Fpath%7Cwith%21some%25strange%24characters`` + """ + return self._message.path + + @reify + def query(self) -> "MultiMapping[str]": + """A multidict with all the variables in the query string.""" + return self._rel_url.query + + @reify + def query_string(self) -> str: + """The query string in the URL. + + E.g., id=10 + """ + return self._rel_url.query_string + + @reify + def headers(self) -> CIMultiDictProxy[str]: + """A case-insensitive multidict proxy with all headers.""" + return self._headers + + @reify + def raw_headers(self) -> RawHeaders: + """A sequence of pairs for all headers.""" + return self._message.raw_headers + + @reify + def if_modified_since(self) -> Optional[datetime.datetime]: + """The value of If-Modified-Since HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self.headers.get(hdrs.IF_MODIFIED_SINCE)) + + @reify + def if_unmodified_since(self) -> Optional[datetime.datetime]: + """The value of If-Unmodified-Since HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self.headers.get(hdrs.IF_UNMODIFIED_SINCE)) + + @staticmethod + def _etag_values(etag_header: str) -> Iterator[ETag]: + """Extract `ETag` objects from raw header.""" + if etag_header == ETAG_ANY: + yield ETag( + is_weak=False, + value=ETAG_ANY, + ) + else: + for match in LIST_QUOTED_ETAG_RE.finditer(etag_header): + is_weak, value, garbage = match.group(2, 3, 4) + # Any symbol captured by 4th group means + # that the following sequence is invalid. + if garbage: + break + + yield ETag( + is_weak=bool(is_weak), + value=value, + ) + + @classmethod + def _if_match_or_none_impl( + cls, header_value: Optional[str] + ) -> Optional[Tuple[ETag, ...]]: + if not header_value: + return None + + return tuple(cls._etag_values(header_value)) + + @reify + def if_match(self) -> Optional[Tuple[ETag, ...]]: + """The value of If-Match HTTP header, or None. + + This header is represented as a `tuple` of `ETag` objects. + """ + return self._if_match_or_none_impl(self.headers.get(hdrs.IF_MATCH)) + + @reify + def if_none_match(self) -> Optional[Tuple[ETag, ...]]: + """The value of If-None-Match HTTP header, or None. + + This header is represented as a `tuple` of `ETag` objects. + """ + return self._if_match_or_none_impl(self.headers.get(hdrs.IF_NONE_MATCH)) + + @reify + def if_range(self) -> Optional[datetime.datetime]: + """The value of If-Range HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self.headers.get(hdrs.IF_RANGE)) + + @reify + def keep_alive(self) -> bool: + """Is keepalive enabled by client?""" + return not self._message.should_close + + @reify + def cookies(self) -> Mapping[str, str]: + """Return request cookies. + + A read-only dictionary-like object. + """ + # Use parse_cookie_header for RFC 6265 compliant Cookie header parsing + # that accepts special characters in cookie names (fixes #2683) + parsed = parse_cookie_header(self.headers.get(hdrs.COOKIE, "")) + # Extract values from Morsel objects + return MappingProxyType({name: morsel.value for name, morsel in parsed}) + + @reify + def http_range(self) -> slice: + """The content of Range HTTP header. + + Return a slice instance. + + """ + rng = self._headers.get(hdrs.RANGE) + start, end = None, None + if rng is not None: + try: + pattern = r"^bytes=(\d*)-(\d*)$" + start, end = re.findall(pattern, rng)[0] + except IndexError: # pattern was not found in header + raise ValueError("range not in acceptable format") + + end = int(end) if end else None + start = int(start) if start else None + + if start is None and end is not None: + # end with no start is to return tail of content + start = -end + end = None + + if start is not None and end is not None: + # end is inclusive in range header, exclusive for slice + end += 1 + + if start >= end: + raise ValueError("start cannot be after end") + + if start is end is None: # No valid range supplied + raise ValueError("No start or end of range specified") + + return slice(start, end, 1) + + @reify + def content(self) -> StreamReader: + """Return raw payload stream.""" + return self._payload + + @property + def has_body(self) -> bool: + """Return True if request's HTTP BODY can be read, False otherwise.""" + warnings.warn( + "Deprecated, use .can_read_body #2005", DeprecationWarning, stacklevel=2 + ) + return not self._payload.at_eof() + + @property + def can_read_body(self) -> bool: + """Return True if request's HTTP BODY can be read, False otherwise.""" + return not self._payload.at_eof() + + @reify + def body_exists(self) -> bool: + """Return True if request has HTTP BODY, False otherwise.""" + return type(self._payload) is not EmptyStreamReader + + async def release(self) -> None: + """Release request. + + Eat unread part of HTTP BODY if present. + """ + while not self._payload.at_eof(): + await self._payload.readany() + + async def read(self) -> bytes: + """Read request body if present. + + Returns bytes object with full request content. + """ + if self._read_bytes is None: + body = bytearray() + while True: + chunk = await self._payload.readany() + body.extend(chunk) + if self._client_max_size: + body_size = len(body) + if body_size >= self._client_max_size: + raise HTTPRequestEntityTooLarge( + max_size=self._client_max_size, actual_size=body_size + ) + if not chunk: + break + self._read_bytes = bytes(body) + return self._read_bytes + + async def text(self) -> str: + """Return BODY as text using encoding from .charset.""" + bytes_body = await self.read() + encoding = self.charset or "utf-8" + return bytes_body.decode(encoding) + + async def json(self, *, loads: JSONDecoder = DEFAULT_JSON_DECODER) -> Any: + """Return BODY as JSON.""" + body = await self.text() + return loads(body) + + async def multipart(self) -> MultipartReader: + """Return async iterator to process BODY as multipart.""" + return MultipartReader(self._headers, self._payload) + + async def post(self) -> "MultiDictProxy[Union[str, bytes, FileField]]": + """Return POST parameters.""" + if self._post is not None: + return self._post + if self._method not in self.POST_METHODS: + self._post = MultiDictProxy(MultiDict()) + return self._post + + content_type = self.content_type + if content_type not in ( + "", + "application/x-www-form-urlencoded", + "multipart/form-data", + ): + self._post = MultiDictProxy(MultiDict()) + return self._post + + out: MultiDict[Union[str, bytes, FileField]] = MultiDict() + + if content_type == "multipart/form-data": + multipart = await self.multipart() + max_size = self._client_max_size + + field = await multipart.next() + while field is not None: + size = 0 + field_ct = field.headers.get(hdrs.CONTENT_TYPE) + + if isinstance(field, BodyPartReader): + assert field.name is not None + + # Note that according to RFC 7578, the Content-Type header + # is optional, even for files, so we can't assume it's + # present. + # https://tools.ietf.org/html/rfc7578#section-4.4 + if field.filename: + # store file in temp file + tmp = await self._loop.run_in_executor( + None, tempfile.TemporaryFile + ) + chunk = await field.read_chunk(size=2**16) + while chunk: + chunk = field.decode(chunk) + await self._loop.run_in_executor(None, tmp.write, chunk) + size += len(chunk) + if 0 < max_size < size: + await self._loop.run_in_executor(None, tmp.close) + raise HTTPRequestEntityTooLarge( + max_size=max_size, actual_size=size + ) + chunk = await field.read_chunk(size=2**16) + await self._loop.run_in_executor(None, tmp.seek, 0) + + if field_ct is None: + field_ct = "application/octet-stream" + + ff = FileField( + field.name, + field.filename, + cast(io.BufferedReader, tmp), + field_ct, + field.headers, + ) + out.add(field.name, ff) + else: + # deal with ordinary data + value = await field.read(decode=True) + if field_ct is None or field_ct.startswith("text/"): + charset = field.get_charset(default="utf-8") + out.add(field.name, value.decode(charset)) + else: + out.add(field.name, value) + size += len(value) + if 0 < max_size < size: + raise HTTPRequestEntityTooLarge( + max_size=max_size, actual_size=size + ) + else: + raise ValueError( + "To decode nested multipart you need to use custom reader", + ) + + field = await multipart.next() + else: + data = await self.read() + if data: + charset = self.charset or "utf-8" + out.extend( + parse_qsl( + data.rstrip().decode(charset), + keep_blank_values=True, + encoding=charset, + ) + ) + + self._post = MultiDictProxy(out) + return self._post + + def get_extra_info(self, name: str, default: Any = None) -> Any: + """Extra info from protocol transport""" + protocol = self._protocol + if protocol is None: + return default + + transport = protocol.transport + if transport is None: + return default + + return transport.get_extra_info(name, default) + + def __repr__(self) -> str: + ascii_encodable_path = self.path.encode("ascii", "backslashreplace").decode( + "ascii" + ) + return "<{} {} {} >".format( + self.__class__.__name__, self._method, ascii_encodable_path + ) + + def __eq__(self, other: object) -> bool: + return id(self) == id(other) + + def __bool__(self) -> bool: + return True + + async def _prepare_hook(self, response: StreamResponse) -> None: + return + + def _cancel(self, exc: BaseException) -> None: + set_exception(self._payload, exc) + + def _finish(self) -> None: + if self._post is None or self.content_type != "multipart/form-data": + return + + # NOTE: Release file descriptors for the + # NOTE: `tempfile.Temporaryfile`-created `_io.BufferedRandom` + # NOTE: instances of files sent within multipart request body + # NOTE: via HTTP POST request. + for file_name, file_field_object in self._post.items(): + if isinstance(file_field_object, FileField): + file_field_object.file.close() + + +class Request(BaseRequest): + + ATTRS = BaseRequest.ATTRS | frozenset(["_match_info"]) + + _match_info: Optional["UrlMappingMatchInfo"] = None + + if DEBUG: + + def __setattr__(self, name: str, val: Any) -> None: + if name not in self.ATTRS: + warnings.warn( + "Setting custom {}.{} attribute " + "is discouraged".format(self.__class__.__name__, name), + DeprecationWarning, + stacklevel=2, + ) + super().__setattr__(name, val) + + def clone( + self, + *, + method: Union[str, _SENTINEL] = sentinel, + rel_url: Union[StrOrURL, _SENTINEL] = sentinel, + headers: Union[LooseHeaders, _SENTINEL] = sentinel, + scheme: Union[str, _SENTINEL] = sentinel, + host: Union[str, _SENTINEL] = sentinel, + remote: Union[str, _SENTINEL] = sentinel, + client_max_size: Union[int, _SENTINEL] = sentinel, + ) -> "Request": + ret = super().clone( + method=method, + rel_url=rel_url, + headers=headers, + scheme=scheme, + host=host, + remote=remote, + client_max_size=client_max_size, + ) + new_ret = cast(Request, ret) + new_ret._match_info = self._match_info + return new_ret + + @reify + def match_info(self) -> "UrlMappingMatchInfo": + """Result of route resolving.""" + match_info = self._match_info + assert match_info is not None + return match_info + + @property + def app(self) -> "Application": + """Application instance.""" + match_info = self._match_info + assert match_info is not None + return match_info.current_app + + @property + def config_dict(self) -> ChainMapProxy: + match_info = self._match_info + assert match_info is not None + lst = match_info.apps + app = self.app + idx = lst.index(app) + sublist = list(reversed(lst[: idx + 1])) + return ChainMapProxy(sublist) + + async def _prepare_hook(self, response: StreamResponse) -> None: + match_info = self._match_info + if match_info is None: + return + for app in match_info._apps: + if on_response_prepare := app.on_response_prepare: + await on_response_prepare.send(self, response) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_response.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_response.py new file mode 100644 index 0000000000000000000000000000000000000000..cdc90cc4f1ca51f99acb6b0c56b23bf3f42d6c1e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_response.py @@ -0,0 +1,856 @@ +import asyncio +import collections.abc +import datetime +import enum +import json +import math +import time +import warnings +from concurrent.futures import Executor +from http import HTTPStatus +from http.cookies import SimpleCookie +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Iterator, + MutableMapping, + Optional, + Union, + cast, +) + +from multidict import CIMultiDict, istr + +from . import hdrs, payload +from .abc import AbstractStreamWriter +from .compression_utils import ZLibCompressor +from .helpers import ( + ETAG_ANY, + QUOTED_ETAG_RE, + ETag, + HeadersMixin, + must_be_empty_body, + parse_http_date, + rfc822_formatted_time, + sentinel, + should_remove_content_length, + validate_etag_value, +) +from .http import SERVER_SOFTWARE, HttpVersion10, HttpVersion11 +from .payload import Payload +from .typedefs import JSONEncoder, LooseHeaders + +REASON_PHRASES = {http_status.value: http_status.phrase for http_status in HTTPStatus} +LARGE_BODY_SIZE = 1024**2 + +__all__ = ("ContentCoding", "StreamResponse", "Response", "json_response") + + +if TYPE_CHECKING: + from .web_request import BaseRequest + + BaseClass = MutableMapping[str, Any] +else: + BaseClass = collections.abc.MutableMapping + + +# TODO(py311): Convert to StrEnum for wider use +class ContentCoding(enum.Enum): + # The content codings that we have support for. + # + # Additional registered codings are listed at: + # https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#content-coding + deflate = "deflate" + gzip = "gzip" + identity = "identity" + + +CONTENT_CODINGS = {coding.value: coding for coding in ContentCoding} + +############################################################ +# HTTP Response classes +############################################################ + + +class StreamResponse(BaseClass, HeadersMixin): + + _body: Union[None, bytes, bytearray, Payload] + _length_check = True + _body = None + _keep_alive: Optional[bool] = None + _chunked: bool = False + _compression: bool = False + _compression_strategy: Optional[int] = None + _compression_force: Optional[ContentCoding] = None + _req: Optional["BaseRequest"] = None + _payload_writer: Optional[AbstractStreamWriter] = None + _eof_sent: bool = False + _must_be_empty_body: Optional[bool] = None + _body_length = 0 + _cookies: Optional[SimpleCookie] = None + _send_headers_immediately = True + + def __init__( + self, + *, + status: int = 200, + reason: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + _real_headers: Optional[CIMultiDict[str]] = None, + ) -> None: + """Initialize a new stream response object. + + _real_headers is an internal parameter used to pass a pre-populated + headers object. It is used by the `Response` class to avoid copying + the headers when creating a new response object. It is not intended + to be used by external code. + """ + self._state: Dict[str, Any] = {} + + if _real_headers is not None: + self._headers = _real_headers + elif headers is not None: + self._headers: CIMultiDict[str] = CIMultiDict(headers) + else: + self._headers = CIMultiDict() + + self._set_status(status, reason) + + @property + def prepared(self) -> bool: + return self._eof_sent or self._payload_writer is not None + + @property + def task(self) -> "Optional[asyncio.Task[None]]": + if self._req: + return self._req.task + else: + return None + + @property + def status(self) -> int: + return self._status + + @property + def chunked(self) -> bool: + return self._chunked + + @property + def compression(self) -> bool: + return self._compression + + @property + def reason(self) -> str: + return self._reason + + def set_status( + self, + status: int, + reason: Optional[str] = None, + ) -> None: + assert ( + not self.prepared + ), "Cannot change the response status code after the headers have been sent" + self._set_status(status, reason) + + def _set_status(self, status: int, reason: Optional[str]) -> None: + self._status = int(status) + if reason is None: + reason = REASON_PHRASES.get(self._status, "") + elif "\n" in reason: + raise ValueError("Reason cannot contain \\n") + self._reason = reason + + @property + def keep_alive(self) -> Optional[bool]: + return self._keep_alive + + def force_close(self) -> None: + self._keep_alive = False + + @property + def body_length(self) -> int: + return self._body_length + + @property + def output_length(self) -> int: + warnings.warn("output_length is deprecated", DeprecationWarning) + assert self._payload_writer + return self._payload_writer.buffer_size + + def enable_chunked_encoding(self, chunk_size: Optional[int] = None) -> None: + """Enables automatic chunked transfer encoding.""" + if hdrs.CONTENT_LENGTH in self._headers: + raise RuntimeError( + "You can't enable chunked encoding when a content length is set" + ) + if chunk_size is not None: + warnings.warn("Chunk size is deprecated #1615", DeprecationWarning) + self._chunked = True + + def enable_compression( + self, + force: Optional[Union[bool, ContentCoding]] = None, + strategy: Optional[int] = None, + ) -> None: + """Enables response compression encoding.""" + # Backwards compatibility for when force was a bool <0.17. + if isinstance(force, bool): + force = ContentCoding.deflate if force else ContentCoding.identity + warnings.warn( + "Using boolean for force is deprecated #3318", DeprecationWarning + ) + elif force is not None: + assert isinstance( + force, ContentCoding + ), "force should one of None, bool or ContentEncoding" + + self._compression = True + self._compression_force = force + self._compression_strategy = strategy + + @property + def headers(self) -> "CIMultiDict[str]": + return self._headers + + @property + def cookies(self) -> SimpleCookie: + if self._cookies is None: + self._cookies = SimpleCookie() + return self._cookies + + def set_cookie( + self, + name: str, + value: str, + *, + expires: Optional[str] = None, + domain: Optional[str] = None, + max_age: Optional[Union[int, str]] = None, + path: str = "/", + secure: Optional[bool] = None, + httponly: Optional[bool] = None, + version: Optional[str] = None, + samesite: Optional[str] = None, + partitioned: Optional[bool] = None, + ) -> None: + """Set or update response cookie. + + Sets new cookie or updates existent with new value. + Also updates only those params which are not None. + """ + if self._cookies is None: + self._cookies = SimpleCookie() + + self._cookies[name] = value + c = self._cookies[name] + + if expires is not None: + c["expires"] = expires + elif c.get("expires") == "Thu, 01 Jan 1970 00:00:00 GMT": + del c["expires"] + + if domain is not None: + c["domain"] = domain + + if max_age is not None: + c["max-age"] = str(max_age) + elif "max-age" in c: + del c["max-age"] + + c["path"] = path + + if secure is not None: + c["secure"] = secure + if httponly is not None: + c["httponly"] = httponly + if version is not None: + c["version"] = version + if samesite is not None: + c["samesite"] = samesite + + if partitioned is not None: + c["partitioned"] = partitioned + + def del_cookie( + self, + name: str, + *, + domain: Optional[str] = None, + path: str = "/", + secure: Optional[bool] = None, + httponly: Optional[bool] = None, + samesite: Optional[str] = None, + ) -> None: + """Delete cookie. + + Creates new empty expired cookie. + """ + # TODO: do we need domain/path here? + if self._cookies is not None: + self._cookies.pop(name, None) + self.set_cookie( + name, + "", + max_age=0, + expires="Thu, 01 Jan 1970 00:00:00 GMT", + domain=domain, + path=path, + secure=secure, + httponly=httponly, + samesite=samesite, + ) + + @property + def content_length(self) -> Optional[int]: + # Just a placeholder for adding setter + return super().content_length + + @content_length.setter + def content_length(self, value: Optional[int]) -> None: + if value is not None: + value = int(value) + if self._chunked: + raise RuntimeError( + "You can't set content length when chunked encoding is enable" + ) + self._headers[hdrs.CONTENT_LENGTH] = str(value) + else: + self._headers.pop(hdrs.CONTENT_LENGTH, None) + + @property + def content_type(self) -> str: + # Just a placeholder for adding setter + return super().content_type + + @content_type.setter + def content_type(self, value: str) -> None: + self.content_type # read header values if needed + self._content_type = str(value) + self._generate_content_type_header() + + @property + def charset(self) -> Optional[str]: + # Just a placeholder for adding setter + return super().charset + + @charset.setter + def charset(self, value: Optional[str]) -> None: + ctype = self.content_type # read header values if needed + if ctype == "application/octet-stream": + raise RuntimeError( + "Setting charset for application/octet-stream " + "doesn't make sense, setup content_type first" + ) + assert self._content_dict is not None + if value is None: + self._content_dict.pop("charset", None) + else: + self._content_dict["charset"] = str(value).lower() + self._generate_content_type_header() + + @property + def last_modified(self) -> Optional[datetime.datetime]: + """The value of Last-Modified HTTP header, or None. + + This header is represented as a `datetime` object. + """ + return parse_http_date(self._headers.get(hdrs.LAST_MODIFIED)) + + @last_modified.setter + def last_modified( + self, value: Optional[Union[int, float, datetime.datetime, str]] + ) -> None: + if value is None: + self._headers.pop(hdrs.LAST_MODIFIED, None) + elif isinstance(value, (int, float)): + self._headers[hdrs.LAST_MODIFIED] = time.strftime( + "%a, %d %b %Y %H:%M:%S GMT", time.gmtime(math.ceil(value)) + ) + elif isinstance(value, datetime.datetime): + self._headers[hdrs.LAST_MODIFIED] = time.strftime( + "%a, %d %b %Y %H:%M:%S GMT", value.utctimetuple() + ) + elif isinstance(value, str): + self._headers[hdrs.LAST_MODIFIED] = value + else: + msg = f"Unsupported type for last_modified: {type(value).__name__}" + raise TypeError(msg) + + @property + def etag(self) -> Optional[ETag]: + quoted_value = self._headers.get(hdrs.ETAG) + if not quoted_value: + return None + elif quoted_value == ETAG_ANY: + return ETag(value=ETAG_ANY) + match = QUOTED_ETAG_RE.fullmatch(quoted_value) + if not match: + return None + is_weak, value = match.group(1, 2) + return ETag( + is_weak=bool(is_weak), + value=value, + ) + + @etag.setter + def etag(self, value: Optional[Union[ETag, str]]) -> None: + if value is None: + self._headers.pop(hdrs.ETAG, None) + elif (isinstance(value, str) and value == ETAG_ANY) or ( + isinstance(value, ETag) and value.value == ETAG_ANY + ): + self._headers[hdrs.ETAG] = ETAG_ANY + elif isinstance(value, str): + validate_etag_value(value) + self._headers[hdrs.ETAG] = f'"{value}"' + elif isinstance(value, ETag) and isinstance(value.value, str): + validate_etag_value(value.value) + hdr_value = f'W/"{value.value}"' if value.is_weak else f'"{value.value}"' + self._headers[hdrs.ETAG] = hdr_value + else: + raise ValueError( + f"Unsupported etag type: {type(value)}. " + f"etag must be str, ETag or None" + ) + + def _generate_content_type_header( + self, CONTENT_TYPE: istr = hdrs.CONTENT_TYPE + ) -> None: + assert self._content_dict is not None + assert self._content_type is not None + params = "; ".join(f"{k}={v}" for k, v in self._content_dict.items()) + if params: + ctype = self._content_type + "; " + params + else: + ctype = self._content_type + self._headers[CONTENT_TYPE] = ctype + + async def _do_start_compression(self, coding: ContentCoding) -> None: + if coding is ContentCoding.identity: + return + assert self._payload_writer is not None + self._headers[hdrs.CONTENT_ENCODING] = coding.value + self._payload_writer.enable_compression( + coding.value, self._compression_strategy + ) + # Compressed payload may have different content length, + # remove the header + self._headers.popall(hdrs.CONTENT_LENGTH, None) + + async def _start_compression(self, request: "BaseRequest") -> None: + if self._compression_force: + await self._do_start_compression(self._compression_force) + return + # Encoding comparisons should be case-insensitive + # https://www.rfc-editor.org/rfc/rfc9110#section-8.4.1 + accept_encoding = request.headers.get(hdrs.ACCEPT_ENCODING, "").lower() + for value, coding in CONTENT_CODINGS.items(): + if value in accept_encoding: + await self._do_start_compression(coding) + return + + async def prepare(self, request: "BaseRequest") -> Optional[AbstractStreamWriter]: + if self._eof_sent: + return None + if self._payload_writer is not None: + return self._payload_writer + self._must_be_empty_body = must_be_empty_body(request.method, self.status) + return await self._start(request) + + async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: + self._req = request + writer = self._payload_writer = request._payload_writer + + await self._prepare_headers() + await request._prepare_hook(self) + await self._write_headers() + + return writer + + async def _prepare_headers(self) -> None: + request = self._req + assert request is not None + writer = self._payload_writer + assert writer is not None + keep_alive = self._keep_alive + if keep_alive is None: + keep_alive = request.keep_alive + self._keep_alive = keep_alive + + version = request.version + + headers = self._headers + if self._cookies: + for cookie in self._cookies.values(): + value = cookie.output(header="")[1:] + headers.add(hdrs.SET_COOKIE, value) + + if self._compression: + await self._start_compression(request) + + if self._chunked: + if version != HttpVersion11: + raise RuntimeError( + "Using chunked encoding is forbidden " + "for HTTP/{0.major}.{0.minor}".format(request.version) + ) + if not self._must_be_empty_body: + writer.enable_chunking() + headers[hdrs.TRANSFER_ENCODING] = "chunked" + elif self._length_check: # Disabled for WebSockets + writer.length = self.content_length + if writer.length is None: + if version >= HttpVersion11: + if not self._must_be_empty_body: + writer.enable_chunking() + headers[hdrs.TRANSFER_ENCODING] = "chunked" + elif not self._must_be_empty_body: + keep_alive = False + + # HTTP 1.1: https://tools.ietf.org/html/rfc7230#section-3.3.2 + # HTTP 1.0: https://tools.ietf.org/html/rfc1945#section-10.4 + if self._must_be_empty_body: + if hdrs.CONTENT_LENGTH in headers and should_remove_content_length( + request.method, self.status + ): + del headers[hdrs.CONTENT_LENGTH] + # https://datatracker.ietf.org/doc/html/rfc9112#section-6.1-10 + # https://datatracker.ietf.org/doc/html/rfc9112#section-6.1-13 + if hdrs.TRANSFER_ENCODING in headers: + del headers[hdrs.TRANSFER_ENCODING] + elif (writer.length if self._length_check else self.content_length) != 0: + # https://www.rfc-editor.org/rfc/rfc9110#section-8.3-5 + headers.setdefault(hdrs.CONTENT_TYPE, "application/octet-stream") + headers.setdefault(hdrs.DATE, rfc822_formatted_time()) + headers.setdefault(hdrs.SERVER, SERVER_SOFTWARE) + + # connection header + if hdrs.CONNECTION not in headers: + if keep_alive: + if version == HttpVersion10: + headers[hdrs.CONNECTION] = "keep-alive" + elif version == HttpVersion11: + headers[hdrs.CONNECTION] = "close" + + async def _write_headers(self) -> None: + request = self._req + assert request is not None + writer = self._payload_writer + assert writer is not None + # status line + version = request.version + status_line = f"HTTP/{version[0]}.{version[1]} {self._status} {self._reason}" + await writer.write_headers(status_line, self._headers) + # Send headers immediately if not opted into buffering + if self._send_headers_immediately: + writer.send_headers() + + async def write(self, data: Union[bytes, bytearray, memoryview]) -> None: + assert isinstance( + data, (bytes, bytearray, memoryview) + ), "data argument must be byte-ish (%r)" % type(data) + + if self._eof_sent: + raise RuntimeError("Cannot call write() after write_eof()") + if self._payload_writer is None: + raise RuntimeError("Cannot call write() before prepare()") + + await self._payload_writer.write(data) + + async def drain(self) -> None: + assert not self._eof_sent, "EOF has already been sent" + assert self._payload_writer is not None, "Response has not been started" + warnings.warn( + "drain method is deprecated, use await resp.write()", + DeprecationWarning, + stacklevel=2, + ) + await self._payload_writer.drain() + + async def write_eof(self, data: bytes = b"") -> None: + assert isinstance( + data, (bytes, bytearray, memoryview) + ), "data argument must be byte-ish (%r)" % type(data) + + if self._eof_sent: + return + + assert self._payload_writer is not None, "Response has not been started" + + await self._payload_writer.write_eof(data) + self._eof_sent = True + self._req = None + self._body_length = self._payload_writer.output_size + self._payload_writer = None + + def __repr__(self) -> str: + if self._eof_sent: + info = "eof" + elif self.prepared: + assert self._req is not None + info = f"{self._req.method} {self._req.path} " + else: + info = "not prepared" + return f"<{self.__class__.__name__} {self.reason} {info}>" + + def __getitem__(self, key: str) -> Any: + return self._state[key] + + def __setitem__(self, key: str, value: Any) -> None: + self._state[key] = value + + def __delitem__(self, key: str) -> None: + del self._state[key] + + def __len__(self) -> int: + return len(self._state) + + def __iter__(self) -> Iterator[str]: + return iter(self._state) + + def __hash__(self) -> int: + return hash(id(self)) + + def __eq__(self, other: object) -> bool: + return self is other + + def __bool__(self) -> bool: + return True + + +class Response(StreamResponse): + + _compressed_body: Optional[bytes] = None + _send_headers_immediately = False + + def __init__( + self, + *, + body: Any = None, + status: int = 200, + reason: Optional[str] = None, + text: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + content_type: Optional[str] = None, + charset: Optional[str] = None, + zlib_executor_size: Optional[int] = None, + zlib_executor: Optional[Executor] = None, + ) -> None: + if body is not None and text is not None: + raise ValueError("body and text are not allowed together") + + if headers is None: + real_headers: CIMultiDict[str] = CIMultiDict() + else: + real_headers = CIMultiDict(headers) + + if content_type is not None and "charset" in content_type: + raise ValueError("charset must not be in content_type argument") + + if text is not None: + if hdrs.CONTENT_TYPE in real_headers: + if content_type or charset: + raise ValueError( + "passing both Content-Type header and " + "content_type or charset params " + "is forbidden" + ) + else: + # fast path for filling headers + if not isinstance(text, str): + raise TypeError("text argument must be str (%r)" % type(text)) + if content_type is None: + content_type = "text/plain" + if charset is None: + charset = "utf-8" + real_headers[hdrs.CONTENT_TYPE] = content_type + "; charset=" + charset + body = text.encode(charset) + text = None + elif hdrs.CONTENT_TYPE in real_headers: + if content_type is not None or charset is not None: + raise ValueError( + "passing both Content-Type header and " + "content_type or charset params " + "is forbidden" + ) + elif content_type is not None: + if charset is not None: + content_type += "; charset=" + charset + real_headers[hdrs.CONTENT_TYPE] = content_type + + super().__init__(status=status, reason=reason, _real_headers=real_headers) + + if text is not None: + self.text = text + else: + self.body = body + + self._zlib_executor_size = zlib_executor_size + self._zlib_executor = zlib_executor + + @property + def body(self) -> Optional[Union[bytes, Payload]]: + return self._body + + @body.setter + def body(self, body: Any) -> None: + if body is None: + self._body = None + elif isinstance(body, (bytes, bytearray)): + self._body = body + else: + try: + self._body = body = payload.PAYLOAD_REGISTRY.get(body) + except payload.LookupError: + raise ValueError("Unsupported body type %r" % type(body)) + + headers = self._headers + + # set content-type + if hdrs.CONTENT_TYPE not in headers: + headers[hdrs.CONTENT_TYPE] = body.content_type + + # copy payload headers + if body.headers: + for key, value in body.headers.items(): + if key not in headers: + headers[key] = value + + self._compressed_body = None + + @property + def text(self) -> Optional[str]: + if self._body is None: + return None + # Note: When _body is a Payload (e.g. FilePayload), this may do blocking I/O + # This is generally safe as most common payloads (BytesPayload, StringPayload) + # don't do blocking I/O, but be careful with file-based payloads + return self._body.decode(self.charset or "utf-8") + + @text.setter + def text(self, text: str) -> None: + assert text is None or isinstance( + text, str + ), "text argument must be str (%r)" % type(text) + + if self.content_type == "application/octet-stream": + self.content_type = "text/plain" + if self.charset is None: + self.charset = "utf-8" + + self._body = text.encode(self.charset) + self._compressed_body = None + + @property + def content_length(self) -> Optional[int]: + if self._chunked: + return None + + if hdrs.CONTENT_LENGTH in self._headers: + return int(self._headers[hdrs.CONTENT_LENGTH]) + + if self._compressed_body is not None: + # Return length of the compressed body + return len(self._compressed_body) + elif isinstance(self._body, Payload): + # A payload without content length, or a compressed payload + return None + elif self._body is not None: + return len(self._body) + else: + return 0 + + @content_length.setter + def content_length(self, value: Optional[int]) -> None: + raise RuntimeError("Content length is set automatically") + + async def write_eof(self, data: bytes = b"") -> None: + if self._eof_sent: + return + if self._compressed_body is None: + body: Optional[Union[bytes, Payload]] = self._body + else: + body = self._compressed_body + assert not data, f"data arg is not supported, got {data!r}" + assert self._req is not None + assert self._payload_writer is not None + if body is None or self._must_be_empty_body: + await super().write_eof() + elif isinstance(self._body, Payload): + await self._body.write(self._payload_writer) + await self._body.close() + await super().write_eof() + else: + await super().write_eof(cast(bytes, body)) + + async def _start(self, request: "BaseRequest") -> AbstractStreamWriter: + if hdrs.CONTENT_LENGTH in self._headers: + if should_remove_content_length(request.method, self.status): + del self._headers[hdrs.CONTENT_LENGTH] + elif not self._chunked: + if isinstance(self._body, Payload): + if self._body.size is not None: + self._headers[hdrs.CONTENT_LENGTH] = str(self._body.size) + else: + body_len = len(self._body) if self._body else "0" + # https://www.rfc-editor.org/rfc/rfc9110.html#section-8.6-7 + if body_len != "0" or ( + self.status != 304 and request.method not in hdrs.METH_HEAD_ALL + ): + self._headers[hdrs.CONTENT_LENGTH] = str(body_len) + + return await super()._start(request) + + async def _do_start_compression(self, coding: ContentCoding) -> None: + if self._chunked or isinstance(self._body, Payload): + return await super()._do_start_compression(coding) + if coding is ContentCoding.identity: + return + # Instead of using _payload_writer.enable_compression, + # compress the whole body + compressor = ZLibCompressor( + encoding=coding.value, + max_sync_chunk_size=self._zlib_executor_size, + executor=self._zlib_executor, + ) + assert self._body is not None + if self._zlib_executor_size is None and len(self._body) > LARGE_BODY_SIZE: + warnings.warn( + "Synchronous compression of large response bodies " + f"({len(self._body)} bytes) might block the async event loop. " + "Consider providing a custom value to zlib_executor_size/" + "zlib_executor response properties or disabling compression on it." + ) + self._compressed_body = ( + await compressor.compress(self._body) + compressor.flush() + ) + self._headers[hdrs.CONTENT_ENCODING] = coding.value + self._headers[hdrs.CONTENT_LENGTH] = str(len(self._compressed_body)) + + +def json_response( + data: Any = sentinel, + *, + text: Optional[str] = None, + body: Optional[bytes] = None, + status: int = 200, + reason: Optional[str] = None, + headers: Optional[LooseHeaders] = None, + content_type: str = "application/json", + dumps: JSONEncoder = json.dumps, +) -> Response: + if data is not sentinel: + if text or body: + raise ValueError("only one of data, text, or body should be specified") + else: + text = dumps(data) + return Response( + text=text, + body=body, + status=status, + reason=reason, + headers=headers, + content_type=content_type, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_routedef.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_routedef.py new file mode 100644 index 0000000000000000000000000000000000000000..f51b6cd00815a4daeabf7ef269a3225b2b764503 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_routedef.py @@ -0,0 +1,214 @@ +import abc +import os # noqa +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterator, + List, + Optional, + Sequence, + Type, + Union, + overload, +) + +import attr + +from . import hdrs +from .abc import AbstractView +from .typedefs import Handler, PathLike + +if TYPE_CHECKING: + from .web_request import Request + from .web_response import StreamResponse + from .web_urldispatcher import AbstractRoute, UrlDispatcher +else: + Request = StreamResponse = UrlDispatcher = AbstractRoute = None + + +__all__ = ( + "AbstractRouteDef", + "RouteDef", + "StaticDef", + "RouteTableDef", + "head", + "options", + "get", + "post", + "patch", + "put", + "delete", + "route", + "view", + "static", +) + + +class AbstractRouteDef(abc.ABC): + @abc.abstractmethod + def register(self, router: UrlDispatcher) -> List[AbstractRoute]: + pass # pragma: no cover + + +_HandlerType = Union[Type[AbstractView], Handler] + + +@attr.s(auto_attribs=True, frozen=True, repr=False, slots=True) +class RouteDef(AbstractRouteDef): + method: str + path: str + handler: _HandlerType + kwargs: Dict[str, Any] + + def __repr__(self) -> str: + info = [] + for name, value in sorted(self.kwargs.items()): + info.append(f", {name}={value!r}") + return " {handler.__name__!r}{info}>".format( + method=self.method, path=self.path, handler=self.handler, info="".join(info) + ) + + def register(self, router: UrlDispatcher) -> List[AbstractRoute]: + if self.method in hdrs.METH_ALL: + reg = getattr(router, "add_" + self.method.lower()) + return [reg(self.path, self.handler, **self.kwargs)] + else: + return [ + router.add_route(self.method, self.path, self.handler, **self.kwargs) + ] + + +@attr.s(auto_attribs=True, frozen=True, repr=False, slots=True) +class StaticDef(AbstractRouteDef): + prefix: str + path: PathLike + kwargs: Dict[str, Any] + + def __repr__(self) -> str: + info = [] + for name, value in sorted(self.kwargs.items()): + info.append(f", {name}={value!r}") + return " {path}{info}>".format( + prefix=self.prefix, path=self.path, info="".join(info) + ) + + def register(self, router: UrlDispatcher) -> List[AbstractRoute]: + resource = router.add_static(self.prefix, self.path, **self.kwargs) + routes = resource.get_info().get("routes", {}) + return list(routes.values()) + + +def route(method: str, path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return RouteDef(method, path, handler, kwargs) + + +def head(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_HEAD, path, handler, **kwargs) + + +def options(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_OPTIONS, path, handler, **kwargs) + + +def get( + path: str, + handler: _HandlerType, + *, + name: Optional[str] = None, + allow_head: bool = True, + **kwargs: Any, +) -> RouteDef: + return route( + hdrs.METH_GET, path, handler, name=name, allow_head=allow_head, **kwargs + ) + + +def post(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_POST, path, handler, **kwargs) + + +def put(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_PUT, path, handler, **kwargs) + + +def patch(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_PATCH, path, handler, **kwargs) + + +def delete(path: str, handler: _HandlerType, **kwargs: Any) -> RouteDef: + return route(hdrs.METH_DELETE, path, handler, **kwargs) + + +def view(path: str, handler: Type[AbstractView], **kwargs: Any) -> RouteDef: + return route(hdrs.METH_ANY, path, handler, **kwargs) + + +def static(prefix: str, path: PathLike, **kwargs: Any) -> StaticDef: + return StaticDef(prefix, path, kwargs) + + +_Deco = Callable[[_HandlerType], _HandlerType] + + +class RouteTableDef(Sequence[AbstractRouteDef]): + """Route definition table""" + + def __init__(self) -> None: + self._items: List[AbstractRouteDef] = [] + + def __repr__(self) -> str: + return f"" + + @overload + def __getitem__(self, index: int) -> AbstractRouteDef: ... + + @overload + def __getitem__(self, index: slice) -> List[AbstractRouteDef]: ... + + def __getitem__(self, index): # type: ignore[no-untyped-def] + return self._items[index] + + def __iter__(self) -> Iterator[AbstractRouteDef]: + return iter(self._items) + + def __len__(self) -> int: + return len(self._items) + + def __contains__(self, item: object) -> bool: + return item in self._items + + def route(self, method: str, path: str, **kwargs: Any) -> _Deco: + def inner(handler: _HandlerType) -> _HandlerType: + self._items.append(RouteDef(method, path, handler, kwargs)) + return handler + + return inner + + def head(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_HEAD, path, **kwargs) + + def get(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_GET, path, **kwargs) + + def post(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_POST, path, **kwargs) + + def put(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_PUT, path, **kwargs) + + def patch(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_PATCH, path, **kwargs) + + def delete(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_DELETE, path, **kwargs) + + def options(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_OPTIONS, path, **kwargs) + + def view(self, path: str, **kwargs: Any) -> _Deco: + return self.route(hdrs.METH_ANY, path, **kwargs) + + def static(self, prefix: str, path: PathLike, **kwargs: Any) -> None: + self._items.append(StaticDef(prefix, path, kwargs)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_runner.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..bcfec727c8419bbc6518085ecedde1f7de8992c9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_runner.py @@ -0,0 +1,399 @@ +import asyncio +import signal +import socket +import warnings +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any, List, Optional, Set + +from yarl import URL + +from .typedefs import PathLike +from .web_app import Application +from .web_server import Server + +if TYPE_CHECKING: + from ssl import SSLContext +else: + try: + from ssl import SSLContext + except ImportError: # pragma: no cover + SSLContext = object # type: ignore[misc,assignment] + +__all__ = ( + "BaseSite", + "TCPSite", + "UnixSite", + "NamedPipeSite", + "SockSite", + "BaseRunner", + "AppRunner", + "ServerRunner", + "GracefulExit", +) + + +class GracefulExit(SystemExit): + code = 1 + + +def _raise_graceful_exit() -> None: + raise GracefulExit() + + +class BaseSite(ABC): + __slots__ = ("_runner", "_ssl_context", "_backlog", "_server") + + def __init__( + self, + runner: "BaseRunner", + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + ) -> None: + if runner.server is None: + raise RuntimeError("Call runner.setup() before making a site") + if shutdown_timeout != 60.0: + msg = "shutdown_timeout should be set on BaseRunner" + warnings.warn(msg, DeprecationWarning, stacklevel=2) + runner._shutdown_timeout = shutdown_timeout + self._runner = runner + self._ssl_context = ssl_context + self._backlog = backlog + self._server: Optional[asyncio.AbstractServer] = None + + @property + @abstractmethod + def name(self) -> str: + pass # pragma: no cover + + @abstractmethod + async def start(self) -> None: + self._runner._reg_site(self) + + async def stop(self) -> None: + self._runner._check_site(self) + if self._server is not None: # Maybe not started yet + self._server.close() + + self._runner._unreg_site(self) + + +class TCPSite(BaseSite): + __slots__ = ("_host", "_port", "_reuse_address", "_reuse_port") + + def __init__( + self, + runner: "BaseRunner", + host: Optional[str] = None, + port: Optional[int] = None, + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + reuse_address: Optional[bool] = None, + reuse_port: Optional[bool] = None, + ) -> None: + super().__init__( + runner, + shutdown_timeout=shutdown_timeout, + ssl_context=ssl_context, + backlog=backlog, + ) + self._host = host + if port is None: + port = 8443 if self._ssl_context else 8080 + self._port = port + self._reuse_address = reuse_address + self._reuse_port = reuse_port + + @property + def name(self) -> str: + scheme = "https" if self._ssl_context else "http" + host = "0.0.0.0" if not self._host else self._host + return str(URL.build(scheme=scheme, host=host, port=self._port)) + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + self._server = await loop.create_server( + server, + self._host, + self._port, + ssl=self._ssl_context, + backlog=self._backlog, + reuse_address=self._reuse_address, + reuse_port=self._reuse_port, + ) + + +class UnixSite(BaseSite): + __slots__ = ("_path",) + + def __init__( + self, + runner: "BaseRunner", + path: PathLike, + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + ) -> None: + super().__init__( + runner, + shutdown_timeout=shutdown_timeout, + ssl_context=ssl_context, + backlog=backlog, + ) + self._path = path + + @property + def name(self) -> str: + scheme = "https" if self._ssl_context else "http" + return f"{scheme}://unix:{self._path}:" + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + self._server = await loop.create_unix_server( + server, + self._path, + ssl=self._ssl_context, + backlog=self._backlog, + ) + + +class NamedPipeSite(BaseSite): + __slots__ = ("_path",) + + def __init__( + self, runner: "BaseRunner", path: str, *, shutdown_timeout: float = 60.0 + ) -> None: + loop = asyncio.get_event_loop() + if not isinstance( + loop, asyncio.ProactorEventLoop # type: ignore[attr-defined] + ): + raise RuntimeError( + "Named Pipes only available in proactor loop under windows" + ) + super().__init__(runner, shutdown_timeout=shutdown_timeout) + self._path = path + + @property + def name(self) -> str: + return self._path + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + _server = await loop.start_serving_pipe( # type: ignore[attr-defined] + server, self._path + ) + self._server = _server[0] + + +class SockSite(BaseSite): + __slots__ = ("_sock", "_name") + + def __init__( + self, + runner: "BaseRunner", + sock: socket.socket, + *, + shutdown_timeout: float = 60.0, + ssl_context: Optional[SSLContext] = None, + backlog: int = 128, + ) -> None: + super().__init__( + runner, + shutdown_timeout=shutdown_timeout, + ssl_context=ssl_context, + backlog=backlog, + ) + self._sock = sock + scheme = "https" if self._ssl_context else "http" + if hasattr(socket, "AF_UNIX") and sock.family == socket.AF_UNIX: + name = f"{scheme}://unix:{sock.getsockname()}:" + else: + host, port = sock.getsockname()[:2] + name = str(URL.build(scheme=scheme, host=host, port=port)) + self._name = name + + @property + def name(self) -> str: + return self._name + + async def start(self) -> None: + await super().start() + loop = asyncio.get_event_loop() + server = self._runner.server + assert server is not None + self._server = await loop.create_server( + server, sock=self._sock, ssl=self._ssl_context, backlog=self._backlog + ) + + +class BaseRunner(ABC): + __slots__ = ("_handle_signals", "_kwargs", "_server", "_sites", "_shutdown_timeout") + + def __init__( + self, + *, + handle_signals: bool = False, + shutdown_timeout: float = 60.0, + **kwargs: Any, + ) -> None: + self._handle_signals = handle_signals + self._kwargs = kwargs + self._server: Optional[Server] = None + self._sites: List[BaseSite] = [] + self._shutdown_timeout = shutdown_timeout + + @property + def server(self) -> Optional[Server]: + return self._server + + @property + def addresses(self) -> List[Any]: + ret: List[Any] = [] + for site in self._sites: + server = site._server + if server is not None: + sockets = server.sockets # type: ignore[attr-defined] + if sockets is not None: + for sock in sockets: + ret.append(sock.getsockname()) + return ret + + @property + def sites(self) -> Set[BaseSite]: + return set(self._sites) + + async def setup(self) -> None: + loop = asyncio.get_event_loop() + + if self._handle_signals: + try: + loop.add_signal_handler(signal.SIGINT, _raise_graceful_exit) + loop.add_signal_handler(signal.SIGTERM, _raise_graceful_exit) + except NotImplementedError: # pragma: no cover + # add_signal_handler is not implemented on Windows + pass + + self._server = await self._make_server() + + @abstractmethod + async def shutdown(self) -> None: + """Call any shutdown hooks to help server close gracefully.""" + + async def cleanup(self) -> None: + # The loop over sites is intentional, an exception on gather() + # leaves self._sites in unpredictable state. + # The loop guaranties that a site is either deleted on success or + # still present on failure + for site in list(self._sites): + await site.stop() + + if self._server: # If setup succeeded + # Yield to event loop to ensure incoming requests prior to stopping the sites + # have all started to be handled before we proceed to close idle connections. + await asyncio.sleep(0) + self._server.pre_shutdown() + await self.shutdown() + await self._server.shutdown(self._shutdown_timeout) + await self._cleanup_server() + + self._server = None + if self._handle_signals: + loop = asyncio.get_running_loop() + try: + loop.remove_signal_handler(signal.SIGINT) + loop.remove_signal_handler(signal.SIGTERM) + except NotImplementedError: # pragma: no cover + # remove_signal_handler is not implemented on Windows + pass + + @abstractmethod + async def _make_server(self) -> Server: + pass # pragma: no cover + + @abstractmethod + async def _cleanup_server(self) -> None: + pass # pragma: no cover + + def _reg_site(self, site: BaseSite) -> None: + if site in self._sites: + raise RuntimeError(f"Site {site} is already registered in runner {self}") + self._sites.append(site) + + def _check_site(self, site: BaseSite) -> None: + if site not in self._sites: + raise RuntimeError(f"Site {site} is not registered in runner {self}") + + def _unreg_site(self, site: BaseSite) -> None: + if site not in self._sites: + raise RuntimeError(f"Site {site} is not registered in runner {self}") + self._sites.remove(site) + + +class ServerRunner(BaseRunner): + """Low-level web server runner""" + + __slots__ = ("_web_server",) + + def __init__( + self, web_server: Server, *, handle_signals: bool = False, **kwargs: Any + ) -> None: + super().__init__(handle_signals=handle_signals, **kwargs) + self._web_server = web_server + + async def shutdown(self) -> None: + pass + + async def _make_server(self) -> Server: + return self._web_server + + async def _cleanup_server(self) -> None: + pass + + +class AppRunner(BaseRunner): + """Web Application runner""" + + __slots__ = ("_app",) + + def __init__( + self, app: Application, *, handle_signals: bool = False, **kwargs: Any + ) -> None: + super().__init__(handle_signals=handle_signals, **kwargs) + if not isinstance(app, Application): + raise TypeError( + "The first argument should be web.Application " + "instance, got {!r}".format(app) + ) + self._app = app + + @property + def app(self) -> Application: + return self._app + + async def shutdown(self) -> None: + await self._app.shutdown() + + async def _make_server(self) -> Server: + loop = asyncio.get_event_loop() + self._app._set_loop(loop) + self._app.on_startup.freeze() + await self._app.startup() + self._app.freeze() + + return self._app._make_handler(loop=loop, **self._kwargs) + + async def _cleanup_server(self) -> None: + await self._app.cleanup() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_server.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_server.py new file mode 100644 index 0000000000000000000000000000000000000000..328aca1e405ef87e4df8a992c32eac092b4af8f0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_server.py @@ -0,0 +1,84 @@ +"""Low level HTTP server.""" + +import asyncio +from typing import Any, Awaitable, Callable, Dict, List, Optional # noqa + +from .abc import AbstractStreamWriter +from .http_parser import RawRequestMessage +from .streams import StreamReader +from .web_protocol import RequestHandler, _RequestFactory, _RequestHandler +from .web_request import BaseRequest + +__all__ = ("Server",) + + +class Server: + def __init__( + self, + handler: _RequestHandler, + *, + request_factory: Optional[_RequestFactory] = None, + handler_cancellation: bool = False, + loop: Optional[asyncio.AbstractEventLoop] = None, + **kwargs: Any, + ) -> None: + self._loop = loop or asyncio.get_running_loop() + self._connections: Dict[RequestHandler, asyncio.Transport] = {} + self._kwargs = kwargs + # requests_count is the number of requests being processed by the server + # for the lifetime of the server. + self.requests_count = 0 + self.request_handler = handler + self.request_factory = request_factory or self._make_request + self.handler_cancellation = handler_cancellation + + @property + def connections(self) -> List[RequestHandler]: + return list(self._connections.keys()) + + def connection_made( + self, handler: RequestHandler, transport: asyncio.Transport + ) -> None: + self._connections[handler] = transport + + def connection_lost( + self, handler: RequestHandler, exc: Optional[BaseException] = None + ) -> None: + if handler in self._connections: + if handler._task_handler: + handler._task_handler.add_done_callback( + lambda f: self._connections.pop(handler, None) + ) + else: + del self._connections[handler] + + def _make_request( + self, + message: RawRequestMessage, + payload: StreamReader, + protocol: RequestHandler, + writer: AbstractStreamWriter, + task: "asyncio.Task[None]", + ) -> BaseRequest: + return BaseRequest(message, payload, protocol, writer, task, self._loop) + + def pre_shutdown(self) -> None: + for conn in self._connections: + conn.close() + + async def shutdown(self, timeout: Optional[float] = None) -> None: + coros = (conn.shutdown(timeout) for conn in self._connections) + await asyncio.gather(*coros) + self._connections.clear() + + def __call__(self) -> RequestHandler: + try: + return RequestHandler(self, loop=self._loop, **self._kwargs) + except TypeError: + # Failsafe creation: remove all custom handler_args + kwargs = { + k: v + for k, v in self._kwargs.items() + if k in ["debug", "access_log_class"] + } + return RequestHandler(self, loop=self._loop, **kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_urldispatcher.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_urldispatcher.py new file mode 100644 index 0000000000000000000000000000000000000000..28ae2518fec3a8b59e1e045ba01d6ff1bad0cd13 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_urldispatcher.py @@ -0,0 +1,1303 @@ +import abc +import asyncio +import base64 +import functools +import hashlib +import html +import inspect +import keyword +import os +import re +import sys +import warnings +from functools import wraps +from pathlib import Path +from types import MappingProxyType +from typing import ( + TYPE_CHECKING, + Any, + Awaitable, + Callable, + Container, + Dict, + Final, + Generator, + Iterable, + Iterator, + List, + Mapping, + NoReturn, + Optional, + Pattern, + Set, + Sized, + Tuple, + Type, + TypedDict, + Union, + cast, +) + +from yarl import URL, __version__ as yarl_version + +from . import hdrs +from .abc import AbstractMatchInfo, AbstractRouter, AbstractView +from .helpers import DEBUG +from .http import HttpVersion11 +from .typedefs import Handler, PathLike +from .web_exceptions import ( + HTTPException, + HTTPExpectationFailed, + HTTPForbidden, + HTTPMethodNotAllowed, + HTTPNotFound, +) +from .web_fileresponse import FileResponse +from .web_request import Request +from .web_response import Response, StreamResponse +from .web_routedef import AbstractRouteDef + +__all__ = ( + "UrlDispatcher", + "UrlMappingMatchInfo", + "AbstractResource", + "Resource", + "PlainResource", + "DynamicResource", + "AbstractRoute", + "ResourceRoute", + "StaticResource", + "View", +) + + +if TYPE_CHECKING: + from .web_app import Application + + BaseDict = Dict[str, str] +else: + BaseDict = dict + +CIRCULAR_SYMLINK_ERROR = ( + (OSError,) + if sys.version_info < (3, 10) and sys.platform.startswith("win32") + else (RuntimeError,) if sys.version_info < (3, 13) else () +) + +YARL_VERSION: Final[Tuple[int, ...]] = tuple(map(int, yarl_version.split(".")[:2])) + +HTTP_METHOD_RE: Final[Pattern[str]] = re.compile( + r"^[0-9A-Za-z!#\$%&'\*\+\-\.\^_`\|~]+$" +) +ROUTE_RE: Final[Pattern[str]] = re.compile( + r"(\{[_a-zA-Z][^{}]*(?:\{[^{}]*\}[^{}]*)*\})" +) +PATH_SEP: Final[str] = re.escape("/") + + +_ExpectHandler = Callable[[Request], Awaitable[Optional[StreamResponse]]] +_Resolve = Tuple[Optional["UrlMappingMatchInfo"], Set[str]] + +html_escape = functools.partial(html.escape, quote=True) + + +class _InfoDict(TypedDict, total=False): + path: str + + formatter: str + pattern: Pattern[str] + + directory: Path + prefix: str + routes: Mapping[str, "AbstractRoute"] + + app: "Application" + + domain: str + + rule: "AbstractRuleMatching" + + http_exception: HTTPException + + +class AbstractResource(Sized, Iterable["AbstractRoute"]): + def __init__(self, *, name: Optional[str] = None) -> None: + self._name = name + + @property + def name(self) -> Optional[str]: + return self._name + + @property + @abc.abstractmethod + def canonical(self) -> str: + """Exposes the resource's canonical path. + + For example '/foo/bar/{name}' + + """ + + @abc.abstractmethod # pragma: no branch + def url_for(self, **kwargs: str) -> URL: + """Construct url for resource with additional params.""" + + @abc.abstractmethod # pragma: no branch + async def resolve(self, request: Request) -> _Resolve: + """Resolve resource. + + Return (UrlMappingMatchInfo, allowed_methods) pair. + """ + + @abc.abstractmethod + def add_prefix(self, prefix: str) -> None: + """Add a prefix to processed URLs. + + Required for subapplications support. + """ + + @abc.abstractmethod + def get_info(self) -> _InfoDict: + """Return a dict with additional info useful for introspection""" + + def freeze(self) -> None: + pass + + @abc.abstractmethod + def raw_match(self, path: str) -> bool: + """Perform a raw match against path""" + + +class AbstractRoute(abc.ABC): + def __init__( + self, + method: str, + handler: Union[Handler, Type[AbstractView]], + *, + expect_handler: Optional[_ExpectHandler] = None, + resource: Optional[AbstractResource] = None, + ) -> None: + + if expect_handler is None: + expect_handler = _default_expect_handler + + assert inspect.iscoroutinefunction(expect_handler) or ( + sys.version_info < (3, 14) and asyncio.iscoroutinefunction(expect_handler) + ), f"Coroutine is expected, got {expect_handler!r}" + + method = method.upper() + if not HTTP_METHOD_RE.match(method): + raise ValueError(f"{method} is not allowed HTTP method") + + assert callable(handler), handler + if inspect.iscoroutinefunction(handler) or ( + sys.version_info < (3, 14) and asyncio.iscoroutinefunction(handler) + ): + pass + elif inspect.isgeneratorfunction(handler): + warnings.warn( + "Bare generators are deprecated, use @coroutine wrapper", + DeprecationWarning, + ) + elif isinstance(handler, type) and issubclass(handler, AbstractView): + pass + else: + warnings.warn( + "Bare functions are deprecated, use async ones", DeprecationWarning + ) + + @wraps(handler) + async def handler_wrapper(request: Request) -> StreamResponse: + result = old_handler(request) # type: ignore[call-arg] + if asyncio.iscoroutine(result): + result = await result + assert isinstance(result, StreamResponse) + return result + + old_handler = handler + handler = handler_wrapper + + self._method = method + self._handler = handler + self._expect_handler = expect_handler + self._resource = resource + + @property + def method(self) -> str: + return self._method + + @property + def handler(self) -> Handler: + return self._handler + + @property + @abc.abstractmethod + def name(self) -> Optional[str]: + """Optional route's name, always equals to resource's name.""" + + @property + def resource(self) -> Optional[AbstractResource]: + return self._resource + + @abc.abstractmethod + def get_info(self) -> _InfoDict: + """Return a dict with additional info useful for introspection""" + + @abc.abstractmethod # pragma: no branch + def url_for(self, *args: str, **kwargs: str) -> URL: + """Construct url for route with additional params.""" + + async def handle_expect_header(self, request: Request) -> Optional[StreamResponse]: + return await self._expect_handler(request) + + +class UrlMappingMatchInfo(BaseDict, AbstractMatchInfo): + + __slots__ = ("_route", "_apps", "_current_app", "_frozen") + + def __init__(self, match_dict: Dict[str, str], route: AbstractRoute) -> None: + super().__init__(match_dict) + self._route = route + self._apps: List[Application] = [] + self._current_app: Optional[Application] = None + self._frozen = False + + @property + def handler(self) -> Handler: + return self._route.handler + + @property + def route(self) -> AbstractRoute: + return self._route + + @property + def expect_handler(self) -> _ExpectHandler: + return self._route.handle_expect_header + + @property + def http_exception(self) -> Optional[HTTPException]: + return None + + def get_info(self) -> _InfoDict: # type: ignore[override] + return self._route.get_info() + + @property + def apps(self) -> Tuple["Application", ...]: + return tuple(self._apps) + + def add_app(self, app: "Application") -> None: + if self._frozen: + raise RuntimeError("Cannot change apps stack after .freeze() call") + if self._current_app is None: + self._current_app = app + self._apps.insert(0, app) + + @property + def current_app(self) -> "Application": + app = self._current_app + assert app is not None + return app + + @current_app.setter + def current_app(self, app: "Application") -> None: + if DEBUG: # pragma: no cover + if app not in self._apps: + raise RuntimeError( + "Expected one of the following apps {!r}, got {!r}".format( + self._apps, app + ) + ) + self._current_app = app + + def freeze(self) -> None: + self._frozen = True + + def __repr__(self) -> str: + return f"" + + +class MatchInfoError(UrlMappingMatchInfo): + + __slots__ = ("_exception",) + + def __init__(self, http_exception: HTTPException) -> None: + self._exception = http_exception + super().__init__({}, SystemRoute(self._exception)) + + @property + def http_exception(self) -> HTTPException: + return self._exception + + def __repr__(self) -> str: + return "".format( + self._exception.status, self._exception.reason + ) + + +async def _default_expect_handler(request: Request) -> None: + """Default handler for Expect header. + + Just send "100 Continue" to client. + raise HTTPExpectationFailed if value of header is not "100-continue" + """ + expect = request.headers.get(hdrs.EXPECT, "") + if request.version == HttpVersion11: + if expect.lower() == "100-continue": + await request.writer.write(b"HTTP/1.1 100 Continue\r\n\r\n") + # Reset output_size as we haven't started the main body yet. + request.writer.output_size = 0 + else: + raise HTTPExpectationFailed(text="Unknown Expect: %s" % expect) + + +class Resource(AbstractResource): + def __init__(self, *, name: Optional[str] = None) -> None: + super().__init__(name=name) + self._routes: Dict[str, ResourceRoute] = {} + self._any_route: Optional[ResourceRoute] = None + self._allowed_methods: Set[str] = set() + + def add_route( + self, + method: str, + handler: Union[Type[AbstractView], Handler], + *, + expect_handler: Optional[_ExpectHandler] = None, + ) -> "ResourceRoute": + if route := self._routes.get(method, self._any_route): + raise RuntimeError( + "Added route will never be executed, " + f"method {route.method} is already " + "registered" + ) + + route_obj = ResourceRoute(method, handler, self, expect_handler=expect_handler) + self.register_route(route_obj) + return route_obj + + def register_route(self, route: "ResourceRoute") -> None: + assert isinstance( + route, ResourceRoute + ), f"Instance of Route class is required, got {route!r}" + if route.method == hdrs.METH_ANY: + self._any_route = route + self._allowed_methods.add(route.method) + self._routes[route.method] = route + + async def resolve(self, request: Request) -> _Resolve: + if (match_dict := self._match(request.rel_url.path_safe)) is None: + return None, set() + if route := self._routes.get(request.method, self._any_route): + return UrlMappingMatchInfo(match_dict, route), self._allowed_methods + return None, self._allowed_methods + + @abc.abstractmethod + def _match(self, path: str) -> Optional[Dict[str, str]]: + pass # pragma: no cover + + def __len__(self) -> int: + return len(self._routes) + + def __iter__(self) -> Iterator["ResourceRoute"]: + return iter(self._routes.values()) + + # TODO: implement all abstract methods + + +class PlainResource(Resource): + def __init__(self, path: str, *, name: Optional[str] = None) -> None: + super().__init__(name=name) + assert not path or path.startswith("/") + self._path = path + + @property + def canonical(self) -> str: + return self._path + + def freeze(self) -> None: + if not self._path: + self._path = "/" + + def add_prefix(self, prefix: str) -> None: + assert prefix.startswith("/") + assert not prefix.endswith("/") + assert len(prefix) > 1 + self._path = prefix + self._path + + def _match(self, path: str) -> Optional[Dict[str, str]]: + # string comparison is about 10 times faster than regexp matching + if self._path == path: + return {} + return None + + def raw_match(self, path: str) -> bool: + return self._path == path + + def get_info(self) -> _InfoDict: + return {"path": self._path} + + def url_for(self) -> URL: # type: ignore[override] + return URL.build(path=self._path, encoded=True) + + def __repr__(self) -> str: + name = "'" + self.name + "' " if self.name is not None else "" + return f"" + + +class DynamicResource(Resource): + + DYN = re.compile(r"\{(?P[_a-zA-Z][_a-zA-Z0-9]*)\}") + DYN_WITH_RE = re.compile(r"\{(?P[_a-zA-Z][_a-zA-Z0-9]*):(?P.+)\}") + GOOD = r"[^{}/]+" + + def __init__(self, path: str, *, name: Optional[str] = None) -> None: + super().__init__(name=name) + self._orig_path = path + pattern = "" + formatter = "" + for part in ROUTE_RE.split(path): + match = self.DYN.fullmatch(part) + if match: + pattern += "(?P<{}>{})".format(match.group("var"), self.GOOD) + formatter += "{" + match.group("var") + "}" + continue + + match = self.DYN_WITH_RE.fullmatch(part) + if match: + pattern += "(?P<{var}>{re})".format(**match.groupdict()) + formatter += "{" + match.group("var") + "}" + continue + + if "{" in part or "}" in part: + raise ValueError(f"Invalid path '{path}'['{part}']") + + part = _requote_path(part) + formatter += part + pattern += re.escape(part) + + try: + compiled = re.compile(pattern) + except re.error as exc: + raise ValueError(f"Bad pattern '{pattern}': {exc}") from None + assert compiled.pattern.startswith(PATH_SEP) + assert formatter.startswith("/") + self._pattern = compiled + self._formatter = formatter + + @property + def canonical(self) -> str: + return self._formatter + + def add_prefix(self, prefix: str) -> None: + assert prefix.startswith("/") + assert not prefix.endswith("/") + assert len(prefix) > 1 + self._pattern = re.compile(re.escape(prefix) + self._pattern.pattern) + self._formatter = prefix + self._formatter + + def _match(self, path: str) -> Optional[Dict[str, str]]: + match = self._pattern.fullmatch(path) + if match is None: + return None + return { + key: _unquote_path_safe(value) for key, value in match.groupdict().items() + } + + def raw_match(self, path: str) -> bool: + return self._orig_path == path + + def get_info(self) -> _InfoDict: + return {"formatter": self._formatter, "pattern": self._pattern} + + def url_for(self, **parts: str) -> URL: + url = self._formatter.format_map({k: _quote_path(v) for k, v in parts.items()}) + return URL.build(path=url, encoded=True) + + def __repr__(self) -> str: + name = "'" + self.name + "' " if self.name is not None else "" + return "".format( + name=name, formatter=self._formatter + ) + + +class PrefixResource(AbstractResource): + def __init__(self, prefix: str, *, name: Optional[str] = None) -> None: + assert not prefix or prefix.startswith("/"), prefix + assert prefix in ("", "/") or not prefix.endswith("/"), prefix + super().__init__(name=name) + self._prefix = _requote_path(prefix) + self._prefix2 = self._prefix + "/" + + @property + def canonical(self) -> str: + return self._prefix + + def add_prefix(self, prefix: str) -> None: + assert prefix.startswith("/") + assert not prefix.endswith("/") + assert len(prefix) > 1 + self._prefix = prefix + self._prefix + self._prefix2 = self._prefix + "/" + + def raw_match(self, prefix: str) -> bool: + return False + + # TODO: impl missing abstract methods + + +class StaticResource(PrefixResource): + VERSION_KEY = "v" + + def __init__( + self, + prefix: str, + directory: PathLike, + *, + name: Optional[str] = None, + expect_handler: Optional[_ExpectHandler] = None, + chunk_size: int = 256 * 1024, + show_index: bool = False, + follow_symlinks: bool = False, + append_version: bool = False, + ) -> None: + super().__init__(prefix, name=name) + try: + directory = Path(directory).expanduser().resolve(strict=True) + except FileNotFoundError as error: + raise ValueError(f"'{directory}' does not exist") from error + if not directory.is_dir(): + raise ValueError(f"'{directory}' is not a directory") + self._directory = directory + self._show_index = show_index + self._chunk_size = chunk_size + self._follow_symlinks = follow_symlinks + self._expect_handler = expect_handler + self._append_version = append_version + + self._routes = { + "GET": ResourceRoute( + "GET", self._handle, self, expect_handler=expect_handler + ), + "HEAD": ResourceRoute( + "HEAD", self._handle, self, expect_handler=expect_handler + ), + } + self._allowed_methods = set(self._routes) + + def url_for( # type: ignore[override] + self, + *, + filename: PathLike, + append_version: Optional[bool] = None, + ) -> URL: + if append_version is None: + append_version = self._append_version + filename = str(filename).lstrip("/") + + url = URL.build(path=self._prefix, encoded=True) + # filename is not encoded + if YARL_VERSION < (1, 6): + url = url / filename.replace("%", "%25") + else: + url = url / filename + + if append_version: + unresolved_path = self._directory.joinpath(filename) + try: + if self._follow_symlinks: + normalized_path = Path(os.path.normpath(unresolved_path)) + normalized_path.relative_to(self._directory) + filepath = normalized_path.resolve() + else: + filepath = unresolved_path.resolve() + filepath.relative_to(self._directory) + except (ValueError, FileNotFoundError): + # ValueError for case when path point to symlink + # with follow_symlinks is False + return url # relatively safe + if filepath.is_file(): + # TODO cache file content + # with file watcher for cache invalidation + with filepath.open("rb") as f: + file_bytes = f.read() + h = self._get_file_hash(file_bytes) + url = url.with_query({self.VERSION_KEY: h}) + return url + return url + + @staticmethod + def _get_file_hash(byte_array: bytes) -> str: + m = hashlib.sha256() # todo sha256 can be configurable param + m.update(byte_array) + b64 = base64.urlsafe_b64encode(m.digest()) + return b64.decode("ascii") + + def get_info(self) -> _InfoDict: + return { + "directory": self._directory, + "prefix": self._prefix, + "routes": self._routes, + } + + def set_options_route(self, handler: Handler) -> None: + if "OPTIONS" in self._routes: + raise RuntimeError("OPTIONS route was set already") + self._routes["OPTIONS"] = ResourceRoute( + "OPTIONS", handler, self, expect_handler=self._expect_handler + ) + self._allowed_methods.add("OPTIONS") + + async def resolve(self, request: Request) -> _Resolve: + path = request.rel_url.path_safe + method = request.method + if not path.startswith(self._prefix2) and path != self._prefix: + return None, set() + + allowed_methods = self._allowed_methods + if method not in allowed_methods: + return None, allowed_methods + + match_dict = {"filename": _unquote_path_safe(path[len(self._prefix) + 1 :])} + return (UrlMappingMatchInfo(match_dict, self._routes[method]), allowed_methods) + + def __len__(self) -> int: + return len(self._routes) + + def __iter__(self) -> Iterator[AbstractRoute]: + return iter(self._routes.values()) + + async def _handle(self, request: Request) -> StreamResponse: + rel_url = request.match_info["filename"] + filename = Path(rel_url) + if filename.anchor: + # rel_url is an absolute name like + # /static/\\machine_name\c$ or /static/D:\path + # where the static dir is totally different + raise HTTPForbidden() + + unresolved_path = self._directory.joinpath(filename) + loop = asyncio.get_running_loop() + return await loop.run_in_executor( + None, self._resolve_path_to_response, unresolved_path + ) + + def _resolve_path_to_response(self, unresolved_path: Path) -> StreamResponse: + """Take the unresolved path and query the file system to form a response.""" + # Check for access outside the root directory. For follow symlinks, URI + # cannot traverse out, but symlinks can. Otherwise, no access outside + # root is permitted. + try: + if self._follow_symlinks: + normalized_path = Path(os.path.normpath(unresolved_path)) + normalized_path.relative_to(self._directory) + file_path = normalized_path.resolve() + else: + file_path = unresolved_path.resolve() + file_path.relative_to(self._directory) + except (ValueError, *CIRCULAR_SYMLINK_ERROR) as error: + # ValueError is raised for the relative check. Circular symlinks + # raise here on resolving for python < 3.13. + raise HTTPNotFound() from error + + # if path is a directory, return the contents if permitted. Note the + # directory check will raise if a segment is not readable. + try: + if file_path.is_dir(): + if self._show_index: + return Response( + text=self._directory_as_html(file_path), + content_type="text/html", + ) + else: + raise HTTPForbidden() + except PermissionError as error: + raise HTTPForbidden() from error + + # Return the file response, which handles all other checks. + return FileResponse(file_path, chunk_size=self._chunk_size) + + def _directory_as_html(self, dir_path: Path) -> str: + """returns directory's index as html.""" + assert dir_path.is_dir() + + relative_path_to_dir = dir_path.relative_to(self._directory).as_posix() + index_of = f"Index of /{html_escape(relative_path_to_dir)}" + h1 = f"

{index_of}

" + + index_list = [] + dir_index = dir_path.iterdir() + for _file in sorted(dir_index): + # show file url as relative to static path + rel_path = _file.relative_to(self._directory).as_posix() + quoted_file_url = _quote_path(f"{self._prefix}/{rel_path}") + + # if file is a directory, add '/' to the end of the name + if _file.is_dir(): + file_name = f"{_file.name}/" + else: + file_name = _file.name + + index_list.append( + f'
  • {html_escape(file_name)}
  • ' + ) + ul = "
      \n{}\n
    ".format("\n".join(index_list)) + body = f"\n{h1}\n{ul}\n" + + head_str = f"\n{index_of}\n" + html = f"\n{head_str}\n{body}\n" + + return html + + def __repr__(self) -> str: + name = "'" + self.name + "'" if self.name is not None else "" + return " {directory!r}>".format( + name=name, path=self._prefix, directory=self._directory + ) + + +class PrefixedSubAppResource(PrefixResource): + def __init__(self, prefix: str, app: "Application") -> None: + super().__init__(prefix) + self._app = app + self._add_prefix_to_resources(prefix) + + def add_prefix(self, prefix: str) -> None: + super().add_prefix(prefix) + self._add_prefix_to_resources(prefix) + + def _add_prefix_to_resources(self, prefix: str) -> None: + router = self._app.router + for resource in router.resources(): + # Since the canonical path of a resource is about + # to change, we need to unindex it and then reindex + router.unindex_resource(resource) + resource.add_prefix(prefix) + router.index_resource(resource) + + def url_for(self, *args: str, **kwargs: str) -> URL: + raise RuntimeError(".url_for() is not supported by sub-application root") + + def get_info(self) -> _InfoDict: + return {"app": self._app, "prefix": self._prefix} + + async def resolve(self, request: Request) -> _Resolve: + match_info = await self._app.router.resolve(request) + match_info.add_app(self._app) + if isinstance(match_info.http_exception, HTTPMethodNotAllowed): + methods = match_info.http_exception.allowed_methods + else: + methods = set() + return match_info, methods + + def __len__(self) -> int: + return len(self._app.router.routes()) + + def __iter__(self) -> Iterator[AbstractRoute]: + return iter(self._app.router.routes()) + + def __repr__(self) -> str: + return " {app!r}>".format( + prefix=self._prefix, app=self._app + ) + + +class AbstractRuleMatching(abc.ABC): + @abc.abstractmethod # pragma: no branch + async def match(self, request: Request) -> bool: + """Return bool if the request satisfies the criteria""" + + @abc.abstractmethod # pragma: no branch + def get_info(self) -> _InfoDict: + """Return a dict with additional info useful for introspection""" + + @property + @abc.abstractmethod # pragma: no branch + def canonical(self) -> str: + """Return a str""" + + +class Domain(AbstractRuleMatching): + re_part = re.compile(r"(?!-)[a-z\d-]{1,63}(? None: + super().__init__() + self._domain = self.validation(domain) + + @property + def canonical(self) -> str: + return self._domain + + def validation(self, domain: str) -> str: + if not isinstance(domain, str): + raise TypeError("Domain must be str") + domain = domain.rstrip(".").lower() + if not domain: + raise ValueError("Domain cannot be empty") + elif "://" in domain: + raise ValueError("Scheme not supported") + url = URL("http://" + domain) + assert url.raw_host is not None + if not all(self.re_part.fullmatch(x) for x in url.raw_host.split(".")): + raise ValueError("Domain not valid") + if url.port == 80: + return url.raw_host + return f"{url.raw_host}:{url.port}" + + async def match(self, request: Request) -> bool: + host = request.headers.get(hdrs.HOST) + if not host: + return False + return self.match_domain(host) + + def match_domain(self, host: str) -> bool: + return host.lower() == self._domain + + def get_info(self) -> _InfoDict: + return {"domain": self._domain} + + +class MaskDomain(Domain): + re_part = re.compile(r"(?!-)[a-z\d\*-]{1,63}(? None: + super().__init__(domain) + mask = self._domain.replace(".", r"\.").replace("*", ".*") + self._mask = re.compile(mask) + + @property + def canonical(self) -> str: + return self._mask.pattern + + def match_domain(self, host: str) -> bool: + return self._mask.fullmatch(host) is not None + + +class MatchedSubAppResource(PrefixedSubAppResource): + def __init__(self, rule: AbstractRuleMatching, app: "Application") -> None: + AbstractResource.__init__(self) + self._prefix = "" + self._app = app + self._rule = rule + + @property + def canonical(self) -> str: + return self._rule.canonical + + def get_info(self) -> _InfoDict: + return {"app": self._app, "rule": self._rule} + + async def resolve(self, request: Request) -> _Resolve: + if not await self._rule.match(request): + return None, set() + match_info = await self._app.router.resolve(request) + match_info.add_app(self._app) + if isinstance(match_info.http_exception, HTTPMethodNotAllowed): + methods = match_info.http_exception.allowed_methods + else: + methods = set() + return match_info, methods + + def __repr__(self) -> str: + return f" {self._app!r}>" + + +class ResourceRoute(AbstractRoute): + """A route with resource""" + + def __init__( + self, + method: str, + handler: Union[Handler, Type[AbstractView]], + resource: AbstractResource, + *, + expect_handler: Optional[_ExpectHandler] = None, + ) -> None: + super().__init__( + method, handler, expect_handler=expect_handler, resource=resource + ) + + def __repr__(self) -> str: + return " {handler!r}".format( + method=self.method, resource=self._resource, handler=self.handler + ) + + @property + def name(self) -> Optional[str]: + if self._resource is None: + return None + return self._resource.name + + def url_for(self, *args: str, **kwargs: str) -> URL: + """Construct url for route with additional params.""" + assert self._resource is not None + return self._resource.url_for(*args, **kwargs) + + def get_info(self) -> _InfoDict: + assert self._resource is not None + return self._resource.get_info() + + +class SystemRoute(AbstractRoute): + def __init__(self, http_exception: HTTPException) -> None: + super().__init__(hdrs.METH_ANY, self._handle) + self._http_exception = http_exception + + def url_for(self, *args: str, **kwargs: str) -> URL: + raise RuntimeError(".url_for() is not allowed for SystemRoute") + + @property + def name(self) -> Optional[str]: + return None + + def get_info(self) -> _InfoDict: + return {"http_exception": self._http_exception} + + async def _handle(self, request: Request) -> StreamResponse: + raise self._http_exception + + @property + def status(self) -> int: + return self._http_exception.status + + @property + def reason(self) -> str: + return self._http_exception.reason + + def __repr__(self) -> str: + return "".format(self=self) + + +class View(AbstractView): + async def _iter(self) -> StreamResponse: + if self.request.method not in hdrs.METH_ALL: + self._raise_allowed_methods() + method: Optional[Callable[[], Awaitable[StreamResponse]]] + method = getattr(self, self.request.method.lower(), None) + if method is None: + self._raise_allowed_methods() + ret = await method() + assert isinstance(ret, StreamResponse) + return ret + + def __await__(self) -> Generator[Any, None, StreamResponse]: + return self._iter().__await__() + + def _raise_allowed_methods(self) -> NoReturn: + allowed_methods = {m for m in hdrs.METH_ALL if hasattr(self, m.lower())} + raise HTTPMethodNotAllowed(self.request.method, allowed_methods) + + +class ResourcesView(Sized, Iterable[AbstractResource], Container[AbstractResource]): + def __init__(self, resources: List[AbstractResource]) -> None: + self._resources = resources + + def __len__(self) -> int: + return len(self._resources) + + def __iter__(self) -> Iterator[AbstractResource]: + yield from self._resources + + def __contains__(self, resource: object) -> bool: + return resource in self._resources + + +class RoutesView(Sized, Iterable[AbstractRoute], Container[AbstractRoute]): + def __init__(self, resources: List[AbstractResource]): + self._routes: List[AbstractRoute] = [] + for resource in resources: + for route in resource: + self._routes.append(route) + + def __len__(self) -> int: + return len(self._routes) + + def __iter__(self) -> Iterator[AbstractRoute]: + yield from self._routes + + def __contains__(self, route: object) -> bool: + return route in self._routes + + +class UrlDispatcher(AbstractRouter, Mapping[str, AbstractResource]): + + NAME_SPLIT_RE = re.compile(r"[.:-]") + + def __init__(self) -> None: + super().__init__() + self._resources: List[AbstractResource] = [] + self._named_resources: Dict[str, AbstractResource] = {} + self._resource_index: dict[str, list[AbstractResource]] = {} + self._matched_sub_app_resources: List[MatchedSubAppResource] = [] + + async def resolve(self, request: Request) -> UrlMappingMatchInfo: + resource_index = self._resource_index + allowed_methods: Set[str] = set() + + # Walk the url parts looking for candidates. We walk the url backwards + # to ensure the most explicit match is found first. If there are multiple + # candidates for a given url part because there are multiple resources + # registered for the same canonical path, we resolve them in a linear + # fashion to ensure registration order is respected. + url_part = request.rel_url.path_safe + while url_part: + for candidate in resource_index.get(url_part, ()): + match_dict, allowed = await candidate.resolve(request) + if match_dict is not None: + return match_dict + else: + allowed_methods |= allowed + if url_part == "/": + break + url_part = url_part.rpartition("/")[0] or "/" + + # + # We didn't find any candidates, so we'll try the matched sub-app + # resources which we have to walk in a linear fashion because they + # have regex/wildcard match rules and we cannot index them. + # + # For most cases we do not expect there to be many of these since + # currently they are only added by `add_domain` + # + for resource in self._matched_sub_app_resources: + match_dict, allowed = await resource.resolve(request) + if match_dict is not None: + return match_dict + else: + allowed_methods |= allowed + + if allowed_methods: + return MatchInfoError(HTTPMethodNotAllowed(request.method, allowed_methods)) + + return MatchInfoError(HTTPNotFound()) + + def __iter__(self) -> Iterator[str]: + return iter(self._named_resources) + + def __len__(self) -> int: + return len(self._named_resources) + + def __contains__(self, resource: object) -> bool: + return resource in self._named_resources + + def __getitem__(self, name: str) -> AbstractResource: + return self._named_resources[name] + + def resources(self) -> ResourcesView: + return ResourcesView(self._resources) + + def routes(self) -> RoutesView: + return RoutesView(self._resources) + + def named_resources(self) -> Mapping[str, AbstractResource]: + return MappingProxyType(self._named_resources) + + def register_resource(self, resource: AbstractResource) -> None: + assert isinstance( + resource, AbstractResource + ), f"Instance of AbstractResource class is required, got {resource!r}" + if self.frozen: + raise RuntimeError("Cannot register a resource into frozen router.") + + name = resource.name + + if name is not None: + parts = self.NAME_SPLIT_RE.split(name) + for part in parts: + if keyword.iskeyword(part): + raise ValueError( + f"Incorrect route name {name!r}, " + "python keywords cannot be used " + "for route name" + ) + if not part.isidentifier(): + raise ValueError( + "Incorrect route name {!r}, " + "the name should be a sequence of " + "python identifiers separated " + "by dash, dot or column".format(name) + ) + if name in self._named_resources: + raise ValueError( + "Duplicate {!r}, " + "already handled by {!r}".format(name, self._named_resources[name]) + ) + self._named_resources[name] = resource + self._resources.append(resource) + + if isinstance(resource, MatchedSubAppResource): + # We cannot index match sub-app resources because they have match rules + self._matched_sub_app_resources.append(resource) + else: + self.index_resource(resource) + + def _get_resource_index_key(self, resource: AbstractResource) -> str: + """Return a key to index the resource in the resource index.""" + if "{" in (index_key := resource.canonical): + # strip at the first { to allow for variables, and than + # rpartition at / to allow for variable parts in the path + # For example if the canonical path is `/core/locations{tail:.*}` + # the index key will be `/core` since index is based on the + # url parts split by `/` + index_key = index_key.partition("{")[0].rpartition("/")[0] + return index_key.rstrip("/") or "/" + + def index_resource(self, resource: AbstractResource) -> None: + """Add a resource to the resource index.""" + resource_key = self._get_resource_index_key(resource) + # There may be multiple resources for a canonical path + # so we keep them in a list to ensure that registration + # order is respected. + self._resource_index.setdefault(resource_key, []).append(resource) + + def unindex_resource(self, resource: AbstractResource) -> None: + """Remove a resource from the resource index.""" + resource_key = self._get_resource_index_key(resource) + self._resource_index[resource_key].remove(resource) + + def add_resource(self, path: str, *, name: Optional[str] = None) -> Resource: + if path and not path.startswith("/"): + raise ValueError("path should be started with / or be empty") + # Reuse last added resource if path and name are the same + if self._resources: + resource = self._resources[-1] + if resource.name == name and resource.raw_match(path): + return cast(Resource, resource) + if not ("{" in path or "}" in path or ROUTE_RE.search(path)): + resource = PlainResource(path, name=name) + self.register_resource(resource) + return resource + resource = DynamicResource(path, name=name) + self.register_resource(resource) + return resource + + def add_route( + self, + method: str, + path: str, + handler: Union[Handler, Type[AbstractView]], + *, + name: Optional[str] = None, + expect_handler: Optional[_ExpectHandler] = None, + ) -> AbstractRoute: + resource = self.add_resource(path, name=name) + return resource.add_route(method, handler, expect_handler=expect_handler) + + def add_static( + self, + prefix: str, + path: PathLike, + *, + name: Optional[str] = None, + expect_handler: Optional[_ExpectHandler] = None, + chunk_size: int = 256 * 1024, + show_index: bool = False, + follow_symlinks: bool = False, + append_version: bool = False, + ) -> AbstractResource: + """Add static files view. + + prefix - url prefix + path - folder with files + + """ + assert prefix.startswith("/") + if prefix.endswith("/"): + prefix = prefix[:-1] + resource = StaticResource( + prefix, + path, + name=name, + expect_handler=expect_handler, + chunk_size=chunk_size, + show_index=show_index, + follow_symlinks=follow_symlinks, + append_version=append_version, + ) + self.register_resource(resource) + return resource + + def add_head(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method HEAD.""" + return self.add_route(hdrs.METH_HEAD, path, handler, **kwargs) + + def add_options(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method OPTIONS.""" + return self.add_route(hdrs.METH_OPTIONS, path, handler, **kwargs) + + def add_get( + self, + path: str, + handler: Handler, + *, + name: Optional[str] = None, + allow_head: bool = True, + **kwargs: Any, + ) -> AbstractRoute: + """Shortcut for add_route with method GET. + + If allow_head is true, another + route is added allowing head requests to the same endpoint. + """ + resource = self.add_resource(path, name=name) + if allow_head: + resource.add_route(hdrs.METH_HEAD, handler, **kwargs) + return resource.add_route(hdrs.METH_GET, handler, **kwargs) + + def add_post(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method POST.""" + return self.add_route(hdrs.METH_POST, path, handler, **kwargs) + + def add_put(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method PUT.""" + return self.add_route(hdrs.METH_PUT, path, handler, **kwargs) + + def add_patch(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method PATCH.""" + return self.add_route(hdrs.METH_PATCH, path, handler, **kwargs) + + def add_delete(self, path: str, handler: Handler, **kwargs: Any) -> AbstractRoute: + """Shortcut for add_route with method DELETE.""" + return self.add_route(hdrs.METH_DELETE, path, handler, **kwargs) + + def add_view( + self, path: str, handler: Type[AbstractView], **kwargs: Any + ) -> AbstractRoute: + """Shortcut for add_route with ANY methods for a class-based view.""" + return self.add_route(hdrs.METH_ANY, path, handler, **kwargs) + + def freeze(self) -> None: + super().freeze() + for resource in self._resources: + resource.freeze() + + def add_routes(self, routes: Iterable[AbstractRouteDef]) -> List[AbstractRoute]: + """Append routes to route table. + + Parameter should be a sequence of RouteDef objects. + + Returns a list of registered AbstractRoute instances. + """ + registered_routes = [] + for route_def in routes: + registered_routes.extend(route_def.register(self)) + return registered_routes + + +def _quote_path(value: str) -> str: + if YARL_VERSION < (1, 6): + value = value.replace("%", "%25") + return URL.build(path=value, encoded=False).raw_path + + +def _unquote_path_safe(value: str) -> str: + if "%" not in value: + return value + return value.replace("%2F", "/").replace("%25", "%") + + +def _requote_path(value: str) -> str: + # Quote non-ascii characters and other characters which must be quoted, + # but preserve existing %-sequences. + result = _quote_path(value) + if "%" in value: + result = result.replace("%25", "%") + return result diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_ws.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_ws.py new file mode 100644 index 0000000000000000000000000000000000000000..575f9a3dc8507d1e6b766333c9daec389313febd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/web_ws.py @@ -0,0 +1,631 @@ +import asyncio +import base64 +import binascii +import hashlib +import json +import sys +from typing import Any, Final, Iterable, Optional, Tuple, Union, cast + +import attr +from multidict import CIMultiDict + +from . import hdrs +from ._websocket.reader import WebSocketDataQueue +from ._websocket.writer import DEFAULT_LIMIT +from .abc import AbstractStreamWriter +from .client_exceptions import WSMessageTypeError +from .helpers import calculate_timeout_when, set_exception, set_result +from .http import ( + WS_CLOSED_MESSAGE, + WS_CLOSING_MESSAGE, + WS_KEY, + WebSocketError, + WebSocketReader, + WebSocketWriter, + WSCloseCode, + WSMessage, + WSMsgType as WSMsgType, + ws_ext_gen, + ws_ext_parse, +) +from .http_websocket import _INTERNAL_RECEIVE_TYPES +from .log import ws_logger +from .streams import EofStream +from .typedefs import JSONDecoder, JSONEncoder +from .web_exceptions import HTTPBadRequest, HTTPException +from .web_request import BaseRequest +from .web_response import StreamResponse + +if sys.version_info >= (3, 11): + import asyncio as async_timeout +else: + import async_timeout + +__all__ = ( + "WebSocketResponse", + "WebSocketReady", + "WSMsgType", +) + +THRESHOLD_CONNLOST_ACCESS: Final[int] = 5 + + +@attr.s(auto_attribs=True, frozen=True, slots=True) +class WebSocketReady: + ok: bool + protocol: Optional[str] + + def __bool__(self) -> bool: + return self.ok + + +class WebSocketResponse(StreamResponse): + + _length_check: bool = False + _ws_protocol: Optional[str] = None + _writer: Optional[WebSocketWriter] = None + _reader: Optional[WebSocketDataQueue] = None + _closed: bool = False + _closing: bool = False + _conn_lost: int = 0 + _close_code: Optional[int] = None + _loop: Optional[asyncio.AbstractEventLoop] = None + _waiting: bool = False + _close_wait: Optional[asyncio.Future[None]] = None + _exception: Optional[BaseException] = None + _heartbeat_when: float = 0.0 + _heartbeat_cb: Optional[asyncio.TimerHandle] = None + _pong_response_cb: Optional[asyncio.TimerHandle] = None + _ping_task: Optional[asyncio.Task[None]] = None + + def __init__( + self, + *, + timeout: float = 10.0, + receive_timeout: Optional[float] = None, + autoclose: bool = True, + autoping: bool = True, + heartbeat: Optional[float] = None, + protocols: Iterable[str] = (), + compress: bool = True, + max_msg_size: int = 4 * 1024 * 1024, + writer_limit: int = DEFAULT_LIMIT, + ) -> None: + super().__init__(status=101) + self._protocols = protocols + self._timeout = timeout + self._receive_timeout = receive_timeout + self._autoclose = autoclose + self._autoping = autoping + self._heartbeat = heartbeat + if heartbeat is not None: + self._pong_heartbeat = heartbeat / 2.0 + self._compress: Union[bool, int] = compress + self._max_msg_size = max_msg_size + self._writer_limit = writer_limit + + def _cancel_heartbeat(self) -> None: + self._cancel_pong_response_cb() + if self._heartbeat_cb is not None: + self._heartbeat_cb.cancel() + self._heartbeat_cb = None + if self._ping_task is not None: + self._ping_task.cancel() + self._ping_task = None + + def _cancel_pong_response_cb(self) -> None: + if self._pong_response_cb is not None: + self._pong_response_cb.cancel() + self._pong_response_cb = None + + def _reset_heartbeat(self) -> None: + if self._heartbeat is None: + return + self._cancel_pong_response_cb() + req = self._req + timeout_ceil_threshold = ( + req._protocol._timeout_ceil_threshold if req is not None else 5 + ) + loop = self._loop + assert loop is not None + now = loop.time() + when = calculate_timeout_when(now, self._heartbeat, timeout_ceil_threshold) + self._heartbeat_when = when + if self._heartbeat_cb is None: + # We do not cancel the previous heartbeat_cb here because + # it generates a significant amount of TimerHandle churn + # which causes asyncio to rebuild the heap frequently. + # Instead _send_heartbeat() will reschedule the next + # heartbeat if it fires too early. + self._heartbeat_cb = loop.call_at(when, self._send_heartbeat) + + def _send_heartbeat(self) -> None: + self._heartbeat_cb = None + loop = self._loop + assert loop is not None and self._writer is not None + now = loop.time() + if now < self._heartbeat_when: + # Heartbeat fired too early, reschedule + self._heartbeat_cb = loop.call_at( + self._heartbeat_when, self._send_heartbeat + ) + return + + req = self._req + timeout_ceil_threshold = ( + req._protocol._timeout_ceil_threshold if req is not None else 5 + ) + when = calculate_timeout_when(now, self._pong_heartbeat, timeout_ceil_threshold) + self._cancel_pong_response_cb() + self._pong_response_cb = loop.call_at(when, self._pong_not_received) + + coro = self._writer.send_frame(b"", WSMsgType.PING) + if sys.version_info >= (3, 12): + # Optimization for Python 3.12, try to send the ping + # immediately to avoid having to schedule + # the task on the event loop. + ping_task = asyncio.Task(coro, loop=loop, eager_start=True) + else: + ping_task = loop.create_task(coro) + + if not ping_task.done(): + self._ping_task = ping_task + ping_task.add_done_callback(self._ping_task_done) + else: + self._ping_task_done(ping_task) + + def _ping_task_done(self, task: "asyncio.Task[None]") -> None: + """Callback for when the ping task completes.""" + if not task.cancelled() and (exc := task.exception()): + self._handle_ping_pong_exception(exc) + self._ping_task = None + + def _pong_not_received(self) -> None: + if self._req is not None and self._req.transport is not None: + self._handle_ping_pong_exception( + asyncio.TimeoutError( + f"No PONG received after {self._pong_heartbeat} seconds" + ) + ) + + def _handle_ping_pong_exception(self, exc: BaseException) -> None: + """Handle exceptions raised during ping/pong processing.""" + if self._closed: + return + self._set_closed() + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + self._exception = exc + if self._waiting and not self._closing and self._reader is not None: + self._reader.feed_data(WSMessage(WSMsgType.ERROR, exc, None), 0) + + def _set_closed(self) -> None: + """Set the connection to closed. + + Cancel any heartbeat timers and set the closed flag. + """ + self._closed = True + self._cancel_heartbeat() + + async def prepare(self, request: BaseRequest) -> AbstractStreamWriter: + # make pre-check to don't hide it by do_handshake() exceptions + if self._payload_writer is not None: + return self._payload_writer + + protocol, writer = self._pre_start(request) + payload_writer = await super().prepare(request) + assert payload_writer is not None + self._post_start(request, protocol, writer) + await payload_writer.drain() + return payload_writer + + def _handshake( + self, request: BaseRequest + ) -> Tuple["CIMultiDict[str]", Optional[str], int, bool]: + headers = request.headers + if "websocket" != headers.get(hdrs.UPGRADE, "").lower().strip(): + raise HTTPBadRequest( + text=( + "No WebSocket UPGRADE hdr: {}\n Can " + '"Upgrade" only to "WebSocket".' + ).format(headers.get(hdrs.UPGRADE)) + ) + + if "upgrade" not in headers.get(hdrs.CONNECTION, "").lower(): + raise HTTPBadRequest( + text="No CONNECTION upgrade hdr: {}".format( + headers.get(hdrs.CONNECTION) + ) + ) + + # find common sub-protocol between client and server + protocol: Optional[str] = None + if hdrs.SEC_WEBSOCKET_PROTOCOL in headers: + req_protocols = [ + str(proto.strip()) + for proto in headers[hdrs.SEC_WEBSOCKET_PROTOCOL].split(",") + ] + + for proto in req_protocols: + if proto in self._protocols: + protocol = proto + break + else: + # No overlap found: Return no protocol as per spec + ws_logger.warning( + "%s: Client protocols %r don’t overlap server-known ones %r", + request.remote, + req_protocols, + self._protocols, + ) + + # check supported version + version = headers.get(hdrs.SEC_WEBSOCKET_VERSION, "") + if version not in ("13", "8", "7"): + raise HTTPBadRequest(text=f"Unsupported version: {version}") + + # check client handshake for validity + key = headers.get(hdrs.SEC_WEBSOCKET_KEY) + try: + if not key or len(base64.b64decode(key)) != 16: + raise HTTPBadRequest(text=f"Handshake error: {key!r}") + except binascii.Error: + raise HTTPBadRequest(text=f"Handshake error: {key!r}") from None + + accept_val = base64.b64encode( + hashlib.sha1(key.encode() + WS_KEY).digest() + ).decode() + response_headers = CIMultiDict( + { + hdrs.UPGRADE: "websocket", + hdrs.CONNECTION: "upgrade", + hdrs.SEC_WEBSOCKET_ACCEPT: accept_val, + } + ) + + notakeover = False + compress = 0 + if self._compress: + extensions = headers.get(hdrs.SEC_WEBSOCKET_EXTENSIONS) + # Server side always get return with no exception. + # If something happened, just drop compress extension + compress, notakeover = ws_ext_parse(extensions, isserver=True) + if compress: + enabledext = ws_ext_gen( + compress=compress, isserver=True, server_notakeover=notakeover + ) + response_headers[hdrs.SEC_WEBSOCKET_EXTENSIONS] = enabledext + + if protocol: + response_headers[hdrs.SEC_WEBSOCKET_PROTOCOL] = protocol + return ( + response_headers, + protocol, + compress, + notakeover, + ) + + def _pre_start(self, request: BaseRequest) -> Tuple[Optional[str], WebSocketWriter]: + self._loop = request._loop + + headers, protocol, compress, notakeover = self._handshake(request) + + self.set_status(101) + self.headers.update(headers) + self.force_close() + self._compress = compress + transport = request._protocol.transport + assert transport is not None + writer = WebSocketWriter( + request._protocol, + transport, + compress=compress, + notakeover=notakeover, + limit=self._writer_limit, + ) + + return protocol, writer + + def _post_start( + self, request: BaseRequest, protocol: Optional[str], writer: WebSocketWriter + ) -> None: + self._ws_protocol = protocol + self._writer = writer + + self._reset_heartbeat() + + loop = self._loop + assert loop is not None + self._reader = WebSocketDataQueue(request._protocol, 2**16, loop=loop) + request.protocol.set_parser( + WebSocketReader( + self._reader, self._max_msg_size, compress=bool(self._compress) + ) + ) + # disable HTTP keepalive for WebSocket + request.protocol.keep_alive(False) + + def can_prepare(self, request: BaseRequest) -> WebSocketReady: + if self._writer is not None: + raise RuntimeError("Already started") + try: + _, protocol, _, _ = self._handshake(request) + except HTTPException: + return WebSocketReady(False, None) + else: + return WebSocketReady(True, protocol) + + @property + def prepared(self) -> bool: + return self._writer is not None + + @property + def closed(self) -> bool: + return self._closed + + @property + def close_code(self) -> Optional[int]: + return self._close_code + + @property + def ws_protocol(self) -> Optional[str]: + return self._ws_protocol + + @property + def compress(self) -> Union[int, bool]: + return self._compress + + def get_extra_info(self, name: str, default: Any = None) -> Any: + """Get optional transport information. + + If no value associated with ``name`` is found, ``default`` is returned. + """ + writer = self._writer + if writer is None: + return default + transport = writer.transport + if transport is None: + return default + return transport.get_extra_info(name, default) + + def exception(self) -> Optional[BaseException]: + return self._exception + + async def ping(self, message: bytes = b"") -> None: + if self._writer is None: + raise RuntimeError("Call .prepare() first") + await self._writer.send_frame(message, WSMsgType.PING) + + async def pong(self, message: bytes = b"") -> None: + # unsolicited pong + if self._writer is None: + raise RuntimeError("Call .prepare() first") + await self._writer.send_frame(message, WSMsgType.PONG) + + async def send_frame( + self, message: bytes, opcode: WSMsgType, compress: Optional[int] = None + ) -> None: + """Send a frame over the websocket.""" + if self._writer is None: + raise RuntimeError("Call .prepare() first") + await self._writer.send_frame(message, opcode, compress) + + async def send_str(self, data: str, compress: Optional[int] = None) -> None: + if self._writer is None: + raise RuntimeError("Call .prepare() first") + if not isinstance(data, str): + raise TypeError("data argument must be str (%r)" % type(data)) + await self._writer.send_frame( + data.encode("utf-8"), WSMsgType.TEXT, compress=compress + ) + + async def send_bytes(self, data: bytes, compress: Optional[int] = None) -> None: + if self._writer is None: + raise RuntimeError("Call .prepare() first") + if not isinstance(data, (bytes, bytearray, memoryview)): + raise TypeError("data argument must be byte-ish (%r)" % type(data)) + await self._writer.send_frame(data, WSMsgType.BINARY, compress=compress) + + async def send_json( + self, + data: Any, + compress: Optional[int] = None, + *, + dumps: JSONEncoder = json.dumps, + ) -> None: + await self.send_str(dumps(data), compress=compress) + + async def write_eof(self) -> None: # type: ignore[override] + if self._eof_sent: + return + if self._payload_writer is None: + raise RuntimeError("Response has not been started") + + await self.close() + self._eof_sent = True + + async def close( + self, *, code: int = WSCloseCode.OK, message: bytes = b"", drain: bool = True + ) -> bool: + """Close websocket connection.""" + if self._writer is None: + raise RuntimeError("Call .prepare() first") + + if self._closed: + return False + self._set_closed() + + try: + await self._writer.close(code, message) + writer = self._payload_writer + assert writer is not None + if drain: + await writer.drain() + except (asyncio.CancelledError, asyncio.TimeoutError): + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + raise + except Exception as exc: + self._exception = exc + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + return True + + reader = self._reader + assert reader is not None + # we need to break `receive()` cycle before we can call + # `reader.read()` as `close()` may be called from different task + if self._waiting: + assert self._loop is not None + assert self._close_wait is None + self._close_wait = self._loop.create_future() + reader.feed_data(WS_CLOSING_MESSAGE, 0) + await self._close_wait + + if self._closing: + self._close_transport() + return True + + try: + async with async_timeout.timeout(self._timeout): + while True: + msg = await reader.read() + if msg.type is WSMsgType.CLOSE: + self._set_code_close_transport(msg.data) + return True + except asyncio.CancelledError: + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + raise + except Exception as exc: + self._exception = exc + self._set_code_close_transport(WSCloseCode.ABNORMAL_CLOSURE) + return True + + def _set_closing(self, code: WSCloseCode) -> None: + """Set the close code and mark the connection as closing.""" + self._closing = True + self._close_code = code + self._cancel_heartbeat() + + def _set_code_close_transport(self, code: WSCloseCode) -> None: + """Set the close code and close the transport.""" + self._close_code = code + self._close_transport() + + def _close_transport(self) -> None: + """Close the transport.""" + if self._req is not None and self._req.transport is not None: + self._req.transport.close() + + async def receive(self, timeout: Optional[float] = None) -> WSMessage: + if self._reader is None: + raise RuntimeError("Call .prepare() first") + + receive_timeout = timeout or self._receive_timeout + while True: + if self._waiting: + raise RuntimeError("Concurrent call to receive() is not allowed") + + if self._closed: + self._conn_lost += 1 + if self._conn_lost >= THRESHOLD_CONNLOST_ACCESS: + raise RuntimeError("WebSocket connection is closed.") + return WS_CLOSED_MESSAGE + elif self._closing: + return WS_CLOSING_MESSAGE + + try: + self._waiting = True + try: + if receive_timeout: + # Entering the context manager and creating + # Timeout() object can take almost 50% of the + # run time in this loop so we avoid it if + # there is no read timeout. + async with async_timeout.timeout(receive_timeout): + msg = await self._reader.read() + else: + msg = await self._reader.read() + self._reset_heartbeat() + finally: + self._waiting = False + if self._close_wait: + set_result(self._close_wait, None) + except asyncio.TimeoutError: + raise + except EofStream: + self._close_code = WSCloseCode.OK + await self.close() + return WSMessage(WSMsgType.CLOSED, None, None) + except WebSocketError as exc: + self._close_code = exc.code + await self.close(code=exc.code) + return WSMessage(WSMsgType.ERROR, exc, None) + except Exception as exc: + self._exception = exc + self._set_closing(WSCloseCode.ABNORMAL_CLOSURE) + await self.close() + return WSMessage(WSMsgType.ERROR, exc, None) + + if msg.type not in _INTERNAL_RECEIVE_TYPES: + # If its not a close/closing/ping/pong message + # we can return it immediately + return msg + + if msg.type is WSMsgType.CLOSE: + self._set_closing(msg.data) + # Could be closed while awaiting reader. + if not self._closed and self._autoclose: + # The client is likely going to close the + # connection out from under us so we do not + # want to drain any pending writes as it will + # likely result writing to a broken pipe. + await self.close(drain=False) + elif msg.type is WSMsgType.CLOSING: + self._set_closing(WSCloseCode.OK) + elif msg.type is WSMsgType.PING and self._autoping: + await self.pong(msg.data) + continue + elif msg.type is WSMsgType.PONG and self._autoping: + continue + + return msg + + async def receive_str(self, *, timeout: Optional[float] = None) -> str: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.TEXT: + raise WSMessageTypeError( + f"Received message {msg.type}:{msg.data!r} is not WSMsgType.TEXT" + ) + return cast(str, msg.data) + + async def receive_bytes(self, *, timeout: Optional[float] = None) -> bytes: + msg = await self.receive(timeout) + if msg.type is not WSMsgType.BINARY: + raise WSMessageTypeError( + f"Received message {msg.type}:{msg.data!r} is not WSMsgType.BINARY" + ) + return cast(bytes, msg.data) + + async def receive_json( + self, *, loads: JSONDecoder = json.loads, timeout: Optional[float] = None + ) -> Any: + data = await self.receive_str(timeout=timeout) + return loads(data) + + async def write(self, data: bytes) -> None: + raise RuntimeError("Cannot call .write() for websocket") + + def __aiter__(self) -> "WebSocketResponse": + return self + + async def __anext__(self) -> WSMessage: + msg = await self.receive() + if msg.type in (WSMsgType.CLOSE, WSMsgType.CLOSING, WSMsgType.CLOSED): + raise StopAsyncIteration + return msg + + def _cancel(self, exc: BaseException) -> None: + # web_protocol calls this from connection_lost + # or when the server is shutting down. + self._closing = True + self._cancel_heartbeat() + if self._reader is not None: + set_exception(self._reader, exc) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/worker.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..f7281bfde7541412c3174aa5fdcb859fa1b7a996 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiohttp/worker.py @@ -0,0 +1,255 @@ +"""Async gunicorn worker for aiohttp.web""" + +import asyncio +import inspect +import os +import re +import signal +import sys +from types import FrameType +from typing import TYPE_CHECKING, Any, Optional + +from gunicorn.config import AccessLogFormat as GunicornAccessLogFormat +from gunicorn.workers import base + +from aiohttp import web + +from .helpers import set_result +from .web_app import Application +from .web_log import AccessLogger + +if TYPE_CHECKING: + import ssl + + SSLContext = ssl.SSLContext +else: + try: + import ssl + + SSLContext = ssl.SSLContext + except ImportError: # pragma: no cover + ssl = None # type: ignore[assignment] + SSLContext = object # type: ignore[misc,assignment] + + +__all__ = ("GunicornWebWorker", "GunicornUVLoopWebWorker") + + +class GunicornWebWorker(base.Worker): # type: ignore[misc,no-any-unimported] + + DEFAULT_AIOHTTP_LOG_FORMAT = AccessLogger.LOG_FORMAT + DEFAULT_GUNICORN_LOG_FORMAT = GunicornAccessLogFormat.default + + def __init__(self, *args: Any, **kw: Any) -> None: # pragma: no cover + super().__init__(*args, **kw) + + self._task: Optional[asyncio.Task[None]] = None + self.exit_code = 0 + self._notify_waiter: Optional[asyncio.Future[bool]] = None + + def init_process(self) -> None: + # create new event_loop after fork + asyncio.get_event_loop().close() + + self.loop = asyncio.new_event_loop() + asyncio.set_event_loop(self.loop) + + super().init_process() + + def run(self) -> None: + self._task = self.loop.create_task(self._run()) + + try: # ignore all finalization problems + self.loop.run_until_complete(self._task) + except Exception: + self.log.exception("Exception in gunicorn worker") + self.loop.run_until_complete(self.loop.shutdown_asyncgens()) + self.loop.close() + + sys.exit(self.exit_code) + + async def _run(self) -> None: + runner = None + if isinstance(self.wsgi, Application): + app = self.wsgi + elif inspect.iscoroutinefunction(self.wsgi) or ( + sys.version_info < (3, 14) and asyncio.iscoroutinefunction(self.wsgi) + ): + wsgi = await self.wsgi() + if isinstance(wsgi, web.AppRunner): + runner = wsgi + app = runner.app + else: + app = wsgi + else: + raise RuntimeError( + "wsgi app should be either Application or " + "async function returning Application, got {}".format(self.wsgi) + ) + + if runner is None: + access_log = self.log.access_log if self.cfg.accesslog else None + runner = web.AppRunner( + app, + logger=self.log, + keepalive_timeout=self.cfg.keepalive, + access_log=access_log, + access_log_format=self._get_valid_log_format( + self.cfg.access_log_format + ), + shutdown_timeout=self.cfg.graceful_timeout / 100 * 95, + ) + await runner.setup() + + ctx = self._create_ssl_context(self.cfg) if self.cfg.is_ssl else None + + runner = runner + assert runner is not None + server = runner.server + assert server is not None + for sock in self.sockets: + site = web.SockSite( + runner, + sock, + ssl_context=ctx, + ) + await site.start() + + # If our parent changed then we shut down. + pid = os.getpid() + try: + while self.alive: # type: ignore[has-type] + self.notify() + + cnt = server.requests_count + if self.max_requests and cnt > self.max_requests: + self.alive = False + self.log.info("Max requests, shutting down: %s", self) + + elif pid == os.getpid() and self.ppid != os.getppid(): + self.alive = False + self.log.info("Parent changed, shutting down: %s", self) + else: + await self._wait_next_notify() + except BaseException: + pass + + await runner.cleanup() + + def _wait_next_notify(self) -> "asyncio.Future[bool]": + self._notify_waiter_done() + + loop = self.loop + assert loop is not None + self._notify_waiter = waiter = loop.create_future() + self.loop.call_later(1.0, self._notify_waiter_done, waiter) + + return waiter + + def _notify_waiter_done( + self, waiter: Optional["asyncio.Future[bool]"] = None + ) -> None: + if waiter is None: + waiter = self._notify_waiter + if waiter is not None: + set_result(waiter, True) + + if waiter is self._notify_waiter: + self._notify_waiter = None + + def init_signals(self) -> None: + # Set up signals through the event loop API. + + self.loop.add_signal_handler( + signal.SIGQUIT, self.handle_quit, signal.SIGQUIT, None + ) + + self.loop.add_signal_handler( + signal.SIGTERM, self.handle_exit, signal.SIGTERM, None + ) + + self.loop.add_signal_handler( + signal.SIGINT, self.handle_quit, signal.SIGINT, None + ) + + self.loop.add_signal_handler( + signal.SIGWINCH, self.handle_winch, signal.SIGWINCH, None + ) + + self.loop.add_signal_handler( + signal.SIGUSR1, self.handle_usr1, signal.SIGUSR1, None + ) + + self.loop.add_signal_handler( + signal.SIGABRT, self.handle_abort, signal.SIGABRT, None + ) + + # Don't let SIGTERM and SIGUSR1 disturb active requests + # by interrupting system calls + signal.siginterrupt(signal.SIGTERM, False) + signal.siginterrupt(signal.SIGUSR1, False) + # Reset signals so Gunicorn doesn't swallow subprocess return codes + # See: https://github.com/aio-libs/aiohttp/issues/6130 + + def handle_quit(self, sig: int, frame: Optional[FrameType]) -> None: + self.alive = False + + # worker_int callback + self.cfg.worker_int(self) + + # wakeup closing process + self._notify_waiter_done() + + def handle_abort(self, sig: int, frame: Optional[FrameType]) -> None: + self.alive = False + self.exit_code = 1 + self.cfg.worker_abort(self) + sys.exit(1) + + @staticmethod + def _create_ssl_context(cfg: Any) -> "SSLContext": + """Creates SSLContext instance for usage in asyncio.create_server. + + See ssl.SSLSocket.__init__ for more details. + """ + if ssl is None: # pragma: no cover + raise RuntimeError("SSL is not supported.") + + ctx = ssl.SSLContext(cfg.ssl_version) + ctx.load_cert_chain(cfg.certfile, cfg.keyfile) + ctx.verify_mode = cfg.cert_reqs + if cfg.ca_certs: + ctx.load_verify_locations(cfg.ca_certs) + if cfg.ciphers: + ctx.set_ciphers(cfg.ciphers) + return ctx + + def _get_valid_log_format(self, source_format: str) -> str: + if source_format == self.DEFAULT_GUNICORN_LOG_FORMAT: + return self.DEFAULT_AIOHTTP_LOG_FORMAT + elif re.search(r"%\([^\)]+\)", source_format): + raise ValueError( + "Gunicorn's style options in form of `%(name)s` are not " + "supported for the log formatting. Please use aiohttp's " + "format specification to configure access log formatting: " + "http://docs.aiohttp.org/en/stable/logging.html" + "#format-specification" + ) + else: + return source_format + + +class GunicornUVLoopWebWorker(GunicornWebWorker): + def init_process(self) -> None: + import uvloop + + # Close any existing event loop before setting a + # new policy. + asyncio.get_event_loop().close() + + # Setup uvloop policy, so that every + # asyncio.get_event_loop() will create an instance + # of uvloop event loop. + asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) + + super().init_process() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/INSTALLER b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/METADATA b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..03a6f0f7ff91628f60c4a95c4f3acbfa8d654ea8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/METADATA @@ -0,0 +1,112 @@ +Metadata-Version: 2.4 +Name: aiosignal +Version: 1.4.0 +Summary: aiosignal: a list of registered asynchronous callbacks +Home-page: https://github.com/aio-libs/aiosignal +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache 2.0 +Project-URL: Chat: Gitter, https://gitter.im/aio-libs/Lobby +Project-URL: CI: GitHub Actions, https://github.com/aio-libs/aiosignal/actions +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/aiosignal +Project-URL: Docs: RTD, https://docs.aiosignal.org +Project-URL: GitHub: issues, https://github.com/aio-libs/aiosignal/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/aiosignal +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Development Status :: 5 - Production/Stable +Classifier: Operating System :: POSIX +Classifier: Operating System :: MacOS :: MacOS X +Classifier: Operating System :: Microsoft :: Windows +Classifier: Framework :: AsyncIO +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +Requires-Dist: frozenlist>=1.1.0 +Requires-Dist: typing-extensions>=4.2; python_version < "3.13" +Dynamic: license-file + +========= +aiosignal +========= + +.. image:: https://github.com/aio-libs/aiosignal/workflows/CI/badge.svg + :target: https://github.com/aio-libs/aiosignal/actions?query=workflow%3ACI + :alt: GitHub status for master branch + +.. image:: https://codecov.io/gh/aio-libs/aiosignal/branch/master/graph/badge.svg?flag=pytest + :target: https://codecov.io/gh/aio-libs/aiosignal?flags[0]=pytest + :alt: codecov.io status for master branch + +.. image:: https://badge.fury.io/py/aiosignal.svg + :target: https://pypi.org/project/aiosignal + :alt: Latest PyPI package version + +.. image:: https://readthedocs.org/projects/aiosignal/badge/?version=latest + :target: https://aiosignal.readthedocs.io/ + :alt: Latest Read The Docs + +.. image:: https://img.shields.io/discourse/topics?server=https%3A%2F%2Faio-libs.discourse.group%2F + :target: https://aio-libs.discourse.group/ + :alt: Discourse group for io-libs + +.. image:: https://badges.gitter.im/Join%20Chat.svg + :target: https://gitter.im/aio-libs/Lobby + :alt: Chat on Gitter + +Introduction +============ + +A project to manage callbacks in `asyncio` projects. + +``Signal`` is a list of registered asynchronous callbacks. + +The signal's life-cycle has two stages: after creation its content +could be filled by using standard list operations: ``sig.append()`` +etc. + +After you call ``sig.freeze()`` the signal is *frozen*: adding, removing +and dropping callbacks is forbidden. + +The only available operation is calling the previously registered +callbacks by using ``await sig.send(data)``. + +For concrete usage examples see the `Signals + +section of the `Web Server Advanced +` chapter of the `aiohttp +documentation`_. + + +Installation +------------ + +:: + + $ pip install aiosignal + + +Documentation +============= + +https://aiosignal.readthedocs.io/ + +License +======= + +``aiosignal`` is offered under the Apache 2 license. + +Source code +=========== + +The project is hosted on GitHub_ + +Please file an issue in the `bug tracker +`_ if you have found a bug +or have some suggestions to improve the library. + +.. _GitHub: https://github.com/aio-libs/aiosignal +.. _aiohttp documentation: https://docs.aiohttp.org/ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/RECORD b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..df5ca06f6fe1bbec1a02456b5b001a34771ecced --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/RECORD @@ -0,0 +1,9 @@ +aiosignal-1.4.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +aiosignal-1.4.0.dist-info/METADATA,sha256=CSR-8dqLxpZyjUcTDnAuQwf299EB1sSFv_nzpxznAI0,3662 +aiosignal-1.4.0.dist-info/RECORD,, +aiosignal-1.4.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91 +aiosignal-1.4.0.dist-info/licenses/LICENSE,sha256=b9UkPpLdf5jsacesN3co50kFcJ_1J6W_mNbQJjwE9bY,11332 +aiosignal-1.4.0.dist-info/top_level.txt,sha256=z45aNOKGDdrI1roqZY3BGXQ22kJFPHBmVdwtLYLtXC0,10 +aiosignal/__init__.py,sha256=TIkmUG9HTBt4dfq2nISYBiZiRB2xwvFtEZydLP0HPL4,1537 +aiosignal/__pycache__/__init__.cpython-312.pyc,, +aiosignal/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/WHEEL b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e7fa31b6f3f78deb1022c1f7927f07d4d16da822 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/top_level.txt b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..ac6df3afe74a5fd43afc7ab7f8393571a495fdc5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal-1.4.0.dist-info/top_level.txt @@ -0,0 +1 @@ +aiosignal diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5ede0090ad93cacd642b11645c1c71bcd3021e2b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal/__init__.py @@ -0,0 +1,59 @@ +import sys +from typing import Any, Awaitable, Callable, TypeVar + +from frozenlist import FrozenList + +if sys.version_info >= (3, 11): + from typing import Unpack +else: + from typing_extensions import Unpack + +if sys.version_info >= (3, 13): + from typing import TypeVarTuple +else: + from typing_extensions import TypeVarTuple + +_T = TypeVar("_T") +_Ts = TypeVarTuple("_Ts", default=Unpack[tuple[()]]) + +__version__ = "1.4.0" + +__all__ = ("Signal",) + + +class Signal(FrozenList[Callable[[Unpack[_Ts]], Awaitable[object]]]): + """Coroutine-based signal implementation. + + To connect a callback to a signal, use any list method. + + Signals are fired using the send() coroutine, which takes named + arguments. + """ + + __slots__ = ("_owner",) + + def __init__(self, owner: object): + super().__init__() + self._owner = owner + + def __repr__(self) -> str: + return "".format( + self._owner, self.frozen, list(self) + ) + + async def send(self, *args: Unpack[_Ts], **kwargs: Any) -> None: + """ + Sends data to all registered receivers. + """ + if not self.frozen: + raise RuntimeError("Cannot send non-frozen signal.") + + for receiver in self: + await receiver(*args, **kwargs) + + def __call__( + self, func: Callable[[Unpack[_Ts]], Awaitable[_T]] + ) -> Callable[[Unpack[_Ts]], Awaitable[_T]]: + """Decorator to add a function to this Signal.""" + self.append(func) + return func diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal/py.typed b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/aiosignal/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c6e0650bc4bf53806420d7ef5f881ecd2bd77ea --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/__init__.py @@ -0,0 +1,104 @@ +# SPDX-License-Identifier: MIT + +""" +Classes Without Boilerplate +""" + +from functools import partial +from typing import Callable, Literal, Protocol + +from . import converters, exceptions, filters, setters, validators +from ._cmp import cmp_using +from ._config import get_run_validators, set_run_validators +from ._funcs import asdict, assoc, astuple, has, resolve_types +from ._make import ( + NOTHING, + Attribute, + Converter, + Factory, + _Nothing, + attrib, + attrs, + evolve, + fields, + fields_dict, + make_class, + validate, +) +from ._next_gen import define, field, frozen, mutable +from ._version_info import VersionInfo + + +s = attributes = attrs +ib = attr = attrib +dataclass = partial(attrs, auto_attribs=True) # happy Easter ;) + + +class AttrsInstance(Protocol): + pass + + +NothingType = Literal[_Nothing.NOTHING] + +__all__ = [ + "NOTHING", + "Attribute", + "AttrsInstance", + "Converter", + "Factory", + "NothingType", + "asdict", + "assoc", + "astuple", + "attr", + "attrib", + "attributes", + "attrs", + "cmp_using", + "converters", + "define", + "evolve", + "exceptions", + "field", + "fields", + "fields_dict", + "filters", + "frozen", + "get_run_validators", + "has", + "ib", + "make_class", + "mutable", + "resolve_types", + "s", + "set_run_validators", + "setters", + "validate", + "validators", +] + + +def _make_getattr(mod_name: str) -> Callable: + """ + Create a metadata proxy for packaging information that uses *mod_name* in + its warnings and errors. + """ + + def __getattr__(name: str) -> str: + if name not in ("__version__", "__version_info__"): + msg = f"module {mod_name} has no attribute {name}" + raise AttributeError(msg) + + from importlib.metadata import metadata + + meta = metadata("attrs") + + if name == "__version_info__": + return VersionInfo._from_version_string(meta["version"]) + + return meta["version"] + + return __getattr__ + + +__getattr__ = _make_getattr(__name__) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/__init__.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..133e50105de3cef606889f32d85f324d94ee40f3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/__init__.pyi @@ -0,0 +1,389 @@ +import enum +import sys + +from typing import ( + Any, + Callable, + Generic, + Literal, + Mapping, + Protocol, + Sequence, + TypeVar, + overload, +) + +# `import X as X` is required to make these public +from . import converters as converters +from . import exceptions as exceptions +from . import filters as filters +from . import setters as setters +from . import validators as validators +from ._cmp import cmp_using as cmp_using +from ._typing_compat import AttrsInstance_ +from ._version_info import VersionInfo +from attrs import ( + define as define, + field as field, + mutable as mutable, + frozen as frozen, + _EqOrderType, + _ValidatorType, + _ConverterType, + _ReprArgType, + _OnSetAttrType, + _OnSetAttrArgType, + _FieldTransformer, + _ValidatorArgType, +) + +if sys.version_info >= (3, 10): + from typing import TypeGuard, TypeAlias +else: + from typing_extensions import TypeGuard, TypeAlias + +if sys.version_info >= (3, 11): + from typing import dataclass_transform +else: + from typing_extensions import dataclass_transform + +__version__: str +__version_info__: VersionInfo +__title__: str +__description__: str +__url__: str +__uri__: str +__author__: str +__email__: str +__license__: str +__copyright__: str + +_T = TypeVar("_T") +_C = TypeVar("_C", bound=type) + +_FilterType = Callable[["Attribute[_T]", _T], bool] + +# We subclass this here to keep the protocol's qualified name clean. +class AttrsInstance(AttrsInstance_, Protocol): + pass + +_A = TypeVar("_A", bound=type[AttrsInstance]) + +class _Nothing(enum.Enum): + NOTHING = enum.auto() + +NOTHING = _Nothing.NOTHING +NothingType: TypeAlias = Literal[_Nothing.NOTHING] + +# NOTE: Factory lies about its return type to make this possible: +# `x: List[int] # = Factory(list)` +# Work around mypy issue #4554 in the common case by using an overload. + +@overload +def Factory(factory: Callable[[], _T]) -> _T: ... +@overload +def Factory( + factory: Callable[[Any], _T], + takes_self: Literal[True], +) -> _T: ... +@overload +def Factory( + factory: Callable[[], _T], + takes_self: Literal[False], +) -> _T: ... + +In = TypeVar("In") +Out = TypeVar("Out") + +class Converter(Generic[In, Out]): + @overload + def __init__(self, converter: Callable[[In], Out]) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, AttrsInstance, Attribute], Out], + *, + takes_self: Literal[True], + takes_field: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, Attribute], Out], + *, + takes_field: Literal[True], + ) -> None: ... + @overload + def __init__( + self, + converter: Callable[[In, AttrsInstance], Out], + *, + takes_self: Literal[True], + ) -> None: ... + +class Attribute(Generic[_T]): + name: str + default: _T | None + validator: _ValidatorType[_T] | None + repr: _ReprArgType + cmp: _EqOrderType + eq: _EqOrderType + order: _EqOrderType + hash: bool | None + init: bool + converter: Converter | None + metadata: dict[Any, Any] + type: type[_T] | None + kw_only: bool + on_setattr: _OnSetAttrType + alias: str | None + + def evolve(self, **changes: Any) -> "Attribute[Any]": ... + +# NOTE: We had several choices for the annotation to use for type arg: +# 1) Type[_T] +# - Pros: Handles simple cases correctly +# - Cons: Might produce less informative errors in the case of conflicting +# TypeVars e.g. `attr.ib(default='bad', type=int)` +# 2) Callable[..., _T] +# - Pros: Better error messages than #1 for conflicting TypeVars +# - Cons: Terrible error messages for validator checks. +# e.g. attr.ib(type=int, validator=validate_str) +# -> error: Cannot infer function type argument +# 3) type (and do all of the work in the mypy plugin) +# - Pros: Simple here, and we could customize the plugin with our own errors. +# - Cons: Would need to write mypy plugin code to handle all the cases. +# We chose option #1. + +# `attr` lies about its return type to make the following possible: +# attr() -> Any +# attr(8) -> int +# attr(validator=) -> Whatever the callable expects. +# This makes this type of assignments possible: +# x: int = attr(8) +# +# This form catches explicit None or no default but with no other arguments +# returns Any. +@overload +def attrib( + default: None = ..., + validator: None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: None = ..., + converter: None = ..., + factory: None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> Any: ... + +# This form catches an explicit None or no default and infers the type from the +# other arguments. +@overload +def attrib( + default: None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: type[_T] | None = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> _T: ... + +# This form catches an explicit default argument. +@overload +def attrib( + default: _T, + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: type[_T] | None = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> _T: ... + +# This form covers type=non-Type: e.g. forward references (str), Any +@overload +def attrib( + default: _T | None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + type: object = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., +) -> Any: ... +@overload +@dataclass_transform(order_default=True, field_specifiers=(attrib, field)) +def attrs( + maybe_cls: _C, + these: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + auto_detect: bool = ..., + collect_by_mro: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., + unsafe_hash: bool | None = ..., +) -> _C: ... +@overload +@dataclass_transform(order_default=True, field_specifiers=(attrib, field)) +def attrs( + maybe_cls: None = ..., + these: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + auto_detect: bool = ..., + collect_by_mro: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., + unsafe_hash: bool | None = ..., +) -> Callable[[_C], _C]: ... +def fields(cls: type[AttrsInstance]) -> Any: ... +def fields_dict(cls: type[AttrsInstance]) -> dict[str, Attribute[Any]]: ... +def validate(inst: AttrsInstance) -> None: ... +def resolve_types( + cls: _A, + globalns: dict[str, Any] | None = ..., + localns: dict[str, Any] | None = ..., + attribs: list[Attribute[Any]] | None = ..., + include_extras: bool = ..., +) -> _A: ... + +# TODO: add support for returning a proper attrs class from the mypy plugin +# we use Any instead of _CountingAttr so that e.g. `make_class('Foo', +# [attr.ib()])` is valid +def make_class( + name: str, + attrs: list[str] | tuple[str, ...] | dict[str, Any], + bases: tuple[type, ...] = ..., + class_body: dict[str, Any] | None = ..., + repr_ns: str | None = ..., + repr: bool = ..., + cmp: _EqOrderType | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + collect_by_mro: bool = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., +) -> type: ... + +# _funcs -- + +# TODO: add support for returning TypedDict from the mypy plugin +# FIXME: asdict/astuple do not honor their factory args. Waiting on one of +# these: +# https://github.com/python/mypy/issues/4236 +# https://github.com/python/typing/issues/253 +# XXX: remember to fix attrs.asdict/astuple too! +def asdict( + inst: AttrsInstance, + recurse: bool = ..., + filter: _FilterType[Any] | None = ..., + dict_factory: type[Mapping[Any, Any]] = ..., + retain_collection_types: bool = ..., + value_serializer: Callable[[type, Attribute[Any], Any], Any] | None = ..., + tuple_keys: bool | None = ..., +) -> dict[str, Any]: ... + +# TODO: add support for returning NamedTuple from the mypy plugin +def astuple( + inst: AttrsInstance, + recurse: bool = ..., + filter: _FilterType[Any] | None = ..., + tuple_factory: type[Sequence[Any]] = ..., + retain_collection_types: bool = ..., +) -> tuple[Any, ...]: ... +def has(cls: type) -> TypeGuard[type[AttrsInstance]]: ... +def assoc(inst: _T, **changes: Any) -> _T: ... +def evolve(inst: _T, **changes: Any) -> _T: ... + +# _config -- + +def set_run_validators(run: bool) -> None: ... +def get_run_validators() -> bool: ... + +# aliases -- + +s = attributes = attrs +ib = attr = attrib +dataclass = attrs # Technically, partial(attrs, auto_attribs=True) ;) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_cmp.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_cmp.py new file mode 100644 index 0000000000000000000000000000000000000000..09bab491f83ef4d15129f34b5f5a9e69bb34d63c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_cmp.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: MIT + + +import functools +import types + +from ._make import __ne__ + + +_operation_names = {"eq": "==", "lt": "<", "le": "<=", "gt": ">", "ge": ">="} + + +def cmp_using( + eq=None, + lt=None, + le=None, + gt=None, + ge=None, + require_same_type=True, + class_name="Comparable", +): + """ + Create a class that can be passed into `attrs.field`'s ``eq``, ``order``, + and ``cmp`` arguments to customize field comparison. + + The resulting class will have a full set of ordering methods if at least + one of ``{lt, le, gt, ge}`` and ``eq`` are provided. + + Args: + eq (typing.Callable | None): + Callable used to evaluate equality of two objects. + + lt (typing.Callable | None): + Callable used to evaluate whether one object is less than another + object. + + le (typing.Callable | None): + Callable used to evaluate whether one object is less than or equal + to another object. + + gt (typing.Callable | None): + Callable used to evaluate whether one object is greater than + another object. + + ge (typing.Callable | None): + Callable used to evaluate whether one object is greater than or + equal to another object. + + require_same_type (bool): + When `True`, equality and ordering methods will return + `NotImplemented` if objects are not of the same type. + + class_name (str | None): Name of class. Defaults to "Comparable". + + See `comparison` for more details. + + .. versionadded:: 21.1.0 + """ + + body = { + "__slots__": ["value"], + "__init__": _make_init(), + "_requirements": [], + "_is_comparable_to": _is_comparable_to, + } + + # Add operations. + num_order_functions = 0 + has_eq_function = False + + if eq is not None: + has_eq_function = True + body["__eq__"] = _make_operator("eq", eq) + body["__ne__"] = __ne__ + + if lt is not None: + num_order_functions += 1 + body["__lt__"] = _make_operator("lt", lt) + + if le is not None: + num_order_functions += 1 + body["__le__"] = _make_operator("le", le) + + if gt is not None: + num_order_functions += 1 + body["__gt__"] = _make_operator("gt", gt) + + if ge is not None: + num_order_functions += 1 + body["__ge__"] = _make_operator("ge", ge) + + type_ = types.new_class( + class_name, (object,), {}, lambda ns: ns.update(body) + ) + + # Add same type requirement. + if require_same_type: + type_._requirements.append(_check_same_type) + + # Add total ordering if at least one operation was defined. + if 0 < num_order_functions < 4: + if not has_eq_function: + # functools.total_ordering requires __eq__ to be defined, + # so raise early error here to keep a nice stack. + msg = "eq must be define is order to complete ordering from lt, le, gt, ge." + raise ValueError(msg) + type_ = functools.total_ordering(type_) + + return type_ + + +def _make_init(): + """ + Create __init__ method. + """ + + def __init__(self, value): + """ + Initialize object with *value*. + """ + self.value = value + + return __init__ + + +def _make_operator(name, func): + """ + Create operator method. + """ + + def method(self, other): + if not self._is_comparable_to(other): + return NotImplemented + + result = func(self.value, other.value) + if result is NotImplemented: + return NotImplemented + + return result + + method.__name__ = f"__{name}__" + method.__doc__ = ( + f"Return a {_operation_names[name]} b. Computed by attrs." + ) + + return method + + +def _is_comparable_to(self, other): + """ + Check whether `other` is comparable to `self`. + """ + return all(func(self, other) for func in self._requirements) + + +def _check_same_type(self, other): + """ + Return True if *self* and *other* are of the same type, False otherwise. + """ + return other.value.__class__ is self.value.__class__ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_cmp.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_cmp.pyi new file mode 100644 index 0000000000000000000000000000000000000000..cc7893b04520afa719b1412c7646c3c1b39bf94b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_cmp.pyi @@ -0,0 +1,13 @@ +from typing import Any, Callable + +_CompareWithType = Callable[[Any, Any], bool] + +def cmp_using( + eq: _CompareWithType | None = ..., + lt: _CompareWithType | None = ..., + le: _CompareWithType | None = ..., + gt: _CompareWithType | None = ..., + ge: _CompareWithType | None = ..., + require_same_type: bool = ..., + class_name: str = ..., +) -> type: ... diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_compat.py new file mode 100644 index 0000000000000000000000000000000000000000..22fcd78387b7b36f005ec5eee3fbf784ba87a93d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_compat.py @@ -0,0 +1,94 @@ +# SPDX-License-Identifier: MIT + +import inspect +import platform +import sys +import threading + +from collections.abc import Mapping, Sequence # noqa: F401 +from typing import _GenericAlias + + +PYPY = platform.python_implementation() == "PyPy" +PY_3_9_PLUS = sys.version_info[:2] >= (3, 9) +PY_3_10_PLUS = sys.version_info[:2] >= (3, 10) +PY_3_11_PLUS = sys.version_info[:2] >= (3, 11) +PY_3_12_PLUS = sys.version_info[:2] >= (3, 12) +PY_3_13_PLUS = sys.version_info[:2] >= (3, 13) +PY_3_14_PLUS = sys.version_info[:2] >= (3, 14) + + +if PY_3_14_PLUS: # pragma: no cover + import annotationlib + + _get_annotations = annotationlib.get_annotations + +else: + + def _get_annotations(cls): + """ + Get annotations for *cls*. + """ + return cls.__dict__.get("__annotations__", {}) + + +class _AnnotationExtractor: + """ + Extract type annotations from a callable, returning None whenever there + is none. + """ + + __slots__ = ["sig"] + + def __init__(self, callable): + try: + self.sig = inspect.signature(callable) + except (ValueError, TypeError): # inspect failed + self.sig = None + + def get_first_param_type(self): + """ + Return the type annotation of the first argument if it's not empty. + """ + if not self.sig: + return None + + params = list(self.sig.parameters.values()) + if params and params[0].annotation is not inspect.Parameter.empty: + return params[0].annotation + + return None + + def get_return_type(self): + """ + Return the return type if it's not empty. + """ + if ( + self.sig + and self.sig.return_annotation is not inspect.Signature.empty + ): + return self.sig.return_annotation + + return None + + +# Thread-local global to track attrs instances which are already being repr'd. +# This is needed because there is no other (thread-safe) way to pass info +# about the instances that are already being repr'd through the call stack +# in order to ensure we don't perform infinite recursion. +# +# For instance, if an instance contains a dict which contains that instance, +# we need to know that we're already repr'ing the outside instance from within +# the dict's repr() call. +# +# This lives here rather than in _make.py so that the functions in _make.py +# don't have a direct reference to the thread-local in their globals dict. +# If they have such a reference, it breaks cloudpickle. +repr_context = threading.local() + + +def get_generic_base(cl): + """If this is a generic class (A[str]), return the generic base for it.""" + if cl.__class__ is _GenericAlias: + return cl.__origin__ + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_config.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_config.py new file mode 100644 index 0000000000000000000000000000000000000000..4b257726fb1e8b95583ecc3eee8d153336dc4089 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_config.py @@ -0,0 +1,31 @@ +# SPDX-License-Identifier: MIT + +__all__ = ["get_run_validators", "set_run_validators"] + +_run_validators = True + + +def set_run_validators(run): + """ + Set whether or not validators are run. By default, they are run. + + .. deprecated:: 21.3.0 It will not be removed, but it also will not be + moved to new ``attrs`` namespace. Use `attrs.validators.set_disabled()` + instead. + """ + if not isinstance(run, bool): + msg = "'run' must be bool." + raise TypeError(msg) + global _run_validators + _run_validators = run + + +def get_run_validators(): + """ + Return whether or not validators are run. + + .. deprecated:: 21.3.0 It will not be removed, but it also will not be + moved to new ``attrs`` namespace. Use `attrs.validators.get_disabled()` + instead. + """ + return _run_validators diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_funcs.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_funcs.py new file mode 100644 index 0000000000000000000000000000000000000000..c39fb8aa5a9426c18157253aad4b0168084eeb1a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_funcs.py @@ -0,0 +1,468 @@ +# SPDX-License-Identifier: MIT + + +import copy + +from ._compat import PY_3_9_PLUS, get_generic_base +from ._make import _OBJ_SETATTR, NOTHING, fields +from .exceptions import AttrsAttributeNotFoundError + + +def asdict( + inst, + recurse=True, + filter=None, + dict_factory=dict, + retain_collection_types=False, + value_serializer=None, +): + """ + Return the *attrs* attribute values of *inst* as a dict. + + Optionally recurse into other *attrs*-decorated classes. + + Args: + inst: Instance of an *attrs*-decorated class. + + recurse (bool): Recurse into classes that are also *attrs*-decorated. + + filter (~typing.Callable): + A callable whose return code determines whether an attribute or + element is included (`True`) or dropped (`False`). Is called with + the `attrs.Attribute` as the first argument and the value as the + second argument. + + dict_factory (~typing.Callable): + A callable to produce dictionaries from. For example, to produce + ordered dictionaries instead of normal Python dictionaries, pass in + ``collections.OrderedDict``. + + retain_collection_types (bool): + Do not convert to `list` when encountering an attribute whose type + is `tuple` or `set`. Only meaningful if *recurse* is `True`. + + value_serializer (typing.Callable | None): + A hook that is called for every attribute or dict key/value. It + receives the current instance, field and value and must return the + (updated) value. The hook is run *after* the optional *filter* has + been applied. + + Returns: + Return type of *dict_factory*. + + Raises: + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 16.0.0 *dict_factory* + .. versionadded:: 16.1.0 *retain_collection_types* + .. versionadded:: 20.3.0 *value_serializer* + .. versionadded:: 21.3.0 + If a dict has a collection for a key, it is serialized as a tuple. + """ + attrs = fields(inst.__class__) + rv = dict_factory() + for a in attrs: + v = getattr(inst, a.name) + if filter is not None and not filter(a, v): + continue + + if value_serializer is not None: + v = value_serializer(inst, a, v) + + if recurse is True: + if has(v.__class__): + rv[a.name] = asdict( + v, + recurse=True, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + elif isinstance(v, (tuple, list, set, frozenset)): + cf = v.__class__ if retain_collection_types is True else list + items = [ + _asdict_anything( + i, + is_key=False, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + for i in v + ] + try: + rv[a.name] = cf(items) + except TypeError: + if not issubclass(cf, tuple): + raise + # Workaround for TypeError: cf.__new__() missing 1 required + # positional argument (which appears, for a namedturle) + rv[a.name] = cf(*items) + elif isinstance(v, dict): + df = dict_factory + rv[a.name] = df( + ( + _asdict_anything( + kk, + is_key=True, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + _asdict_anything( + vv, + is_key=False, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + ) + for kk, vv in v.items() + ) + else: + rv[a.name] = v + else: + rv[a.name] = v + return rv + + +def _asdict_anything( + val, + is_key, + filter, + dict_factory, + retain_collection_types, + value_serializer, +): + """ + ``asdict`` only works on attrs instances, this works on anything. + """ + if getattr(val.__class__, "__attrs_attrs__", None) is not None: + # Attrs class. + rv = asdict( + val, + recurse=True, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + elif isinstance(val, (tuple, list, set, frozenset)): + if retain_collection_types is True: + cf = val.__class__ + elif is_key: + cf = tuple + else: + cf = list + + rv = cf( + [ + _asdict_anything( + i, + is_key=False, + filter=filter, + dict_factory=dict_factory, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ) + for i in val + ] + ) + elif isinstance(val, dict): + df = dict_factory + rv = df( + ( + _asdict_anything( + kk, + is_key=True, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + _asdict_anything( + vv, + is_key=False, + filter=filter, + dict_factory=df, + retain_collection_types=retain_collection_types, + value_serializer=value_serializer, + ), + ) + for kk, vv in val.items() + ) + else: + rv = val + if value_serializer is not None: + rv = value_serializer(None, None, rv) + + return rv + + +def astuple( + inst, + recurse=True, + filter=None, + tuple_factory=tuple, + retain_collection_types=False, +): + """ + Return the *attrs* attribute values of *inst* as a tuple. + + Optionally recurse into other *attrs*-decorated classes. + + Args: + inst: Instance of an *attrs*-decorated class. + + recurse (bool): + Recurse into classes that are also *attrs*-decorated. + + filter (~typing.Callable): + A callable whose return code determines whether an attribute or + element is included (`True`) or dropped (`False`). Is called with + the `attrs.Attribute` as the first argument and the value as the + second argument. + + tuple_factory (~typing.Callable): + A callable to produce tuples from. For example, to produce lists + instead of tuples. + + retain_collection_types (bool): + Do not convert to `list` or `dict` when encountering an attribute + which type is `tuple`, `dict` or `set`. Only meaningful if + *recurse* is `True`. + + Returns: + Return type of *tuple_factory* + + Raises: + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 16.2.0 + """ + attrs = fields(inst.__class__) + rv = [] + retain = retain_collection_types # Very long. :/ + for a in attrs: + v = getattr(inst, a.name) + if filter is not None and not filter(a, v): + continue + if recurse is True: + if has(v.__class__): + rv.append( + astuple( + v, + recurse=True, + filter=filter, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + ) + elif isinstance(v, (tuple, list, set, frozenset)): + cf = v.__class__ if retain is True else list + items = [ + ( + astuple( + j, + recurse=True, + filter=filter, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(j.__class__) + else j + ) + for j in v + ] + try: + rv.append(cf(items)) + except TypeError: + if not issubclass(cf, tuple): + raise + # Workaround for TypeError: cf.__new__() missing 1 required + # positional argument (which appears, for a namedturle) + rv.append(cf(*items)) + elif isinstance(v, dict): + df = v.__class__ if retain is True else dict + rv.append( + df( + ( + ( + astuple( + kk, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(kk.__class__) + else kk + ), + ( + astuple( + vv, + tuple_factory=tuple_factory, + retain_collection_types=retain, + ) + if has(vv.__class__) + else vv + ), + ) + for kk, vv in v.items() + ) + ) + else: + rv.append(v) + else: + rv.append(v) + + return rv if tuple_factory is list else tuple_factory(rv) + + +def has(cls): + """ + Check whether *cls* is a class with *attrs* attributes. + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + Returns: + bool: + """ + attrs = getattr(cls, "__attrs_attrs__", None) + if attrs is not None: + return True + + # No attrs, maybe it's a specialized generic (A[str])? + generic_base = get_generic_base(cls) + if generic_base is not None: + generic_attrs = getattr(generic_base, "__attrs_attrs__", None) + if generic_attrs is not None: + # Stick it on here for speed next time. + cls.__attrs_attrs__ = generic_attrs + return generic_attrs is not None + return False + + +def assoc(inst, **changes): + """ + Copy *inst* and apply *changes*. + + This is different from `evolve` that applies the changes to the arguments + that create the new instance. + + `evolve`'s behavior is preferable, but there are `edge cases`_ where it + doesn't work. Therefore `assoc` is deprecated, but will not be removed. + + .. _`edge cases`: https://github.com/python-attrs/attrs/issues/251 + + Args: + inst: Instance of a class with *attrs* attributes. + + changes: Keyword changes in the new copy. + + Returns: + A copy of inst with *changes* incorporated. + + Raises: + attrs.exceptions.AttrsAttributeNotFoundError: + If *attr_name* couldn't be found on *cls*. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. deprecated:: 17.1.0 + Use `attrs.evolve` instead if you can. This function will not be + removed du to the slightly different approach compared to + `attrs.evolve`, though. + """ + new = copy.copy(inst) + attrs = fields(inst.__class__) + for k, v in changes.items(): + a = getattr(attrs, k, NOTHING) + if a is NOTHING: + msg = f"{k} is not an attrs attribute on {new.__class__}." + raise AttrsAttributeNotFoundError(msg) + _OBJ_SETATTR(new, k, v) + return new + + +def resolve_types( + cls, globalns=None, localns=None, attribs=None, include_extras=True +): + """ + Resolve any strings and forward annotations in type annotations. + + This is only required if you need concrete types in :class:`Attribute`'s + *type* field. In other words, you don't need to resolve your types if you + only use them for static type checking. + + With no arguments, names will be looked up in the module in which the class + was created. If this is not what you want, for example, if the name only + exists inside a method, you may pass *globalns* or *localns* to specify + other dictionaries in which to look up these names. See the docs of + `typing.get_type_hints` for more details. + + Args: + cls (type): Class to resolve. + + globalns (dict | None): Dictionary containing global variables. + + localns (dict | None): Dictionary containing local variables. + + attribs (list | None): + List of attribs for the given class. This is necessary when calling + from inside a ``field_transformer`` since *cls* is not an *attrs* + class yet. + + include_extras (bool): + Resolve more accurately, if possible. Pass ``include_extras`` to + ``typing.get_hints``, if supported by the typing module. On + supported Python versions (3.9+), this resolves the types more + accurately. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class and you didn't pass any attribs. + + NameError: If types cannot be resolved because of missing variables. + + Returns: + *cls* so you can use this function also as a class decorator. Please + note that you have to apply it **after** `attrs.define`. That means the + decorator has to come in the line **before** `attrs.define`. + + .. versionadded:: 20.1.0 + .. versionadded:: 21.1.0 *attribs* + .. versionadded:: 23.1.0 *include_extras* + """ + # Since calling get_type_hints is expensive we cache whether we've + # done it already. + if getattr(cls, "__attrs_types_resolved__", None) != cls: + import typing + + kwargs = {"globalns": globalns, "localns": localns} + + if PY_3_9_PLUS: + kwargs["include_extras"] = include_extras + + hints = typing.get_type_hints(cls, **kwargs) + for field in fields(cls) if attribs is None else attribs: + if field.name in hints: + # Since fields have been frozen we must work around it. + _OBJ_SETATTR(field, "type", hints[field.name]) + # We store the class we resolved so that subclasses know they haven't + # been resolved. + cls.__attrs_types_resolved__ = cls + + # Return the class so you can use it as a decorator too. + return cls diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_make.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_make.py new file mode 100644 index 0000000000000000000000000000000000000000..e84d9792a744f34934a45b26d457f669596f7dee --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_make.py @@ -0,0 +1,3123 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +import abc +import contextlib +import copy +import enum +import inspect +import itertools +import linecache +import sys +import types +import unicodedata + +from collections.abc import Callable, Mapping +from functools import cached_property +from typing import Any, NamedTuple, TypeVar + +# We need to import _compat itself in addition to the _compat members to avoid +# having the thread-local in the globals here. +from . import _compat, _config, setters +from ._compat import ( + PY_3_10_PLUS, + PY_3_11_PLUS, + PY_3_13_PLUS, + _AnnotationExtractor, + _get_annotations, + get_generic_base, +) +from .exceptions import ( + DefaultAlreadySetError, + FrozenInstanceError, + NotAnAttrsClassError, + UnannotatedAttributeError, +) + + +# This is used at least twice, so cache it here. +_OBJ_SETATTR = object.__setattr__ +_INIT_FACTORY_PAT = "__attr_factory_%s" +_CLASSVAR_PREFIXES = ( + "typing.ClassVar", + "t.ClassVar", + "ClassVar", + "typing_extensions.ClassVar", +) +# we don't use a double-underscore prefix because that triggers +# name mangling when trying to create a slot for the field +# (when slots=True) +_HASH_CACHE_FIELD = "_attrs_cached_hash" + +_EMPTY_METADATA_SINGLETON = types.MappingProxyType({}) + +# Unique object for unequivocal getattr() defaults. +_SENTINEL = object() + +_DEFAULT_ON_SETATTR = setters.pipe(setters.convert, setters.validate) + + +class _Nothing(enum.Enum): + """ + Sentinel to indicate the lack of a value when `None` is ambiguous. + + If extending attrs, you can use ``typing.Literal[NOTHING]`` to show + that a value may be ``NOTHING``. + + .. versionchanged:: 21.1.0 ``bool(NOTHING)`` is now False. + .. versionchanged:: 22.2.0 ``NOTHING`` is now an ``enum.Enum`` variant. + """ + + NOTHING = enum.auto() + + def __repr__(self): + return "NOTHING" + + def __bool__(self): + return False + + +NOTHING = _Nothing.NOTHING +""" +Sentinel to indicate the lack of a value when `None` is ambiguous. + +When using in 3rd party code, use `attrs.NothingType` for type annotations. +""" + + +class _CacheHashWrapper(int): + """ + An integer subclass that pickles / copies as None + + This is used for non-slots classes with ``cache_hash=True``, to avoid + serializing a potentially (even likely) invalid hash value. Since `None` + is the default value for uncalculated hashes, whenever this is copied, + the copy's value for the hash should automatically reset. + + See GH #613 for more details. + """ + + def __reduce__(self, _none_constructor=type(None), _args=()): # noqa: B008 + return _none_constructor, _args + + +def attrib( + default=NOTHING, + validator=None, + repr=True, + cmp=None, + hash=None, + init=True, + metadata=None, + type=None, + converter=None, + factory=None, + kw_only=False, + eq=None, + order=None, + on_setattr=None, + alias=None, +): + """ + Create a new field / attribute on a class. + + Identical to `attrs.field`, except it's not keyword-only. + + Consider using `attrs.field` in new code (``attr.ib`` will *never* go away, + though). + + .. warning:: + + Does **nothing** unless the class is also decorated with + `attr.s` (or similar)! + + + .. versionadded:: 15.2.0 *convert* + .. versionadded:: 16.3.0 *metadata* + .. versionchanged:: 17.1.0 *validator* can be a ``list`` now. + .. versionchanged:: 17.1.0 + *hash* is `None` and therefore mirrors *eq* by default. + .. versionadded:: 17.3.0 *type* + .. deprecated:: 17.4.0 *convert* + .. versionadded:: 17.4.0 + *converter* as a replacement for the deprecated *convert* to achieve + consistency with other noun-based arguments. + .. versionadded:: 18.1.0 + ``factory=f`` is syntactic sugar for ``default=attr.Factory(f)``. + .. versionadded:: 18.2.0 *kw_only* + .. versionchanged:: 19.2.0 *convert* keyword argument removed. + .. versionchanged:: 19.2.0 *repr* also accepts a custom callable. + .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. + .. versionadded:: 19.2.0 *eq* and *order* + .. versionadded:: 20.1.0 *on_setattr* + .. versionchanged:: 20.3.0 *kw_only* backported to Python 2 + .. versionchanged:: 21.1.0 + *eq*, *order*, and *cmp* also accept a custom callable + .. versionchanged:: 21.1.0 *cmp* undeprecated + .. versionadded:: 22.2.0 *alias* + """ + eq, eq_key, order, order_key = _determine_attrib_eq_order( + cmp, eq, order, True + ) + + if hash is not None and hash is not True and hash is not False: + msg = "Invalid value for hash. Must be True, False, or None." + raise TypeError(msg) + + if factory is not None: + if default is not NOTHING: + msg = ( + "The `default` and `factory` arguments are mutually exclusive." + ) + raise ValueError(msg) + if not callable(factory): + msg = "The `factory` argument must be a callable." + raise ValueError(msg) + default = Factory(factory) + + if metadata is None: + metadata = {} + + # Apply syntactic sugar by auto-wrapping. + if isinstance(on_setattr, (list, tuple)): + on_setattr = setters.pipe(*on_setattr) + + if validator and isinstance(validator, (list, tuple)): + validator = and_(*validator) + + if converter and isinstance(converter, (list, tuple)): + converter = pipe(*converter) + + return _CountingAttr( + default=default, + validator=validator, + repr=repr, + cmp=None, + hash=hash, + init=init, + converter=converter, + metadata=metadata, + type=type, + kw_only=kw_only, + eq=eq, + eq_key=eq_key, + order=order, + order_key=order_key, + on_setattr=on_setattr, + alias=alias, + ) + + +def _compile_and_eval( + script: str, + globs: dict[str, Any] | None, + locs: Mapping[str, object] | None = None, + filename: str = "", +) -> None: + """ + Evaluate the script with the given global (globs) and local (locs) + variables. + """ + bytecode = compile(script, filename, "exec") + eval(bytecode, globs, locs) + + +def _linecache_and_compile( + script: str, + filename: str, + globs: dict[str, Any] | None, + locals: Mapping[str, object] | None = None, +) -> dict[str, Any]: + """ + Cache the script with _linecache_, compile it and return the _locals_. + """ + + locs = {} if locals is None else locals + + # In order of debuggers like PDB being able to step through the code, + # we add a fake linecache entry. + count = 1 + base_filename = filename + while True: + linecache_tuple = ( + len(script), + None, + script.splitlines(True), + filename, + ) + old_val = linecache.cache.setdefault(filename, linecache_tuple) + if old_val == linecache_tuple: + break + + filename = f"{base_filename[:-1]}-{count}>" + count += 1 + + _compile_and_eval(script, globs, locs, filename) + + return locs + + +def _make_attr_tuple_class(cls_name: str, attr_names: list[str]) -> type: + """ + Create a tuple subclass to hold `Attribute`s for an `attrs` class. + + The subclass is a bare tuple with properties for names. + + class MyClassAttributes(tuple): + __slots__ = () + x = property(itemgetter(0)) + """ + attr_class_name = f"{cls_name}Attributes" + body = {} + for i, attr_name in enumerate(attr_names): + + def getter(self, i=i): + return self[i] + + body[attr_name] = property(getter) + return type(attr_class_name, (tuple,), body) + + +# Tuple class for extracted attributes from a class definition. +# `base_attrs` is a subset of `attrs`. +class _Attributes(NamedTuple): + attrs: type + base_attrs: list[Attribute] + base_attrs_map: dict[str, type] + + +def _is_class_var(annot): + """ + Check whether *annot* is a typing.ClassVar. + + The string comparison hack is used to avoid evaluating all string + annotations which would put attrs-based classes at a performance + disadvantage compared to plain old classes. + """ + annot = str(annot) + + # Annotation can be quoted. + if annot.startswith(("'", '"')) and annot.endswith(("'", '"')): + annot = annot[1:-1] + + return annot.startswith(_CLASSVAR_PREFIXES) + + +def _has_own_attribute(cls, attrib_name): + """ + Check whether *cls* defines *attrib_name* (and doesn't just inherit it). + """ + return attrib_name in cls.__dict__ + + +def _collect_base_attrs( + cls, taken_attr_names +) -> tuple[list[Attribute], dict[str, type]]: + """ + Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. + """ + base_attrs = [] + base_attr_map = {} # A dictionary of base attrs to their classes. + + # Traverse the MRO and collect attributes. + for base_cls in reversed(cls.__mro__[1:-1]): + for a in getattr(base_cls, "__attrs_attrs__", []): + if a.inherited or a.name in taken_attr_names: + continue + + a = a.evolve(inherited=True) # noqa: PLW2901 + base_attrs.append(a) + base_attr_map[a.name] = base_cls + + # For each name, only keep the freshest definition i.e. the furthest at the + # back. base_attr_map is fine because it gets overwritten with every new + # instance. + filtered = [] + seen = set() + for a in reversed(base_attrs): + if a.name in seen: + continue + filtered.insert(0, a) + seen.add(a.name) + + return filtered, base_attr_map + + +def _collect_base_attrs_broken(cls, taken_attr_names): + """ + Collect attr.ibs from base classes of *cls*, except *taken_attr_names*. + + N.B. *taken_attr_names* will be mutated. + + Adhere to the old incorrect behavior. + + Notably it collects from the front and considers inherited attributes which + leads to the buggy behavior reported in #428. + """ + base_attrs = [] + base_attr_map = {} # A dictionary of base attrs to their classes. + + # Traverse the MRO and collect attributes. + for base_cls in cls.__mro__[1:-1]: + for a in getattr(base_cls, "__attrs_attrs__", []): + if a.name in taken_attr_names: + continue + + a = a.evolve(inherited=True) # noqa: PLW2901 + taken_attr_names.add(a.name) + base_attrs.append(a) + base_attr_map[a.name] = base_cls + + return base_attrs, base_attr_map + + +def _transform_attrs( + cls, these, auto_attribs, kw_only, collect_by_mro, field_transformer +) -> _Attributes: + """ + Transform all `_CountingAttr`s on a class into `Attribute`s. + + If *these* is passed, use that and don't look for them on the class. + + If *collect_by_mro* is True, collect them in the correct MRO order, + otherwise use the old -- incorrect -- order. See #428. + + Return an `_Attributes`. + """ + cd = cls.__dict__ + anns = _get_annotations(cls) + + if these is not None: + ca_list = list(these.items()) + elif auto_attribs is True: + ca_names = { + name + for name, attr in cd.items() + if attr.__class__ is _CountingAttr + } + ca_list = [] + annot_names = set() + for attr_name, type in anns.items(): + if _is_class_var(type): + continue + annot_names.add(attr_name) + a = cd.get(attr_name, NOTHING) + + if a.__class__ is not _CountingAttr: + a = attrib(a) + ca_list.append((attr_name, a)) + + unannotated = ca_names - annot_names + if unannotated: + raise UnannotatedAttributeError( + "The following `attr.ib`s lack a type annotation: " + + ", ".join( + sorted(unannotated, key=lambda n: cd.get(n).counter) + ) + + "." + ) + else: + ca_list = sorted( + ( + (name, attr) + for name, attr in cd.items() + if attr.__class__ is _CountingAttr + ), + key=lambda e: e[1].counter, + ) + + fca = Attribute.from_counting_attr + own_attrs = [ + fca(attr_name, ca, anns.get(attr_name)) for attr_name, ca in ca_list + ] + + if collect_by_mro: + base_attrs, base_attr_map = _collect_base_attrs( + cls, {a.name for a in own_attrs} + ) + else: + base_attrs, base_attr_map = _collect_base_attrs_broken( + cls, {a.name for a in own_attrs} + ) + + if kw_only: + own_attrs = [a.evolve(kw_only=True) for a in own_attrs] + base_attrs = [a.evolve(kw_only=True) for a in base_attrs] + + attrs = base_attrs + own_attrs + + if field_transformer is not None: + attrs = tuple(field_transformer(cls, attrs)) + + # Check attr order after executing the field_transformer. + # Mandatory vs non-mandatory attr order only matters when they are part of + # the __init__ signature and when they aren't kw_only (which are moved to + # the end and can be mandatory or non-mandatory in any order, as they will + # be specified as keyword args anyway). Check the order of those attrs: + had_default = False + for a in (a for a in attrs if a.init is not False and a.kw_only is False): + if had_default is True and a.default is NOTHING: + msg = f"No mandatory attributes allowed after an attribute with a default value or factory. Attribute in question: {a!r}" + raise ValueError(msg) + + if had_default is False and a.default is not NOTHING: + had_default = True + + # Resolve default field alias after executing field_transformer. + # This allows field_transformer to differentiate between explicit vs + # default aliases and supply their own defaults. + for a in attrs: + if not a.alias: + # Evolve is very slow, so we hold our nose and do it dirty. + _OBJ_SETATTR.__get__(a)("alias", _default_init_alias_for(a.name)) + + # Create AttrsClass *after* applying the field_transformer since it may + # add or remove attributes! + attr_names = [a.name for a in attrs] + AttrsClass = _make_attr_tuple_class(cls.__name__, attr_names) + + return _Attributes(AttrsClass(attrs), base_attrs, base_attr_map) + + +def _make_cached_property_getattr(cached_properties, original_getattr, cls): + lines = [ + # Wrapped to get `__class__` into closure cell for super() + # (It will be replaced with the newly constructed class after construction). + "def wrapper(_cls):", + " __class__ = _cls", + " def __getattr__(self, item, cached_properties=cached_properties, original_getattr=original_getattr, _cached_setattr_get=_cached_setattr_get):", + " func = cached_properties.get(item)", + " if func is not None:", + " result = func(self)", + " _setter = _cached_setattr_get(self)", + " _setter(item, result)", + " return result", + ] + if original_getattr is not None: + lines.append( + " return original_getattr(self, item)", + ) + else: + lines.extend( + [ + " try:", + " return super().__getattribute__(item)", + " except AttributeError:", + " if not hasattr(super(), '__getattr__'):", + " raise", + " return super().__getattr__(item)", + " original_error = f\"'{self.__class__.__name__}' object has no attribute '{item}'\"", + " raise AttributeError(original_error)", + ] + ) + + lines.extend( + [ + " return __getattr__", + "__getattr__ = wrapper(_cls)", + ] + ) + + unique_filename = _generate_unique_filename(cls, "getattr") + + glob = { + "cached_properties": cached_properties, + "_cached_setattr_get": _OBJ_SETATTR.__get__, + "original_getattr": original_getattr, + } + + return _linecache_and_compile( + "\n".join(lines), unique_filename, glob, locals={"_cls": cls} + )["__getattr__"] + + +def _frozen_setattrs(self, name, value): + """ + Attached to frozen classes as __setattr__. + """ + if isinstance(self, BaseException) and name in ( + "__cause__", + "__context__", + "__traceback__", + "__suppress_context__", + "__notes__", + ): + BaseException.__setattr__(self, name, value) + return + + raise FrozenInstanceError + + +def _frozen_delattrs(self, name): + """ + Attached to frozen classes as __delattr__. + """ + if isinstance(self, BaseException) and name in ("__notes__",): + BaseException.__delattr__(self, name) + return + + raise FrozenInstanceError + + +def evolve(*args, **changes): + """ + Create a new instance, based on the first positional argument with + *changes* applied. + + .. tip:: + + On Python 3.13 and later, you can also use `copy.replace` instead. + + Args: + + inst: + Instance of a class with *attrs* attributes. *inst* must be passed + as a positional argument. + + changes: + Keyword changes in the new copy. + + Returns: + A copy of inst with *changes* incorporated. + + Raises: + TypeError: + If *attr_name* couldn't be found in the class ``__init__``. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + .. versionadded:: 17.1.0 + .. deprecated:: 23.1.0 + It is now deprecated to pass the instance using the keyword argument + *inst*. It will raise a warning until at least April 2024, after which + it will become an error. Always pass the instance as a positional + argument. + .. versionchanged:: 24.1.0 + *inst* can't be passed as a keyword argument anymore. + """ + try: + (inst,) = args + except ValueError: + msg = ( + f"evolve() takes 1 positional argument, but {len(args)} were given" + ) + raise TypeError(msg) from None + + cls = inst.__class__ + attrs = fields(cls) + for a in attrs: + if not a.init: + continue + attr_name = a.name # To deal with private attributes. + init_name = a.alias + if init_name not in changes: + changes[init_name] = getattr(inst, attr_name) + + return cls(**changes) + + +class _ClassBuilder: + """ + Iteratively build *one* class. + """ + + __slots__ = ( + "_add_method_dunders", + "_attr_names", + "_attrs", + "_base_attr_map", + "_base_names", + "_cache_hash", + "_cls", + "_cls_dict", + "_delete_attribs", + "_frozen", + "_has_custom_setattr", + "_has_post_init", + "_has_pre_init", + "_is_exc", + "_on_setattr", + "_pre_init_has_args", + "_repr_added", + "_script_snippets", + "_slots", + "_weakref_slot", + "_wrote_own_setattr", + ) + + def __init__( + self, + cls: type, + these, + slots, + frozen, + weakref_slot, + getstate_setstate, + auto_attribs, + kw_only, + cache_hash, + is_exc, + collect_by_mro, + on_setattr, + has_custom_setattr, + field_transformer, + ): + attrs, base_attrs, base_map = _transform_attrs( + cls, + these, + auto_attribs, + kw_only, + collect_by_mro, + field_transformer, + ) + + self._cls = cls + self._cls_dict = dict(cls.__dict__) if slots else {} + self._attrs = attrs + self._base_names = {a.name for a in base_attrs} + self._base_attr_map = base_map + self._attr_names = tuple(a.name for a in attrs) + self._slots = slots + self._frozen = frozen + self._weakref_slot = weakref_slot + self._cache_hash = cache_hash + self._has_pre_init = bool(getattr(cls, "__attrs_pre_init__", False)) + self._pre_init_has_args = False + if self._has_pre_init: + # Check if the pre init method has more arguments than just `self` + # We want to pass arguments if pre init expects arguments + pre_init_func = cls.__attrs_pre_init__ + pre_init_signature = inspect.signature(pre_init_func) + self._pre_init_has_args = len(pre_init_signature.parameters) > 1 + self._has_post_init = bool(getattr(cls, "__attrs_post_init__", False)) + self._delete_attribs = not bool(these) + self._is_exc = is_exc + self._on_setattr = on_setattr + + self._has_custom_setattr = has_custom_setattr + self._wrote_own_setattr = False + + self._cls_dict["__attrs_attrs__"] = self._attrs + + if frozen: + self._cls_dict["__setattr__"] = _frozen_setattrs + self._cls_dict["__delattr__"] = _frozen_delattrs + + self._wrote_own_setattr = True + elif on_setattr in ( + _DEFAULT_ON_SETATTR, + setters.validate, + setters.convert, + ): + has_validator = has_converter = False + for a in attrs: + if a.validator is not None: + has_validator = True + if a.converter is not None: + has_converter = True + + if has_validator and has_converter: + break + if ( + ( + on_setattr == _DEFAULT_ON_SETATTR + and not (has_validator or has_converter) + ) + or (on_setattr == setters.validate and not has_validator) + or (on_setattr == setters.convert and not has_converter) + ): + # If class-level on_setattr is set to convert + validate, but + # there's no field to convert or validate, pretend like there's + # no on_setattr. + self._on_setattr = None + + if getstate_setstate: + ( + self._cls_dict["__getstate__"], + self._cls_dict["__setstate__"], + ) = self._make_getstate_setstate() + + # tuples of script, globs, hook + self._script_snippets: list[ + tuple[str, dict, Callable[[dict, dict], Any]] + ] = [] + self._repr_added = False + + # We want to only do this check once; in 99.9% of cases these + # exist. + if not hasattr(self._cls, "__module__") or not hasattr( + self._cls, "__qualname__" + ): + self._add_method_dunders = self._add_method_dunders_safe + else: + self._add_method_dunders = self._add_method_dunders_unsafe + + def __repr__(self): + return f"<_ClassBuilder(cls={self._cls.__name__})>" + + def _eval_snippets(self) -> None: + """ + Evaluate any registered snippets in one go. + """ + script = "\n".join([snippet[0] for snippet in self._script_snippets]) + globs = {} + for _, snippet_globs, _ in self._script_snippets: + globs.update(snippet_globs) + + locs = _linecache_and_compile( + script, + _generate_unique_filename(self._cls, "methods"), + globs, + ) + + for _, _, hook in self._script_snippets: + hook(self._cls_dict, locs) + + def build_class(self): + """ + Finalize class based on the accumulated configuration. + + Builder cannot be used after calling this method. + """ + self._eval_snippets() + if self._slots is True: + cls = self._create_slots_class() + else: + cls = self._patch_original_class() + if PY_3_10_PLUS: + cls = abc.update_abstractmethods(cls) + + # The method gets only called if it's not inherited from a base class. + # _has_own_attribute does NOT work properly for classmethods. + if ( + getattr(cls, "__attrs_init_subclass__", None) + and "__attrs_init_subclass__" not in cls.__dict__ + ): + cls.__attrs_init_subclass__() + + return cls + + def _patch_original_class(self): + """ + Apply accumulated methods and return the class. + """ + cls = self._cls + base_names = self._base_names + + # Clean class of attribute definitions (`attr.ib()`s). + if self._delete_attribs: + for name in self._attr_names: + if ( + name not in base_names + and getattr(cls, name, _SENTINEL) is not _SENTINEL + ): + # An AttributeError can happen if a base class defines a + # class variable and we want to set an attribute with the + # same name by using only a type annotation. + with contextlib.suppress(AttributeError): + delattr(cls, name) + + # Attach our dunder methods. + for name, value in self._cls_dict.items(): + setattr(cls, name, value) + + # If we've inherited an attrs __setattr__ and don't write our own, + # reset it to object's. + if not self._wrote_own_setattr and getattr( + cls, "__attrs_own_setattr__", False + ): + cls.__attrs_own_setattr__ = False + + if not self._has_custom_setattr: + cls.__setattr__ = _OBJ_SETATTR + + return cls + + def _create_slots_class(self): + """ + Build and return a new class with a `__slots__` attribute. + """ + cd = { + k: v + for k, v in self._cls_dict.items() + if k not in (*tuple(self._attr_names), "__dict__", "__weakref__") + } + + # If our class doesn't have its own implementation of __setattr__ + # (either from the user or by us), check the bases, if one of them has + # an attrs-made __setattr__, that needs to be reset. We don't walk the + # MRO because we only care about our immediate base classes. + # XXX: This can be confused by subclassing a slotted attrs class with + # XXX: a non-attrs class and subclass the resulting class with an attrs + # XXX: class. See `test_slotted_confused` for details. For now that's + # XXX: OK with us. + if not self._wrote_own_setattr: + cd["__attrs_own_setattr__"] = False + + if not self._has_custom_setattr: + for base_cls in self._cls.__bases__: + if base_cls.__dict__.get("__attrs_own_setattr__", False): + cd["__setattr__"] = _OBJ_SETATTR + break + + # Traverse the MRO to collect existing slots + # and check for an existing __weakref__. + existing_slots = {} + weakref_inherited = False + for base_cls in self._cls.__mro__[1:-1]: + if base_cls.__dict__.get("__weakref__", None) is not None: + weakref_inherited = True + existing_slots.update( + { + name: getattr(base_cls, name) + for name in getattr(base_cls, "__slots__", []) + } + ) + + base_names = set(self._base_names) + + names = self._attr_names + if ( + self._weakref_slot + and "__weakref__" not in getattr(self._cls, "__slots__", ()) + and "__weakref__" not in names + and not weakref_inherited + ): + names += ("__weakref__",) + + cached_properties = { + name: cached_prop.func + for name, cached_prop in cd.items() + if isinstance(cached_prop, cached_property) + } + + # Collect methods with a `__class__` reference that are shadowed in the new class. + # To know to update them. + additional_closure_functions_to_update = [] + if cached_properties: + class_annotations = _get_annotations(self._cls) + for name, func in cached_properties.items(): + # Add cached properties to names for slotting. + names += (name,) + # Clear out function from class to avoid clashing. + del cd[name] + additional_closure_functions_to_update.append(func) + annotation = inspect.signature(func).return_annotation + if annotation is not inspect.Parameter.empty: + class_annotations[name] = annotation + + original_getattr = cd.get("__getattr__") + if original_getattr is not None: + additional_closure_functions_to_update.append(original_getattr) + + cd["__getattr__"] = _make_cached_property_getattr( + cached_properties, original_getattr, self._cls + ) + + # We only add the names of attributes that aren't inherited. + # Setting __slots__ to inherited attributes wastes memory. + slot_names = [name for name in names if name not in base_names] + + # There are slots for attributes from current class + # that are defined in parent classes. + # As their descriptors may be overridden by a child class, + # we collect them here and update the class dict + reused_slots = { + slot: slot_descriptor + for slot, slot_descriptor in existing_slots.items() + if slot in slot_names + } + slot_names = [name for name in slot_names if name not in reused_slots] + cd.update(reused_slots) + if self._cache_hash: + slot_names.append(_HASH_CACHE_FIELD) + + cd["__slots__"] = tuple(slot_names) + + cd["__qualname__"] = self._cls.__qualname__ + + # Create new class based on old class and our methods. + cls = type(self._cls)(self._cls.__name__, self._cls.__bases__, cd) + + # The following is a fix for + # . + # If a method mentions `__class__` or uses the no-arg super(), the + # compiler will bake a reference to the class in the method itself + # as `method.__closure__`. Since we replace the class with a + # clone, we rewrite these references so it keeps working. + for item in itertools.chain( + cls.__dict__.values(), additional_closure_functions_to_update + ): + if isinstance(item, (classmethod, staticmethod)): + # Class- and staticmethods hide their functions inside. + # These might need to be rewritten as well. + closure_cells = getattr(item.__func__, "__closure__", None) + elif isinstance(item, property): + # Workaround for property `super()` shortcut (PY3-only). + # There is no universal way for other descriptors. + closure_cells = getattr(item.fget, "__closure__", None) + else: + closure_cells = getattr(item, "__closure__", None) + + if not closure_cells: # Catch None or the empty list. + continue + for cell in closure_cells: + try: + match = cell.cell_contents is self._cls + except ValueError: # noqa: PERF203 + # ValueError: Cell is empty + pass + else: + if match: + cell.cell_contents = cls + return cls + + def add_repr(self, ns): + script, globs = _make_repr_script(self._attrs, ns) + + def _attach_repr(cls_dict, globs): + cls_dict["__repr__"] = self._add_method_dunders(globs["__repr__"]) + + self._script_snippets.append((script, globs, _attach_repr)) + self._repr_added = True + return self + + def add_str(self): + if not self._repr_added: + msg = "__str__ can only be generated if a __repr__ exists." + raise ValueError(msg) + + def __str__(self): + return self.__repr__() + + self._cls_dict["__str__"] = self._add_method_dunders(__str__) + return self + + def _make_getstate_setstate(self): + """ + Create custom __setstate__ and __getstate__ methods. + """ + # __weakref__ is not writable. + state_attr_names = tuple( + an for an in self._attr_names if an != "__weakref__" + ) + + def slots_getstate(self): + """ + Automatically created by attrs. + """ + return {name: getattr(self, name) for name in state_attr_names} + + hash_caching_enabled = self._cache_hash + + def slots_setstate(self, state): + """ + Automatically created by attrs. + """ + __bound_setattr = _OBJ_SETATTR.__get__(self) + if isinstance(state, tuple): + # Backward compatibility with attrs instances pickled with + # attrs versions before v22.2.0 which stored tuples. + for name, value in zip(state_attr_names, state): + __bound_setattr(name, value) + else: + for name in state_attr_names: + if name in state: + __bound_setattr(name, state[name]) + + # The hash code cache is not included when the object is + # serialized, but it still needs to be initialized to None to + # indicate that the first call to __hash__ should be a cache + # miss. + if hash_caching_enabled: + __bound_setattr(_HASH_CACHE_FIELD, None) + + return slots_getstate, slots_setstate + + def make_unhashable(self): + self._cls_dict["__hash__"] = None + return self + + def add_hash(self): + script, globs = _make_hash_script( + self._cls, + self._attrs, + frozen=self._frozen, + cache_hash=self._cache_hash, + ) + + def attach_hash(cls_dict: dict, locs: dict) -> None: + cls_dict["__hash__"] = self._add_method_dunders(locs["__hash__"]) + + self._script_snippets.append((script, globs, attach_hash)) + + return self + + def add_init(self): + script, globs, annotations = _make_init_script( + self._cls, + self._attrs, + self._has_pre_init, + self._pre_init_has_args, + self._has_post_init, + self._frozen, + self._slots, + self._cache_hash, + self._base_attr_map, + self._is_exc, + self._on_setattr, + attrs_init=False, + ) + + def _attach_init(cls_dict, globs): + init = globs["__init__"] + init.__annotations__ = annotations + cls_dict["__init__"] = self._add_method_dunders(init) + + self._script_snippets.append((script, globs, _attach_init)) + + return self + + def add_replace(self): + self._cls_dict["__replace__"] = self._add_method_dunders( + lambda self, **changes: evolve(self, **changes) + ) + return self + + def add_match_args(self): + self._cls_dict["__match_args__"] = tuple( + field.name + for field in self._attrs + if field.init and not field.kw_only + ) + + def add_attrs_init(self): + script, globs, annotations = _make_init_script( + self._cls, + self._attrs, + self._has_pre_init, + self._pre_init_has_args, + self._has_post_init, + self._frozen, + self._slots, + self._cache_hash, + self._base_attr_map, + self._is_exc, + self._on_setattr, + attrs_init=True, + ) + + def _attach_attrs_init(cls_dict, globs): + init = globs["__attrs_init__"] + init.__annotations__ = annotations + cls_dict["__attrs_init__"] = self._add_method_dunders(init) + + self._script_snippets.append((script, globs, _attach_attrs_init)) + + return self + + def add_eq(self): + cd = self._cls_dict + + script, globs = _make_eq_script(self._attrs) + + def _attach_eq(cls_dict, globs): + cls_dict["__eq__"] = self._add_method_dunders(globs["__eq__"]) + + self._script_snippets.append((script, globs, _attach_eq)) + + cd["__ne__"] = __ne__ + + return self + + def add_order(self): + cd = self._cls_dict + + cd["__lt__"], cd["__le__"], cd["__gt__"], cd["__ge__"] = ( + self._add_method_dunders(meth) + for meth in _make_order(self._cls, self._attrs) + ) + + return self + + def add_setattr(self): + sa_attrs = {} + for a in self._attrs: + on_setattr = a.on_setattr or self._on_setattr + if on_setattr and on_setattr is not setters.NO_OP: + sa_attrs[a.name] = a, on_setattr + + if not sa_attrs: + return self + + if self._has_custom_setattr: + # We need to write a __setattr__ but there already is one! + msg = "Can't combine custom __setattr__ with on_setattr hooks." + raise ValueError(msg) + + # docstring comes from _add_method_dunders + def __setattr__(self, name, val): + try: + a, hook = sa_attrs[name] + except KeyError: + nval = val + else: + nval = hook(self, a, val) + + _OBJ_SETATTR(self, name, nval) + + self._cls_dict["__attrs_own_setattr__"] = True + self._cls_dict["__setattr__"] = self._add_method_dunders(__setattr__) + self._wrote_own_setattr = True + + return self + + def _add_method_dunders_unsafe(self, method: Callable) -> Callable: + """ + Add __module__ and __qualname__ to a *method*. + """ + method.__module__ = self._cls.__module__ + + method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}" + + method.__doc__ = ( + f"Method generated by attrs for class {self._cls.__qualname__}." + ) + + return method + + def _add_method_dunders_safe(self, method: Callable) -> Callable: + """ + Add __module__ and __qualname__ to a *method* if possible. + """ + with contextlib.suppress(AttributeError): + method.__module__ = self._cls.__module__ + + with contextlib.suppress(AttributeError): + method.__qualname__ = f"{self._cls.__qualname__}.{method.__name__}" + + with contextlib.suppress(AttributeError): + method.__doc__ = f"Method generated by attrs for class {self._cls.__qualname__}." + + return method + + +def _determine_attrs_eq_order(cmp, eq, order, default_eq): + """ + Validate the combination of *cmp*, *eq*, and *order*. Derive the effective + values of eq and order. If *eq* is None, set it to *default_eq*. + """ + if cmp is not None and any((eq is not None, order is not None)): + msg = "Don't mix `cmp` with `eq' and `order`." + raise ValueError(msg) + + # cmp takes precedence due to bw-compatibility. + if cmp is not None: + return cmp, cmp + + # If left None, equality is set to the specified default and ordering + # mirrors equality. + if eq is None: + eq = default_eq + + if order is None: + order = eq + + if eq is False and order is True: + msg = "`order` can only be True if `eq` is True too." + raise ValueError(msg) + + return eq, order + + +def _determine_attrib_eq_order(cmp, eq, order, default_eq): + """ + Validate the combination of *cmp*, *eq*, and *order*. Derive the effective + values of eq and order. If *eq* is None, set it to *default_eq*. + """ + if cmp is not None and any((eq is not None, order is not None)): + msg = "Don't mix `cmp` with `eq' and `order`." + raise ValueError(msg) + + def decide_callable_or_boolean(value): + """ + Decide whether a key function is used. + """ + if callable(value): + value, key = True, value + else: + key = None + return value, key + + # cmp takes precedence due to bw-compatibility. + if cmp is not None: + cmp, cmp_key = decide_callable_or_boolean(cmp) + return cmp, cmp_key, cmp, cmp_key + + # If left None, equality is set to the specified default and ordering + # mirrors equality. + if eq is None: + eq, eq_key = default_eq, None + else: + eq, eq_key = decide_callable_or_boolean(eq) + + if order is None: + order, order_key = eq, eq_key + else: + order, order_key = decide_callable_or_boolean(order) + + if eq is False and order is True: + msg = "`order` can only be True if `eq` is True too." + raise ValueError(msg) + + return eq, eq_key, order, order_key + + +def _determine_whether_to_implement( + cls, flag, auto_detect, dunders, default=True +): + """ + Check whether we should implement a set of methods for *cls*. + + *flag* is the argument passed into @attr.s like 'init', *auto_detect* the + same as passed into @attr.s and *dunders* is a tuple of attribute names + whose presence signal that the user has implemented it themselves. + + Return *default* if no reason for either for or against is found. + """ + if flag is True or flag is False: + return flag + + if flag is None and auto_detect is False: + return default + + # Logically, flag is None and auto_detect is True here. + for dunder in dunders: + if _has_own_attribute(cls, dunder): + return False + + return default + + +def attrs( + maybe_cls=None, + these=None, + repr_ns=None, + repr=None, + cmp=None, + hash=None, + init=None, + slots=False, + frozen=False, + weakref_slot=True, + str=False, + auto_attribs=False, + kw_only=False, + cache_hash=False, + auto_exc=False, + eq=None, + order=None, + auto_detect=False, + collect_by_mro=False, + getstate_setstate=None, + on_setattr=None, + field_transformer=None, + match_args=True, + unsafe_hash=None, +): + r""" + A class decorator that adds :term:`dunder methods` according to the + specified attributes using `attr.ib` or the *these* argument. + + Consider using `attrs.define` / `attrs.frozen` in new code (``attr.s`` will + *never* go away, though). + + Args: + repr_ns (str): + When using nested classes, there was no way in Python 2 to + automatically detect that. This argument allows to set a custom + name for a more meaningful ``repr`` output. This argument is + pointless in Python 3 and is therefore deprecated. + + .. caution:: + Refer to `attrs.define` for the rest of the parameters, but note that they + can have different defaults. + + Notably, leaving *on_setattr* as `None` will **not** add any hooks. + + .. versionadded:: 16.0.0 *slots* + .. versionadded:: 16.1.0 *frozen* + .. versionadded:: 16.3.0 *str* + .. versionadded:: 16.3.0 Support for ``__attrs_post_init__``. + .. versionchanged:: 17.1.0 + *hash* supports `None` as value which is also the default now. + .. versionadded:: 17.3.0 *auto_attribs* + .. versionchanged:: 18.1.0 + If *these* is passed, no attributes are deleted from the class body. + .. versionchanged:: 18.1.0 If *these* is ordered, the order is retained. + .. versionadded:: 18.2.0 *weakref_slot* + .. deprecated:: 18.2.0 + ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now raise a + `DeprecationWarning` if the classes compared are subclasses of + each other. ``__eq`` and ``__ne__`` never tried to compared subclasses + to each other. + .. versionchanged:: 19.2.0 + ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` now do not consider + subclasses comparable anymore. + .. versionadded:: 18.2.0 *kw_only* + .. versionadded:: 18.2.0 *cache_hash* + .. versionadded:: 19.1.0 *auto_exc* + .. deprecated:: 19.2.0 *cmp* Removal on or after 2021-06-01. + .. versionadded:: 19.2.0 *eq* and *order* + .. versionadded:: 20.1.0 *auto_detect* + .. versionadded:: 20.1.0 *collect_by_mro* + .. versionadded:: 20.1.0 *getstate_setstate* + .. versionadded:: 20.1.0 *on_setattr* + .. versionadded:: 20.3.0 *field_transformer* + .. versionchanged:: 21.1.0 + ``init=False`` injects ``__attrs_init__`` + .. versionchanged:: 21.1.0 Support for ``__attrs_pre_init__`` + .. versionchanged:: 21.1.0 *cmp* undeprecated + .. versionadded:: 21.3.0 *match_args* + .. versionadded:: 22.2.0 + *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance). + .. deprecated:: 24.1.0 *repr_ns* + .. versionchanged:: 24.1.0 + Instances are not compared as tuples of attributes anymore, but using a + big ``and`` condition. This is faster and has more correct behavior for + uncomparable values like `math.nan`. + .. versionadded:: 24.1.0 + If a class has an *inherited* classmethod called + ``__attrs_init_subclass__``, it is executed after the class is created. + .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*. + """ + if repr_ns is not None: + import warnings + + warnings.warn( + DeprecationWarning( + "The `repr_ns` argument is deprecated and will be removed in or after August 2025." + ), + stacklevel=2, + ) + + eq_, order_ = _determine_attrs_eq_order(cmp, eq, order, None) + + # unsafe_hash takes precedence due to PEP 681. + if unsafe_hash is not None: + hash = unsafe_hash + + if isinstance(on_setattr, (list, tuple)): + on_setattr = setters.pipe(*on_setattr) + + def wrap(cls): + is_frozen = frozen or _has_frozen_base_class(cls) + is_exc = auto_exc is True and issubclass(cls, BaseException) + has_own_setattr = auto_detect and _has_own_attribute( + cls, "__setattr__" + ) + + if has_own_setattr and is_frozen: + msg = "Can't freeze a class with a custom __setattr__." + raise ValueError(msg) + + builder = _ClassBuilder( + cls, + these, + slots, + is_frozen, + weakref_slot, + _determine_whether_to_implement( + cls, + getstate_setstate, + auto_detect, + ("__getstate__", "__setstate__"), + default=slots, + ), + auto_attribs, + kw_only, + cache_hash, + is_exc, + collect_by_mro, + on_setattr, + has_own_setattr, + field_transformer, + ) + + if _determine_whether_to_implement( + cls, repr, auto_detect, ("__repr__",) + ): + builder.add_repr(repr_ns) + + if str is True: + builder.add_str() + + eq = _determine_whether_to_implement( + cls, eq_, auto_detect, ("__eq__", "__ne__") + ) + if not is_exc and eq is True: + builder.add_eq() + if not is_exc and _determine_whether_to_implement( + cls, order_, auto_detect, ("__lt__", "__le__", "__gt__", "__ge__") + ): + builder.add_order() + + if not frozen: + builder.add_setattr() + + nonlocal hash + if ( + hash is None + and auto_detect is True + and _has_own_attribute(cls, "__hash__") + ): + hash = False + + if hash is not True and hash is not False and hash is not None: + # Can't use `hash in` because 1 == True for example. + msg = "Invalid value for hash. Must be True, False, or None." + raise TypeError(msg) + + if hash is False or (hash is None and eq is False) or is_exc: + # Don't do anything. Should fall back to __object__'s __hash__ + # which is by id. + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled." + raise TypeError(msg) + elif hash is True or ( + hash is None and eq is True and is_frozen is True + ): + # Build a __hash__ if told so, or if it's safe. + builder.add_hash() + else: + # Raise TypeError on attempts to hash. + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, hashing must be either explicitly or implicitly enabled." + raise TypeError(msg) + builder.make_unhashable() + + if _determine_whether_to_implement( + cls, init, auto_detect, ("__init__",) + ): + builder.add_init() + else: + builder.add_attrs_init() + if cache_hash: + msg = "Invalid value for cache_hash. To use hash caching, init must be True." + raise TypeError(msg) + + if PY_3_13_PLUS and not _has_own_attribute(cls, "__replace__"): + builder.add_replace() + + if ( + PY_3_10_PLUS + and match_args + and not _has_own_attribute(cls, "__match_args__") + ): + builder.add_match_args() + + return builder.build_class() + + # maybe_cls's type depends on the usage of the decorator. It's a class + # if it's used as `@attrs` but `None` if used as `@attrs()`. + if maybe_cls is None: + return wrap + + return wrap(maybe_cls) + + +_attrs = attrs +""" +Internal alias so we can use it in functions that take an argument called +*attrs*. +""" + + +def _has_frozen_base_class(cls): + """ + Check whether *cls* has a frozen ancestor by looking at its + __setattr__. + """ + return cls.__setattr__ is _frozen_setattrs + + +def _generate_unique_filename(cls: type, func_name: str) -> str: + """ + Create a "filename" suitable for a function being generated. + """ + return ( + f"" + ) + + +def _make_hash_script( + cls: type, attrs: list[Attribute], frozen: bool, cache_hash: bool +) -> tuple[str, dict]: + attrs = tuple( + a for a in attrs if a.hash is True or (a.hash is None and a.eq is True) + ) + + tab = " " + + type_hash = hash(_generate_unique_filename(cls, "hash")) + # If eq is custom generated, we need to include the functions in globs + globs = {} + + hash_def = "def __hash__(self" + hash_func = "hash((" + closing_braces = "))" + if not cache_hash: + hash_def += "):" + else: + hash_def += ", *" + + hash_def += ", _cache_wrapper=__import__('attr._make')._make._CacheHashWrapper):" + hash_func = "_cache_wrapper(" + hash_func + closing_braces += ")" + + method_lines = [hash_def] + + def append_hash_computation_lines(prefix, indent): + """ + Generate the code for actually computing the hash code. + Below this will either be returned directly or used to compute + a value which is then cached, depending on the value of cache_hash + """ + + method_lines.extend( + [ + indent + prefix + hash_func, + indent + f" {type_hash},", + ] + ) + + for a in attrs: + if a.eq_key: + cmp_name = f"_{a.name}_key" + globs[cmp_name] = a.eq_key + method_lines.append( + indent + f" {cmp_name}(self.{a.name})," + ) + else: + method_lines.append(indent + f" self.{a.name},") + + method_lines.append(indent + " " + closing_braces) + + if cache_hash: + method_lines.append(tab + f"if self.{_HASH_CACHE_FIELD} is None:") + if frozen: + append_hash_computation_lines( + f"object.__setattr__(self, '{_HASH_CACHE_FIELD}', ", tab * 2 + ) + method_lines.append(tab * 2 + ")") # close __setattr__ + else: + append_hash_computation_lines( + f"self.{_HASH_CACHE_FIELD} = ", tab * 2 + ) + method_lines.append(tab + f"return self.{_HASH_CACHE_FIELD}") + else: + append_hash_computation_lines("return ", tab) + + script = "\n".join(method_lines) + return script, globs + + +def _add_hash(cls: type, attrs: list[Attribute]): + """ + Add a hash method to *cls*. + """ + script, globs = _make_hash_script( + cls, attrs, frozen=False, cache_hash=False + ) + _compile_and_eval( + script, globs, filename=_generate_unique_filename(cls, "__hash__") + ) + cls.__hash__ = globs["__hash__"] + return cls + + +def __ne__(self, other): + """ + Check equality and either forward a NotImplemented or + return the result negated. + """ + result = self.__eq__(other) + if result is NotImplemented: + return NotImplemented + + return not result + + +def _make_eq_script(attrs: list) -> tuple[str, dict]: + """ + Create __eq__ method for *cls* with *attrs*. + """ + attrs = [a for a in attrs if a.eq] + + lines = [ + "def __eq__(self, other):", + " if other.__class__ is not self.__class__:", + " return NotImplemented", + ] + + globs = {} + if attrs: + lines.append(" return (") + for a in attrs: + if a.eq_key: + cmp_name = f"_{a.name}_key" + # Add the key function to the global namespace + # of the evaluated function. + globs[cmp_name] = a.eq_key + lines.append( + f" {cmp_name}(self.{a.name}) == {cmp_name}(other.{a.name})" + ) + else: + lines.append(f" self.{a.name} == other.{a.name}") + if a is not attrs[-1]: + lines[-1] = f"{lines[-1]} and" + lines.append(" )") + else: + lines.append(" return True") + + script = "\n".join(lines) + + return script, globs + + +def _make_order(cls, attrs): + """ + Create ordering methods for *cls* with *attrs*. + """ + attrs = [a for a in attrs if a.order] + + def attrs_to_tuple(obj): + """ + Save us some typing. + """ + return tuple( + key(value) if key else value + for value, key in ( + (getattr(obj, a.name), a.order_key) for a in attrs + ) + ) + + def __lt__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) < attrs_to_tuple(other) + + return NotImplemented + + def __le__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) <= attrs_to_tuple(other) + + return NotImplemented + + def __gt__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) > attrs_to_tuple(other) + + return NotImplemented + + def __ge__(self, other): + """ + Automatically created by attrs. + """ + if other.__class__ is self.__class__: + return attrs_to_tuple(self) >= attrs_to_tuple(other) + + return NotImplemented + + return __lt__, __le__, __gt__, __ge__ + + +def _add_eq(cls, attrs=None): + """ + Add equality methods to *cls* with *attrs*. + """ + if attrs is None: + attrs = cls.__attrs_attrs__ + + script, globs = _make_eq_script(attrs) + _compile_and_eval( + script, globs, filename=_generate_unique_filename(cls, "__eq__") + ) + cls.__eq__ = globs["__eq__"] + cls.__ne__ = __ne__ + + return cls + + +def _make_repr_script(attrs, ns) -> tuple[str, dict]: + """ + Create the source and globs for a __repr__ and return it. + """ + # Figure out which attributes to include, and which function to use to + # format them. The a.repr value can be either bool or a custom + # callable. + attr_names_with_reprs = tuple( + (a.name, (repr if a.repr is True else a.repr), a.init) + for a in attrs + if a.repr is not False + ) + globs = { + name + "_repr": r for name, r, _ in attr_names_with_reprs if r != repr + } + globs["_compat"] = _compat + globs["AttributeError"] = AttributeError + globs["NOTHING"] = NOTHING + attribute_fragments = [] + for name, r, i in attr_names_with_reprs: + accessor = ( + "self." + name if i else 'getattr(self, "' + name + '", NOTHING)' + ) + fragment = ( + "%s={%s!r}" % (name, accessor) + if r == repr + else "%s={%s_repr(%s)}" % (name, name, accessor) + ) + attribute_fragments.append(fragment) + repr_fragment = ", ".join(attribute_fragments) + + if ns is None: + cls_name_fragment = '{self.__class__.__qualname__.rsplit(">.", 1)[-1]}' + else: + cls_name_fragment = ns + ".{self.__class__.__name__}" + + lines = [ + "def __repr__(self):", + " try:", + " already_repring = _compat.repr_context.already_repring", + " except AttributeError:", + " already_repring = {id(self),}", + " _compat.repr_context.already_repring = already_repring", + " else:", + " if id(self) in already_repring:", + " return '...'", + " else:", + " already_repring.add(id(self))", + " try:", + f" return f'{cls_name_fragment}({repr_fragment})'", + " finally:", + " already_repring.remove(id(self))", + ] + + return "\n".join(lines), globs + + +def _add_repr(cls, ns=None, attrs=None): + """ + Add a repr method to *cls*. + """ + if attrs is None: + attrs = cls.__attrs_attrs__ + + script, globs = _make_repr_script(attrs, ns) + _compile_and_eval( + script, globs, filename=_generate_unique_filename(cls, "__repr__") + ) + cls.__repr__ = globs["__repr__"] + return cls + + +def fields(cls): + """ + Return the tuple of *attrs* attributes for a class. + + The tuple also allows accessing the fields by their names (see below for + examples). + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + Returns: + tuple (with name accessors) of `attrs.Attribute` + + .. versionchanged:: 16.2.0 Returned tuple allows accessing the fields + by name. + .. versionchanged:: 23.1.0 Add support for generic classes. + """ + generic_base = get_generic_base(cls) + + if generic_base is None and not isinstance(cls, type): + msg = "Passed object must be a class." + raise TypeError(msg) + + attrs = getattr(cls, "__attrs_attrs__", None) + + if attrs is None: + if generic_base is not None: + attrs = getattr(generic_base, "__attrs_attrs__", None) + if attrs is not None: + # Even though this is global state, stick it on here to speed + # it up. We rely on `cls` being cached for this to be + # efficient. + cls.__attrs_attrs__ = attrs + return attrs + msg = f"{cls!r} is not an attrs-decorated class." + raise NotAnAttrsClassError(msg) + + return attrs + + +def fields_dict(cls): + """ + Return an ordered dictionary of *attrs* attributes for a class, whose keys + are the attribute names. + + Args: + cls (type): Class to introspect. + + Raises: + TypeError: If *cls* is not a class. + + attrs.exceptions.NotAnAttrsClassError: + If *cls* is not an *attrs* class. + + Returns: + dict[str, attrs.Attribute]: Dict of attribute name to definition + + .. versionadded:: 18.1.0 + """ + if not isinstance(cls, type): + msg = "Passed object must be a class." + raise TypeError(msg) + attrs = getattr(cls, "__attrs_attrs__", None) + if attrs is None: + msg = f"{cls!r} is not an attrs-decorated class." + raise NotAnAttrsClassError(msg) + return {a.name: a for a in attrs} + + +def validate(inst): + """ + Validate all attributes on *inst* that have a validator. + + Leaves all exceptions through. + + Args: + inst: Instance of a class with *attrs* attributes. + """ + if _config._run_validators is False: + return + + for a in fields(inst.__class__): + v = a.validator + if v is not None: + v(inst, a, getattr(inst, a.name)) + + +def _is_slot_attr(a_name, base_attr_map): + """ + Check if the attribute name comes from a slot class. + """ + cls = base_attr_map.get(a_name) + return cls and "__slots__" in cls.__dict__ + + +def _make_init_script( + cls, + attrs, + pre_init, + pre_init_has_args, + post_init, + frozen, + slots, + cache_hash, + base_attr_map, + is_exc, + cls_on_setattr, + attrs_init, +) -> tuple[str, dict, dict]: + has_cls_on_setattr = ( + cls_on_setattr is not None and cls_on_setattr is not setters.NO_OP + ) + + if frozen and has_cls_on_setattr: + msg = "Frozen classes can't use on_setattr." + raise ValueError(msg) + + needs_cached_setattr = cache_hash or frozen + filtered_attrs = [] + attr_dict = {} + for a in attrs: + if not a.init and a.default is NOTHING: + continue + + filtered_attrs.append(a) + attr_dict[a.name] = a + + if a.on_setattr is not None: + if frozen is True: + msg = "Frozen classes can't use on_setattr." + raise ValueError(msg) + + needs_cached_setattr = True + elif has_cls_on_setattr and a.on_setattr is not setters.NO_OP: + needs_cached_setattr = True + + script, globs, annotations = _attrs_to_init_script( + filtered_attrs, + frozen, + slots, + pre_init, + pre_init_has_args, + post_init, + cache_hash, + base_attr_map, + is_exc, + needs_cached_setattr, + has_cls_on_setattr, + "__attrs_init__" if attrs_init else "__init__", + ) + if cls.__module__ in sys.modules: + # This makes typing.get_type_hints(CLS.__init__) resolve string types. + globs.update(sys.modules[cls.__module__].__dict__) + + globs.update({"NOTHING": NOTHING, "attr_dict": attr_dict}) + + if needs_cached_setattr: + # Save the lookup overhead in __init__ if we need to circumvent + # setattr hooks. + globs["_cached_setattr_get"] = _OBJ_SETATTR.__get__ + + return script, globs, annotations + + +def _setattr(attr_name: str, value_var: str, has_on_setattr: bool) -> str: + """ + Use the cached object.setattr to set *attr_name* to *value_var*. + """ + return f"_setattr('{attr_name}', {value_var})" + + +def _setattr_with_converter( + attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter +) -> str: + """ + Use the cached object.setattr to set *attr_name* to *value_var*, but run + its converter first. + """ + return f"_setattr('{attr_name}', {converter._fmt_converter_call(attr_name, value_var)})" + + +def _assign(attr_name: str, value: str, has_on_setattr: bool) -> str: + """ + Unless *attr_name* has an on_setattr hook, use normal assignment. Otherwise + relegate to _setattr. + """ + if has_on_setattr: + return _setattr(attr_name, value, True) + + return f"self.{attr_name} = {value}" + + +def _assign_with_converter( + attr_name: str, value_var: str, has_on_setattr: bool, converter: Converter +) -> str: + """ + Unless *attr_name* has an on_setattr hook, use normal assignment after + conversion. Otherwise relegate to _setattr_with_converter. + """ + if has_on_setattr: + return _setattr_with_converter(attr_name, value_var, True, converter) + + return f"self.{attr_name} = {converter._fmt_converter_call(attr_name, value_var)}" + + +def _determine_setters( + frozen: bool, slots: bool, base_attr_map: dict[str, type] +): + """ + Determine the correct setter functions based on whether a class is frozen + and/or slotted. + """ + if frozen is True: + if slots is True: + return (), _setattr, _setattr_with_converter + + # Dict frozen classes assign directly to __dict__. + # But only if the attribute doesn't come from an ancestor slot + # class. + # Note _inst_dict will be used again below if cache_hash is True + + def fmt_setter( + attr_name: str, value_var: str, has_on_setattr: bool + ) -> str: + if _is_slot_attr(attr_name, base_attr_map): + return _setattr(attr_name, value_var, has_on_setattr) + + return f"_inst_dict['{attr_name}'] = {value_var}" + + def fmt_setter_with_converter( + attr_name: str, + value_var: str, + has_on_setattr: bool, + converter: Converter, + ) -> str: + if has_on_setattr or _is_slot_attr(attr_name, base_attr_map): + return _setattr_with_converter( + attr_name, value_var, has_on_setattr, converter + ) + + return f"_inst_dict['{attr_name}'] = {converter._fmt_converter_call(attr_name, value_var)}" + + return ( + ("_inst_dict = self.__dict__",), + fmt_setter, + fmt_setter_with_converter, + ) + + # Not frozen -- we can just assign directly. + return (), _assign, _assign_with_converter + + +def _attrs_to_init_script( + attrs: list[Attribute], + is_frozen: bool, + is_slotted: bool, + call_pre_init: bool, + pre_init_has_args: bool, + call_post_init: bool, + does_cache_hash: bool, + base_attr_map: dict[str, type], + is_exc: bool, + needs_cached_setattr: bool, + has_cls_on_setattr: bool, + method_name: str, +) -> tuple[str, dict, dict]: + """ + Return a script of an initializer for *attrs*, a dict of globals, and + annotations for the initializer. + + The globals are required by the generated script. + """ + lines = ["self.__attrs_pre_init__()"] if call_pre_init else [] + + if needs_cached_setattr: + lines.append( + # Circumvent the __setattr__ descriptor to save one lookup per + # assignment. Note _setattr will be used again below if + # does_cache_hash is True. + "_setattr = _cached_setattr_get(self)" + ) + + extra_lines, fmt_setter, fmt_setter_with_converter = _determine_setters( + is_frozen, is_slotted, base_attr_map + ) + lines.extend(extra_lines) + + args = [] + kw_only_args = [] + attrs_to_validate = [] + + # This is a dictionary of names to validator and converter callables. + # Injecting this into __init__ globals lets us avoid lookups. + names_for_globals = {} + annotations = {"return": None} + + for a in attrs: + if a.validator: + attrs_to_validate.append(a) + + attr_name = a.name + has_on_setattr = a.on_setattr is not None or ( + a.on_setattr is not setters.NO_OP and has_cls_on_setattr + ) + # a.alias is set to maybe-mangled attr_name in _ClassBuilder if not + # explicitly provided + arg_name = a.alias + + has_factory = isinstance(a.default, Factory) + maybe_self = "self" if has_factory and a.default.takes_self else "" + + if a.converter is not None and not isinstance(a.converter, Converter): + converter = Converter(a.converter) + else: + converter = a.converter + + if a.init is False: + if has_factory: + init_factory_name = _INIT_FACTORY_PAT % (a.name,) + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, + init_factory_name + f"({maybe_self})", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + fmt_setter( + attr_name, + init_factory_name + f"({maybe_self})", + has_on_setattr, + ) + ) + names_for_globals[init_factory_name] = a.default.factory + elif converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, + f"attr_dict['{attr_name}'].default", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + fmt_setter( + attr_name, + f"attr_dict['{attr_name}'].default", + has_on_setattr, + ) + ) + elif a.default is not NOTHING and not has_factory: + arg = f"{arg_name}=attr_dict['{attr_name}'].default" + if a.kw_only: + kw_only_args.append(arg) + else: + args.append(arg) + + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) + + elif has_factory: + arg = f"{arg_name}=NOTHING" + if a.kw_only: + kw_only_args.append(arg) + else: + args.append(arg) + lines.append(f"if {arg_name} is not NOTHING:") + + init_factory_name = _INIT_FACTORY_PAT % (a.name,) + if converter is not None: + lines.append( + " " + + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + lines.append("else:") + lines.append( + " " + + fmt_setter_with_converter( + attr_name, + init_factory_name + "(" + maybe_self + ")", + has_on_setattr, + converter, + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append( + " " + fmt_setter(attr_name, arg_name, has_on_setattr) + ) + lines.append("else:") + lines.append( + " " + + fmt_setter( + attr_name, + init_factory_name + "(" + maybe_self + ")", + has_on_setattr, + ) + ) + names_for_globals[init_factory_name] = a.default.factory + else: + if a.kw_only: + kw_only_args.append(arg_name) + else: + args.append(arg_name) + + if converter is not None: + lines.append( + fmt_setter_with_converter( + attr_name, arg_name, has_on_setattr, converter + ) + ) + names_for_globals[converter._get_global_name(a.name)] = ( + converter.converter + ) + else: + lines.append(fmt_setter(attr_name, arg_name, has_on_setattr)) + + if a.init is True: + if a.type is not None and converter is None: + annotations[arg_name] = a.type + elif converter is not None and converter._first_param_type: + # Use the type from the converter if present. + annotations[arg_name] = converter._first_param_type + + if attrs_to_validate: # we can skip this if there are no validators. + names_for_globals["_config"] = _config + lines.append("if _config._run_validators is True:") + for a in attrs_to_validate: + val_name = "__attr_validator_" + a.name + attr_name = "__attr_" + a.name + lines.append(f" {val_name}(self, {attr_name}, self.{a.name})") + names_for_globals[val_name] = a.validator + names_for_globals[attr_name] = a + + if call_post_init: + lines.append("self.__attrs_post_init__()") + + # Because this is set only after __attrs_post_init__ is called, a crash + # will result if post-init tries to access the hash code. This seemed + # preferable to setting this beforehand, in which case alteration to field + # values during post-init combined with post-init accessing the hash code + # would result in silent bugs. + if does_cache_hash: + if is_frozen: + if is_slotted: + init_hash_cache = f"_setattr('{_HASH_CACHE_FIELD}', None)" + else: + init_hash_cache = f"_inst_dict['{_HASH_CACHE_FIELD}'] = None" + else: + init_hash_cache = f"self.{_HASH_CACHE_FIELD} = None" + lines.append(init_hash_cache) + + # For exceptions we rely on BaseException.__init__ for proper + # initialization. + if is_exc: + vals = ",".join(f"self.{a.name}" for a in attrs if a.init) + + lines.append(f"BaseException.__init__(self, {vals})") + + args = ", ".join(args) + pre_init_args = args + if kw_only_args: + # leading comma & kw_only args + args += f"{', ' if args else ''}*, {', '.join(kw_only_args)}" + pre_init_kw_only_args = ", ".join( + [ + f"{kw_arg_name}={kw_arg_name}" + # We need to remove the defaults from the kw_only_args. + for kw_arg_name in (kwa.split("=")[0] for kwa in kw_only_args) + ] + ) + pre_init_args += ", " if pre_init_args else "" + pre_init_args += pre_init_kw_only_args + + if call_pre_init and pre_init_has_args: + # If pre init method has arguments, pass same arguments as `__init__`. + lines[0] = f"self.__attrs_pre_init__({pre_init_args})" + + # Python <3.12 doesn't allow backslashes in f-strings. + NL = "\n " + return ( + f"""def {method_name}(self, {args}): + {NL.join(lines) if lines else "pass"} +""", + names_for_globals, + annotations, + ) + + +def _default_init_alias_for(name: str) -> str: + """ + The default __init__ parameter name for a field. + + This performs private-name adjustment via leading-unscore stripping, + and is the default value of Attribute.alias if not provided. + """ + + return name.lstrip("_") + + +class Attribute: + """ + *Read-only* representation of an attribute. + + .. warning:: + + You should never instantiate this class yourself. + + The class has *all* arguments of `attr.ib` (except for ``factory`` which is + only syntactic sugar for ``default=Factory(...)`` plus the following: + + - ``name`` (`str`): The name of the attribute. + - ``alias`` (`str`): The __init__ parameter name of the attribute, after + any explicit overrides and default private-attribute-name handling. + - ``inherited`` (`bool`): Whether or not that attribute has been inherited + from a base class. + - ``eq_key`` and ``order_key`` (`typing.Callable` or `None`): The + callables that are used for comparing and ordering objects by this + attribute, respectively. These are set by passing a callable to + `attr.ib`'s ``eq``, ``order``, or ``cmp`` arguments. See also + :ref:`comparison customization `. + + Instances of this class are frequently used for introspection purposes + like: + + - `fields` returns a tuple of them. + - Validators get them passed as the first argument. + - The :ref:`field transformer ` hook receives a list of + them. + - The ``alias`` property exposes the __init__ parameter name of the field, + with any overrides and default private-attribute handling applied. + + + .. versionadded:: 20.1.0 *inherited* + .. versionadded:: 20.1.0 *on_setattr* + .. versionchanged:: 20.2.0 *inherited* is not taken into account for + equality checks and hashing anymore. + .. versionadded:: 21.1.0 *eq_key* and *order_key* + .. versionadded:: 22.2.0 *alias* + + For the full version history of the fields, see `attr.ib`. + """ + + # These slots must NOT be reordered because we use them later for + # instantiation. + __slots__ = ( # noqa: RUF023 + "name", + "default", + "validator", + "repr", + "eq", + "eq_key", + "order", + "order_key", + "hash", + "init", + "metadata", + "type", + "converter", + "kw_only", + "inherited", + "on_setattr", + "alias", + ) + + def __init__( + self, + name, + default, + validator, + repr, + cmp, # XXX: unused, remove along with other cmp code. + hash, + init, + inherited, + metadata=None, + type=None, + converter=None, + kw_only=False, + eq=None, + eq_key=None, + order=None, + order_key=None, + on_setattr=None, + alias=None, + ): + eq, eq_key, order, order_key = _determine_attrib_eq_order( + cmp, eq_key or eq, order_key or order, True + ) + + # Cache this descriptor here to speed things up later. + bound_setattr = _OBJ_SETATTR.__get__(self) + + # Despite the big red warning, people *do* instantiate `Attribute` + # themselves. + bound_setattr("name", name) + bound_setattr("default", default) + bound_setattr("validator", validator) + bound_setattr("repr", repr) + bound_setattr("eq", eq) + bound_setattr("eq_key", eq_key) + bound_setattr("order", order) + bound_setattr("order_key", order_key) + bound_setattr("hash", hash) + bound_setattr("init", init) + bound_setattr("converter", converter) + bound_setattr( + "metadata", + ( + types.MappingProxyType(dict(metadata)) # Shallow copy + if metadata + else _EMPTY_METADATA_SINGLETON + ), + ) + bound_setattr("type", type) + bound_setattr("kw_only", kw_only) + bound_setattr("inherited", inherited) + bound_setattr("on_setattr", on_setattr) + bound_setattr("alias", alias) + + def __setattr__(self, name, value): + raise FrozenInstanceError + + @classmethod + def from_counting_attr(cls, name: str, ca: _CountingAttr, type=None): + # type holds the annotated value. deal with conflicts: + if type is None: + type = ca.type + elif ca.type is not None: + msg = f"Type annotation and type argument cannot both be present for '{name}'." + raise ValueError(msg) + return cls( + name, + ca._default, + ca._validator, + ca.repr, + None, + ca.hash, + ca.init, + False, + ca.metadata, + type, + ca.converter, + ca.kw_only, + ca.eq, + ca.eq_key, + ca.order, + ca.order_key, + ca.on_setattr, + ca.alias, + ) + + # Don't use attrs.evolve since fields(Attribute) doesn't work + def evolve(self, **changes): + """ + Copy *self* and apply *changes*. + + This works similarly to `attrs.evolve` but that function does not work + with :class:`attrs.Attribute`. + + It is mainly meant to be used for `transform-fields`. + + .. versionadded:: 20.3.0 + """ + new = copy.copy(self) + + new._setattrs(changes.items()) + + return new + + # Don't use _add_pickle since fields(Attribute) doesn't work + def __getstate__(self): + """ + Play nice with pickle. + """ + return tuple( + getattr(self, name) if name != "metadata" else dict(self.metadata) + for name in self.__slots__ + ) + + def __setstate__(self, state): + """ + Play nice with pickle. + """ + self._setattrs(zip(self.__slots__, state)) + + def _setattrs(self, name_values_pairs): + bound_setattr = _OBJ_SETATTR.__get__(self) + for name, value in name_values_pairs: + if name != "metadata": + bound_setattr(name, value) + else: + bound_setattr( + name, + ( + types.MappingProxyType(dict(value)) + if value + else _EMPTY_METADATA_SINGLETON + ), + ) + + +_a = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=(name != "metadata"), + init=True, + inherited=False, + alias=_default_init_alias_for(name), + ) + for name in Attribute.__slots__ +] + +Attribute = _add_hash( + _add_eq( + _add_repr(Attribute, attrs=_a), + attrs=[a for a in _a if a.name != "inherited"], + ), + attrs=[a for a in _a if a.hash and a.name != "inherited"], +) + + +class _CountingAttr: + """ + Intermediate representation of attributes that uses a counter to preserve + the order in which the attributes have been defined. + + *Internal* data structure of the attrs library. Running into is most + likely the result of a bug like a forgotten `@attr.s` decorator. + """ + + __slots__ = ( + "_default", + "_validator", + "alias", + "converter", + "counter", + "eq", + "eq_key", + "hash", + "init", + "kw_only", + "metadata", + "on_setattr", + "order", + "order_key", + "repr", + "type", + ) + __attrs_attrs__ = ( + *tuple( + Attribute( + name=name, + alias=_default_init_alias_for(name), + default=NOTHING, + validator=None, + repr=True, + cmp=None, + hash=True, + init=True, + kw_only=False, + eq=True, + eq_key=None, + order=False, + order_key=None, + inherited=False, + on_setattr=None, + ) + for name in ( + "counter", + "_default", + "repr", + "eq", + "order", + "hash", + "init", + "on_setattr", + "alias", + ) + ), + Attribute( + name="metadata", + alias="metadata", + default=None, + validator=None, + repr=True, + cmp=None, + hash=False, + init=True, + kw_only=False, + eq=True, + eq_key=None, + order=False, + order_key=None, + inherited=False, + on_setattr=None, + ), + ) + cls_counter = 0 + + def __init__( + self, + default, + validator, + repr, + cmp, + hash, + init, + converter, + metadata, + type, + kw_only, + eq, + eq_key, + order, + order_key, + on_setattr, + alias, + ): + _CountingAttr.cls_counter += 1 + self.counter = _CountingAttr.cls_counter + self._default = default + self._validator = validator + self.converter = converter + self.repr = repr + self.eq = eq + self.eq_key = eq_key + self.order = order + self.order_key = order_key + self.hash = hash + self.init = init + self.metadata = metadata + self.type = type + self.kw_only = kw_only + self.on_setattr = on_setattr + self.alias = alias + + def validator(self, meth): + """ + Decorator that adds *meth* to the list of validators. + + Returns *meth* unchanged. + + .. versionadded:: 17.1.0 + """ + if self._validator is None: + self._validator = meth + else: + self._validator = and_(self._validator, meth) + return meth + + def default(self, meth): + """ + Decorator that allows to set the default for an attribute. + + Returns *meth* unchanged. + + Raises: + DefaultAlreadySetError: If default has been set before. + + .. versionadded:: 17.1.0 + """ + if self._default is not NOTHING: + raise DefaultAlreadySetError + + self._default = Factory(meth, takes_self=True) + + return meth + + +_CountingAttr = _add_eq(_add_repr(_CountingAttr)) + + +class Factory: + """ + Stores a factory callable. + + If passed as the default value to `attrs.field`, the factory is used to + generate a new value. + + Args: + factory (typing.Callable): + A callable that takes either none or exactly one mandatory + positional argument depending on *takes_self*. + + takes_self (bool): + Pass the partially initialized instance that is being initialized + as a positional argument. + + .. versionadded:: 17.1.0 *takes_self* + """ + + __slots__ = ("factory", "takes_self") + + def __init__(self, factory, takes_self=False): + self.factory = factory + self.takes_self = takes_self + + def __getstate__(self): + """ + Play nice with pickle. + """ + return tuple(getattr(self, name) for name in self.__slots__) + + def __setstate__(self, state): + """ + Play nice with pickle. + """ + for name, value in zip(self.__slots__, state): + setattr(self, name, value) + + +_f = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=True, + init=True, + inherited=False, + ) + for name in Factory.__slots__ +] + +Factory = _add_hash(_add_eq(_add_repr(Factory, attrs=_f), attrs=_f), attrs=_f) + + +class Converter: + """ + Stores a converter callable. + + Allows for the wrapped converter to take additional arguments. The + arguments are passed in the order they are documented. + + Args: + converter (Callable): A callable that converts the passed value. + + takes_self (bool): + Pass the partially initialized instance that is being initialized + as a positional argument. (default: `False`) + + takes_field (bool): + Pass the field definition (an :class:`Attribute`) into the + converter as a positional argument. (default: `False`) + + .. versionadded:: 24.1.0 + """ + + __slots__ = ( + "__call__", + "_first_param_type", + "_global_name", + "converter", + "takes_field", + "takes_self", + ) + + def __init__(self, converter, *, takes_self=False, takes_field=False): + self.converter = converter + self.takes_self = takes_self + self.takes_field = takes_field + + ex = _AnnotationExtractor(converter) + self._first_param_type = ex.get_first_param_type() + + if not (self.takes_self or self.takes_field): + self.__call__ = lambda value, _, __: self.converter(value) + elif self.takes_self and not self.takes_field: + self.__call__ = lambda value, instance, __: self.converter( + value, instance + ) + elif not self.takes_self and self.takes_field: + self.__call__ = lambda value, __, field: self.converter( + value, field + ) + else: + self.__call__ = lambda value, instance, field: self.converter( + value, instance, field + ) + + rt = ex.get_return_type() + if rt is not None: + self.__call__.__annotations__["return"] = rt + + @staticmethod + def _get_global_name(attr_name: str) -> str: + """ + Return the name that a converter for an attribute name *attr_name* + would have. + """ + return f"__attr_converter_{attr_name}" + + def _fmt_converter_call(self, attr_name: str, value_var: str) -> str: + """ + Return a string that calls the converter for an attribute name + *attr_name* and the value in variable named *value_var* according to + `self.takes_self` and `self.takes_field`. + """ + if not (self.takes_self or self.takes_field): + return f"{self._get_global_name(attr_name)}({value_var})" + + if self.takes_self and self.takes_field: + return f"{self._get_global_name(attr_name)}({value_var}, self, attr_dict['{attr_name}'])" + + if self.takes_self: + return f"{self._get_global_name(attr_name)}({value_var}, self)" + + return f"{self._get_global_name(attr_name)}({value_var}, attr_dict['{attr_name}'])" + + def __getstate__(self): + """ + Return a dict containing only converter and takes_self -- the rest gets + computed when loading. + """ + return { + "converter": self.converter, + "takes_self": self.takes_self, + "takes_field": self.takes_field, + } + + def __setstate__(self, state): + """ + Load instance from state. + """ + self.__init__(**state) + + +_f = [ + Attribute( + name=name, + default=NOTHING, + validator=None, + repr=True, + cmp=None, + eq=True, + order=False, + hash=True, + init=True, + inherited=False, + ) + for name in ("converter", "takes_self", "takes_field") +] + +Converter = _add_hash( + _add_eq(_add_repr(Converter, attrs=_f), attrs=_f), attrs=_f +) + + +def make_class( + name, attrs, bases=(object,), class_body=None, **attributes_arguments +): + r""" + A quick way to create a new class called *name* with *attrs*. + + .. note:: + + ``make_class()`` is a thin wrapper around `attr.s`, not `attrs.define` + which means that it doesn't come with some of the improved defaults. + + For example, if you want the same ``on_setattr`` behavior as in + `attrs.define`, you have to pass the hooks yourself: ``make_class(..., + on_setattr=setters.pipe(setters.convert, setters.validate)`` + + .. warning:: + + It is *your* duty to ensure that the class name and the attribute names + are valid identifiers. ``make_class()`` will *not* validate them for + you. + + Args: + name (str): The name for the new class. + + attrs (list | dict): + A list of names or a dictionary of mappings of names to `attr.ib`\ + s / `attrs.field`\ s. + + The order is deduced from the order of the names or attributes + inside *attrs*. Otherwise the order of the definition of the + attributes is used. + + bases (tuple[type, ...]): Classes that the new class will subclass. + + class_body (dict): + An optional dictionary of class attributes for the new class. + + attributes_arguments: Passed unmodified to `attr.s`. + + Returns: + type: A new class with *attrs*. + + .. versionadded:: 17.1.0 *bases* + .. versionchanged:: 18.1.0 If *attrs* is ordered, the order is retained. + .. versionchanged:: 23.2.0 *class_body* + .. versionchanged:: 25.2.0 Class names can now be unicode. + """ + # Class identifiers are converted into the normal form NFKC while parsing + name = unicodedata.normalize("NFKC", name) + + if isinstance(attrs, dict): + cls_dict = attrs + elif isinstance(attrs, (list, tuple)): + cls_dict = {a: attrib() for a in attrs} + else: + msg = "attrs argument must be a dict or a list." + raise TypeError(msg) + + pre_init = cls_dict.pop("__attrs_pre_init__", None) + post_init = cls_dict.pop("__attrs_post_init__", None) + user_init = cls_dict.pop("__init__", None) + + body = {} + if class_body is not None: + body.update(class_body) + if pre_init is not None: + body["__attrs_pre_init__"] = pre_init + if post_init is not None: + body["__attrs_post_init__"] = post_init + if user_init is not None: + body["__init__"] = user_init + + type_ = types.new_class(name, bases, {}, lambda ns: ns.update(body)) + + # For pickling to work, the __module__ variable needs to be set to the + # frame where the class is created. Bypass this step in environments where + # sys._getframe is not defined (Jython for example) or sys._getframe is not + # defined for arguments greater than 0 (IronPython). + with contextlib.suppress(AttributeError, ValueError): + type_.__module__ = sys._getframe(1).f_globals.get( + "__name__", "__main__" + ) + + # We do it here for proper warnings with meaningful stacklevel. + cmp = attributes_arguments.pop("cmp", None) + ( + attributes_arguments["eq"], + attributes_arguments["order"], + ) = _determine_attrs_eq_order( + cmp, + attributes_arguments.get("eq"), + attributes_arguments.get("order"), + True, + ) + + cls = _attrs(these=cls_dict, **attributes_arguments)(type_) + # Only add type annotations now or "_attrs()" will complain: + cls.__annotations__ = { + k: v.type for k, v in cls_dict.items() if v.type is not None + } + return cls + + +# These are required by within this module so we define them here and merely +# import into .validators / .converters. + + +@attrs(slots=True, unsafe_hash=True) +class _AndValidator: + """ + Compose many validators to a single one. + """ + + _validators = attrib() + + def __call__(self, inst, attr, value): + for v in self._validators: + v(inst, attr, value) + + +def and_(*validators): + """ + A validator that composes multiple validators into one. + + When called on a value, it runs all wrapped validators. + + Args: + validators (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of validators. + + .. versionadded:: 17.1.0 + """ + vals = [] + for validator in validators: + vals.extend( + validator._validators + if isinstance(validator, _AndValidator) + else [validator] + ) + + return _AndValidator(tuple(vals)) + + +def pipe(*converters): + """ + A converter that composes multiple converters into one. + + When called on a value, it runs all wrapped converters, returning the + *last* value. + + Type annotations will be inferred from the wrapped converters', if they + have any. + + converters (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of converters. + + .. versionadded:: 20.1.0 + """ + + return_instance = any(isinstance(c, Converter) for c in converters) + + if return_instance: + + def pipe_converter(val, inst, field): + for c in converters: + val = ( + c(val, inst, field) if isinstance(c, Converter) else c(val) + ) + + return val + + else: + + def pipe_converter(val): + for c in converters: + val = c(val) + + return val + + if not converters: + # If the converter list is empty, pipe_converter is the identity. + A = TypeVar("A") + pipe_converter.__annotations__.update({"val": A, "return": A}) + else: + # Get parameter type from first converter. + t = _AnnotationExtractor(converters[0]).get_first_param_type() + if t: + pipe_converter.__annotations__["val"] = t + + last = converters[-1] + if not PY_3_11_PLUS and isinstance(last, Converter): + last = last.__call__ + + # Get return type from last converter. + rt = _AnnotationExtractor(last).get_return_type() + if rt: + pipe_converter.__annotations__["return"] = rt + + if return_instance: + return Converter(pipe_converter, takes_self=True, takes_field=True) + return pipe_converter diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_next_gen.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_next_gen.py new file mode 100644 index 0000000000000000000000000000000000000000..9290664b2dca9285855a4c4c38bb09ca9e616f69 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_next_gen.py @@ -0,0 +1,623 @@ +# SPDX-License-Identifier: MIT + +""" +These are keyword-only APIs that call `attr.s` and `attr.ib` with different +default values. +""" + +from functools import partial + +from . import setters +from ._funcs import asdict as _asdict +from ._funcs import astuple as _astuple +from ._make import ( + _DEFAULT_ON_SETATTR, + NOTHING, + _frozen_setattrs, + attrib, + attrs, +) +from .exceptions import UnannotatedAttributeError + + +def define( + maybe_cls=None, + *, + these=None, + repr=None, + unsafe_hash=None, + hash=None, + init=None, + slots=True, + frozen=False, + weakref_slot=True, + str=False, + auto_attribs=None, + kw_only=False, + cache_hash=False, + auto_exc=True, + eq=None, + order=False, + auto_detect=True, + getstate_setstate=None, + on_setattr=None, + field_transformer=None, + match_args=True, +): + r""" + A class decorator that adds :term:`dunder methods` according to + :term:`fields ` specified using :doc:`type annotations `, + `field()` calls, or the *these* argument. + + Since *attrs* patches or replaces an existing class, you cannot use + `object.__init_subclass__` with *attrs* classes, because it runs too early. + As a replacement, you can define ``__attrs_init_subclass__`` on your class. + It will be called by *attrs* classes that subclass it after they're + created. See also :ref:`init-subclass`. + + Args: + slots (bool): + Create a :term:`slotted class ` that's more + memory-efficient. Slotted classes are generally superior to the + default dict classes, but have some gotchas you should know about, + so we encourage you to read the :term:`glossary entry `. + + auto_detect (bool): + Instead of setting the *init*, *repr*, *eq*, and *hash* arguments + explicitly, assume they are set to True **unless any** of the + involved methods for one of the arguments is implemented in the + *current* class (meaning, it is *not* inherited from some base + class). + + So, for example by implementing ``__eq__`` on a class yourself, + *attrs* will deduce ``eq=False`` and will create *neither* + ``__eq__`` *nor* ``__ne__`` (but Python classes come with a + sensible ``__ne__`` by default, so it *should* be enough to only + implement ``__eq__`` in most cases). + + Passing True or False` to *init*, *repr*, *eq*, or *hash* + overrides whatever *auto_detect* would determine. + + auto_exc (bool): + If the class subclasses `BaseException` (which implicitly includes + any subclass of any exception), the following happens to behave + like a well-behaved Python exception class: + + - the values for *eq*, *order*, and *hash* are ignored and the + instances compare and hash by the instance's ids [#]_ , + - all attributes that are either passed into ``__init__`` or have a + default value are additionally available as a tuple in the + ``args`` attribute, + - the value of *str* is ignored leaving ``__str__`` to base + classes. + + .. [#] + Note that *attrs* will *not* remove existing implementations of + ``__hash__`` or the equality methods. It just won't add own + ones. + + on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]): + A callable that is run whenever the user attempts to set an + attribute (either by assignment like ``i.x = 42`` or by using + `setattr` like ``setattr(i, "x", 42)``). It receives the same + arguments as validators: the instance, the attribute that is being + modified, and the new value. + + If no exception is raised, the attribute is set to the return value + of the callable. + + If a list of callables is passed, they're automatically wrapped in + an `attrs.setters.pipe`. + + If left None, the default behavior is to run converters and + validators whenever an attribute is set. + + init (bool): + Create a ``__init__`` method that initializes the *attrs* + attributes. Leading underscores are stripped for the argument name, + unless an alias is set on the attribute. + + .. seealso:: + `init` shows advanced ways to customize the generated + ``__init__`` method, including executing code before and after. + + repr(bool): + Create a ``__repr__`` method with a human readable representation + of *attrs* attributes. + + str (bool): + Create a ``__str__`` method that is identical to ``__repr__``. This + is usually not necessary except for `Exception`\ s. + + eq (bool | None): + If True or None (default), add ``__eq__`` and ``__ne__`` methods + that check two instances for equality. + + .. seealso:: + `comparison` describes how to customize the comparison behavior + going as far comparing NumPy arrays. + + order (bool | None): + If True, add ``__lt__``, ``__le__``, ``__gt__``, and ``__ge__`` + methods that behave like *eq* above and allow instances to be + ordered. + + They compare the instances as if they were tuples of their *attrs* + attributes if and only if the types of both classes are + *identical*. + + If `None` mirror value of *eq*. + + .. seealso:: `comparison` + + unsafe_hash (bool | None): + If None (default), the ``__hash__`` method is generated according + how *eq* and *frozen* are set. + + 1. If *both* are True, *attrs* will generate a ``__hash__`` for + you. + 2. If *eq* is True and *frozen* is False, ``__hash__`` will be set + to None, marking it unhashable (which it is). + 3. If *eq* is False, ``__hash__`` will be left untouched meaning + the ``__hash__`` method of the base class will be used. If the + base class is `object`, this means it will fall back to id-based + hashing. + + Although not recommended, you can decide for yourself and force + *attrs* to create one (for example, if the class is immutable even + though you didn't freeze it programmatically) by passing True or + not. Both of these cases are rather special and should be used + carefully. + + .. seealso:: + + - Our documentation on `hashing`, + - Python's documentation on `object.__hash__`, + - and the `GitHub issue that led to the default \ behavior + `_ for more + details. + + hash (bool | None): + Deprecated alias for *unsafe_hash*. *unsafe_hash* takes precedence. + + cache_hash (bool): + Ensure that the object's hash code is computed only once and stored + on the object. If this is set to True, hashing must be either + explicitly or implicitly enabled for this class. If the hash code + is cached, avoid any reassignments of fields involved in hash code + computation or mutations of the objects those fields point to after + object creation. If such changes occur, the behavior of the + object's hash code is undefined. + + frozen (bool): + Make instances immutable after initialization. If someone attempts + to modify a frozen instance, `attrs.exceptions.FrozenInstanceError` + is raised. + + .. note:: + + 1. This is achieved by installing a custom ``__setattr__`` + method on your class, so you can't implement your own. + + 2. True immutability is impossible in Python. + + 3. This *does* have a minor a runtime performance `impact + ` when initializing new instances. In other + words: ``__init__`` is slightly slower with ``frozen=True``. + + 4. If a class is frozen, you cannot modify ``self`` in + ``__attrs_post_init__`` or a self-written ``__init__``. You + can circumvent that limitation by using + ``object.__setattr__(self, "attribute_name", value)``. + + 5. Subclasses of a frozen class are frozen too. + + kw_only (bool): + Make all attributes keyword-only in the generated ``__init__`` (if + *init* is False, this parameter is ignored). + + weakref_slot (bool): + Make instances weak-referenceable. This has no effect unless + *slots* is True. + + field_transformer (~typing.Callable | None): + A function that is called with the original class object and all + fields right before *attrs* finalizes the class. You can use this, + for example, to automatically add converters or validators to + fields based on their types. + + .. seealso:: `transform-fields` + + match_args (bool): + If True (default), set ``__match_args__`` on the class to support + :pep:`634` (*Structural Pattern Matching*). It is a tuple of all + non-keyword-only ``__init__`` parameter names on Python 3.10 and + later. Ignored on older Python versions. + + collect_by_mro (bool): + If True, *attrs* collects attributes from base classes correctly + according to the `method resolution order + `_. If False, *attrs* + will mimic the (wrong) behavior of `dataclasses` and :pep:`681`. + + See also `issue #428 + `_. + + getstate_setstate (bool | None): + .. note:: + + This is usually only interesting for slotted classes and you + should probably just set *auto_detect* to True. + + If True, ``__getstate__`` and ``__setstate__`` are generated and + attached to the class. This is necessary for slotted classes to be + pickleable. If left None, it's True by default for slotted classes + and False for dict classes. + + If *auto_detect* is True, and *getstate_setstate* is left None, and + **either** ``__getstate__`` or ``__setstate__`` is detected + directly on the class (meaning: not inherited), it is set to False + (this is usually what you want). + + auto_attribs (bool | None): + If True, look at type annotations to determine which attributes to + use, like `dataclasses`. If False, it will only look for explicit + :func:`field` class attributes, like classic *attrs*. + + If left None, it will guess: + + 1. If any attributes are annotated and no unannotated + `attrs.field`\ s are found, it assumes *auto_attribs=True*. + 2. Otherwise it assumes *auto_attribs=False* and tries to collect + `attrs.field`\ s. + + If *attrs* decides to look at type annotations, **all** fields + **must** be annotated. If *attrs* encounters a field that is set to + a :func:`field` / `attr.ib` but lacks a type annotation, an + `attrs.exceptions.UnannotatedAttributeError` is raised. Use + ``field_name: typing.Any = field(...)`` if you don't want to set a + type. + + .. warning:: + + For features that use the attribute name to create decorators + (for example, :ref:`validators `), you still *must* + assign :func:`field` / `attr.ib` to them. Otherwise Python will + either not find the name or try to use the default value to + call, for example, ``validator`` on it. + + Attributes annotated as `typing.ClassVar`, and attributes that are + neither annotated nor set to an `field()` are **ignored**. + + these (dict[str, object]): + A dictionary of name to the (private) return value of `field()` + mappings. This is useful to avoid the definition of your attributes + within the class body because you can't (for example, if you want + to add ``__repr__`` methods to Django models) or don't want to. + + If *these* is not `None`, *attrs* will *not* search the class body + for attributes and will *not* remove any attributes from it. + + The order is deduced from the order of the attributes inside + *these*. + + Arguably, this is a rather obscure feature. + + .. versionadded:: 20.1.0 + .. versionchanged:: 21.3.0 Converters are also run ``on_setattr``. + .. versionadded:: 22.2.0 + *unsafe_hash* as an alias for *hash* (for :pep:`681` compliance). + .. versionchanged:: 24.1.0 + Instances are not compared as tuples of attributes anymore, but using a + big ``and`` condition. This is faster and has more correct behavior for + uncomparable values like `math.nan`. + .. versionadded:: 24.1.0 + If a class has an *inherited* classmethod called + ``__attrs_init_subclass__``, it is executed after the class is created. + .. deprecated:: 24.1.0 *hash* is deprecated in favor of *unsafe_hash*. + .. versionadded:: 24.3.0 + Unless already present, a ``__replace__`` method is automatically + created for `copy.replace` (Python 3.13+ only). + + .. note:: + + The main differences to the classic `attr.s` are: + + - Automatically detect whether or not *auto_attribs* should be `True` + (c.f. *auto_attribs* parameter). + - Converters and validators run when attributes are set by default -- + if *frozen* is `False`. + - *slots=True* + + Usually, this has only upsides and few visible effects in everyday + programming. But it *can* lead to some surprising behaviors, so + please make sure to read :term:`slotted classes`. + + - *auto_exc=True* + - *auto_detect=True* + - *order=False* + - Some options that were only relevant on Python 2 or were kept around + for backwards-compatibility have been removed. + + """ + + def do_it(cls, auto_attribs): + return attrs( + maybe_cls=cls, + these=these, + repr=repr, + hash=hash, + unsafe_hash=unsafe_hash, + init=init, + slots=slots, + frozen=frozen, + weakref_slot=weakref_slot, + str=str, + auto_attribs=auto_attribs, + kw_only=kw_only, + cache_hash=cache_hash, + auto_exc=auto_exc, + eq=eq, + order=order, + auto_detect=auto_detect, + collect_by_mro=True, + getstate_setstate=getstate_setstate, + on_setattr=on_setattr, + field_transformer=field_transformer, + match_args=match_args, + ) + + def wrap(cls): + """ + Making this a wrapper ensures this code runs during class creation. + + We also ensure that frozen-ness of classes is inherited. + """ + nonlocal frozen, on_setattr + + had_on_setattr = on_setattr not in (None, setters.NO_OP) + + # By default, mutable classes convert & validate on setattr. + if frozen is False and on_setattr is None: + on_setattr = _DEFAULT_ON_SETATTR + + # However, if we subclass a frozen class, we inherit the immutability + # and disable on_setattr. + for base_cls in cls.__bases__: + if base_cls.__setattr__ is _frozen_setattrs: + if had_on_setattr: + msg = "Frozen classes can't use on_setattr (frozen-ness was inherited)." + raise ValueError(msg) + + on_setattr = setters.NO_OP + break + + if auto_attribs is not None: + return do_it(cls, auto_attribs) + + try: + return do_it(cls, True) + except UnannotatedAttributeError: + return do_it(cls, False) + + # maybe_cls's type depends on the usage of the decorator. It's a class + # if it's used as `@attrs` but `None` if used as `@attrs()`. + if maybe_cls is None: + return wrap + + return wrap(maybe_cls) + + +mutable = define +frozen = partial(define, frozen=True, on_setattr=None) + + +def field( + *, + default=NOTHING, + validator=None, + repr=True, + hash=None, + init=True, + metadata=None, + type=None, + converter=None, + factory=None, + kw_only=False, + eq=None, + order=None, + on_setattr=None, + alias=None, +): + """ + Create a new :term:`field` / :term:`attribute` on a class. + + .. warning:: + + Does **nothing** unless the class is also decorated with + `attrs.define` (or similar)! + + Args: + default: + A value that is used if an *attrs*-generated ``__init__`` is used + and no value is passed while instantiating or the attribute is + excluded using ``init=False``. + + If the value is an instance of `attrs.Factory`, its callable will + be used to construct a new value (useful for mutable data types + like lists or dicts). + + If a default is not set (or set manually to `attrs.NOTHING`), a + value *must* be supplied when instantiating; otherwise a + `TypeError` will be raised. + + .. seealso:: `defaults` + + factory (~typing.Callable): + Syntactic sugar for ``default=attr.Factory(factory)``. + + validator (~typing.Callable | list[~typing.Callable]): + Callable that is called by *attrs*-generated ``__init__`` methods + after the instance has been initialized. They receive the + initialized instance, the :func:`~attrs.Attribute`, and the passed + value. + + The return value is *not* inspected so the validator has to throw + an exception itself. + + If a `list` is passed, its items are treated as validators and must + all pass. + + Validators can be globally disabled and re-enabled using + `attrs.validators.get_disabled` / `attrs.validators.set_disabled`. + + The validator can also be set using decorator notation as shown + below. + + .. seealso:: :ref:`validators` + + repr (bool | ~typing.Callable): + Include this attribute in the generated ``__repr__`` method. If + True, include the attribute; if False, omit it. By default, the + built-in ``repr()`` function is used. To override how the attribute + value is formatted, pass a ``callable`` that takes a single value + and returns a string. Note that the resulting string is used as-is, + which means it will be used directly *instead* of calling + ``repr()`` (the default). + + eq (bool | ~typing.Callable): + If True (default), include this attribute in the generated + ``__eq__`` and ``__ne__`` methods that check two instances for + equality. To override how the attribute value is compared, pass a + callable that takes a single value and returns the value to be + compared. + + .. seealso:: `comparison` + + order (bool | ~typing.Callable): + If True (default), include this attributes in the generated + ``__lt__``, ``__le__``, ``__gt__`` and ``__ge__`` methods. To + override how the attribute value is ordered, pass a callable that + takes a single value and returns the value to be ordered. + + .. seealso:: `comparison` + + hash (bool | None): + Include this attribute in the generated ``__hash__`` method. If + None (default), mirror *eq*'s value. This is the correct behavior + according the Python spec. Setting this value to anything else + than None is *discouraged*. + + .. seealso:: `hashing` + + init (bool): + Include this attribute in the generated ``__init__`` method. + + It is possible to set this to False and set a default value. In + that case this attributed is unconditionally initialized with the + specified default value or factory. + + .. seealso:: `init` + + converter (typing.Callable | Converter): + A callable that is called by *attrs*-generated ``__init__`` methods + to convert attribute's value to the desired format. + + If a vanilla callable is passed, it is given the passed-in value as + the only positional argument. It is possible to receive additional + arguments by wrapping the callable in a `Converter`. + + Either way, the returned value will be used as the new value of the + attribute. The value is converted before being passed to the + validator, if any. + + .. seealso:: :ref:`converters` + + metadata (dict | None): + An arbitrary mapping, to be used by third-party code. + + .. seealso:: `extending-metadata`. + + type (type): + The type of the attribute. Nowadays, the preferred method to + specify the type is using a variable annotation (see :pep:`526`). + This argument is provided for backwards-compatibility and for usage + with `make_class`. Regardless of the approach used, the type will + be stored on ``Attribute.type``. + + Please note that *attrs* doesn't do anything with this metadata by + itself. You can use it as part of your own code or for `static type + checking `. + + kw_only (bool): + Make this attribute keyword-only in the generated ``__init__`` (if + ``init`` is False, this parameter is ignored). + + on_setattr (~typing.Callable | list[~typing.Callable] | None | ~typing.Literal[attrs.setters.NO_OP]): + Allows to overwrite the *on_setattr* setting from `attr.s`. If left + None, the *on_setattr* value from `attr.s` is used. Set to + `attrs.setters.NO_OP` to run **no** `setattr` hooks for this + attribute -- regardless of the setting in `define()`. + + alias (str | None): + Override this attribute's parameter name in the generated + ``__init__`` method. If left None, default to ``name`` stripped + of leading underscores. See `private-attributes`. + + .. versionadded:: 20.1.0 + .. versionchanged:: 21.1.0 + *eq*, *order*, and *cmp* also accept a custom callable + .. versionadded:: 22.2.0 *alias* + .. versionadded:: 23.1.0 + The *type* parameter has been re-added; mostly for `attrs.make_class`. + Please note that type checkers ignore this metadata. + + .. seealso:: + + `attr.ib` + """ + return attrib( + default=default, + validator=validator, + repr=repr, + hash=hash, + init=init, + metadata=metadata, + type=type, + converter=converter, + factory=factory, + kw_only=kw_only, + eq=eq, + order=order, + on_setattr=on_setattr, + alias=alias, + ) + + +def asdict(inst, *, recurse=True, filter=None, value_serializer=None): + """ + Same as `attr.asdict`, except that collections types are always retained + and dict is always used as *dict_factory*. + + .. versionadded:: 21.3.0 + """ + return _asdict( + inst=inst, + recurse=recurse, + filter=filter, + value_serializer=value_serializer, + retain_collection_types=True, + ) + + +def astuple(inst, *, recurse=True, filter=None): + """ + Same as `attr.astuple`, except that collections types are always retained + and `tuple` is always used as the *tuple_factory*. + + .. versionadded:: 21.3.0 + """ + return _astuple( + inst=inst, recurse=recurse, filter=filter, retain_collection_types=True + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_typing_compat.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_typing_compat.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ca7b71e906a28f88726bbd342fdfe636af0281e7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_typing_compat.pyi @@ -0,0 +1,15 @@ +from typing import Any, ClassVar, Protocol + +# MYPY is a special constant in mypy which works the same way as `TYPE_CHECKING`. +MYPY = False + +if MYPY: + # A protocol to be able to statically accept an attrs class. + class AttrsInstance_(Protocol): + __attrs_attrs__: ClassVar[Any] + +else: + # For type checkers without plug-in support use an empty protocol that + # will (hopefully) be combined into a union. + class AttrsInstance_(Protocol): + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_version_info.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_version_info.py new file mode 100644 index 0000000000000000000000000000000000000000..51a1312f9759f21063caea779a62882d7f7c86ae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_version_info.py @@ -0,0 +1,86 @@ +# SPDX-License-Identifier: MIT + + +from functools import total_ordering + +from ._funcs import astuple +from ._make import attrib, attrs + + +@total_ordering +@attrs(eq=False, order=False, slots=True, frozen=True) +class VersionInfo: + """ + A version object that can be compared to tuple of length 1--4: + + >>> attr.VersionInfo(19, 1, 0, "final") <= (19, 2) + True + >>> attr.VersionInfo(19, 1, 0, "final") < (19, 1, 1) + True + >>> vi = attr.VersionInfo(19, 2, 0, "final") + >>> vi < (19, 1, 1) + False + >>> vi < (19,) + False + >>> vi == (19, 2,) + True + >>> vi == (19, 2, 1) + False + + .. versionadded:: 19.2 + """ + + year = attrib(type=int) + minor = attrib(type=int) + micro = attrib(type=int) + releaselevel = attrib(type=str) + + @classmethod + def _from_version_string(cls, s): + """ + Parse *s* and return a _VersionInfo. + """ + v = s.split(".") + if len(v) == 3: + v.append("final") + + return cls( + year=int(v[0]), minor=int(v[1]), micro=int(v[2]), releaselevel=v[3] + ) + + def _ensure_tuple(self, other): + """ + Ensure *other* is a tuple of a valid length. + + Returns a possibly transformed *other* and ourselves as a tuple of + the same length as *other*. + """ + + if self.__class__ is other.__class__: + other = astuple(other) + + if not isinstance(other, tuple): + raise NotImplementedError + + if not (1 <= len(other) <= 4): + raise NotImplementedError + + return astuple(self)[: len(other)], other + + def __eq__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + return us == them + + def __lt__(self, other): + try: + us, them = self._ensure_tuple(other) + except NotImplementedError: + return NotImplemented + + # Since alphabetically "dev0" < "final" < "post1" < "post2", we don't + # have to do anything special with releaselevel for now. + return us < them diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_version_info.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_version_info.pyi new file mode 100644 index 0000000000000000000000000000000000000000..45ced086337783c4b73b26cd17d2c1c260e24029 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/_version_info.pyi @@ -0,0 +1,9 @@ +class VersionInfo: + @property + def year(self) -> int: ... + @property + def minor(self) -> int: ... + @property + def micro(self) -> int: ... + @property + def releaselevel(self) -> str: ... diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/converters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/converters.py new file mode 100644 index 0000000000000000000000000000000000000000..0a79deef04282fb33a42f6aca59563d49e70d4cb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/converters.py @@ -0,0 +1,162 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful converters. +""" + +import typing + +from ._compat import _AnnotationExtractor +from ._make import NOTHING, Converter, Factory, pipe + + +__all__ = [ + "default_if_none", + "optional", + "pipe", + "to_bool", +] + + +def optional(converter): + """ + A converter that allows an attribute to be optional. An optional attribute + is one which can be set to `None`. + + Type annotations will be inferred from the wrapped converter's, if it has + any. + + Args: + converter (typing.Callable): + the converter that is used for non-`None` values. + + .. versionadded:: 17.1.0 + """ + + if isinstance(converter, Converter): + + def optional_converter(val, inst, field): + if val is None: + return None + return converter(val, inst, field) + + else: + + def optional_converter(val): + if val is None: + return None + return converter(val) + + xtr = _AnnotationExtractor(converter) + + t = xtr.get_first_param_type() + if t: + optional_converter.__annotations__["val"] = typing.Optional[t] + + rt = xtr.get_return_type() + if rt: + optional_converter.__annotations__["return"] = typing.Optional[rt] + + if isinstance(converter, Converter): + return Converter(optional_converter, takes_self=True, takes_field=True) + + return optional_converter + + +def default_if_none(default=NOTHING, factory=None): + """ + A converter that allows to replace `None` values by *default* or the result + of *factory*. + + Args: + default: + Value to be used if `None` is passed. Passing an instance of + `attrs.Factory` is supported, however the ``takes_self`` option is + *not*. + + factory (typing.Callable): + A callable that takes no parameters whose result is used if `None` + is passed. + + Raises: + TypeError: If **neither** *default* or *factory* is passed. + + TypeError: If **both** *default* and *factory* are passed. + + ValueError: + If an instance of `attrs.Factory` is passed with + ``takes_self=True``. + + .. versionadded:: 18.2.0 + """ + if default is NOTHING and factory is None: + msg = "Must pass either `default` or `factory`." + raise TypeError(msg) + + if default is not NOTHING and factory is not None: + msg = "Must pass either `default` or `factory` but not both." + raise TypeError(msg) + + if factory is not None: + default = Factory(factory) + + if isinstance(default, Factory): + if default.takes_self: + msg = "`takes_self` is not supported by default_if_none." + raise ValueError(msg) + + def default_if_none_converter(val): + if val is not None: + return val + + return default.factory() + + else: + + def default_if_none_converter(val): + if val is not None: + return val + + return default + + return default_if_none_converter + + +def to_bool(val): + """ + Convert "boolean" strings (for example, from environment variables) to real + booleans. + + Values mapping to `True`: + + - ``True`` + - ``"true"`` / ``"t"`` + - ``"yes"`` / ``"y"`` + - ``"on"`` + - ``"1"`` + - ``1`` + + Values mapping to `False`: + + - ``False`` + - ``"false"`` / ``"f"`` + - ``"no"`` / ``"n"`` + - ``"off"`` + - ``"0"`` + - ``0`` + + Raises: + ValueError: For any other value. + + .. versionadded:: 21.3.0 + """ + if isinstance(val, str): + val = val.lower() + + if val in (True, "true", "t", "yes", "y", "on", "1", 1): + return True + if val in (False, "false", "f", "no", "n", "off", "0", 0): + return False + + msg = f"Cannot convert value to bool: {val!r}" + raise ValueError(msg) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/converters.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/converters.pyi new file mode 100644 index 0000000000000000000000000000000000000000..12bd0c4f17bdc60fb8904598af0a3d56d5874a9e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/converters.pyi @@ -0,0 +1,19 @@ +from typing import Callable, Any, overload + +from attrs import _ConverterType, _CallableConverterType + +@overload +def pipe(*validators: _CallableConverterType) -> _CallableConverterType: ... +@overload +def pipe(*validators: _ConverterType) -> _ConverterType: ... +@overload +def optional(converter: _CallableConverterType) -> _CallableConverterType: ... +@overload +def optional(converter: _ConverterType) -> _ConverterType: ... +@overload +def default_if_none(default: Any) -> _CallableConverterType: ... +@overload +def default_if_none( + *, factory: Callable[[], Any] +) -> _CallableConverterType: ... +def to_bool(val: str | int | bool) -> bool: ... diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/exceptions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..3b7abb8154108aa1d0ae52fa9ee8e489f05b5563 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/exceptions.py @@ -0,0 +1,95 @@ +# SPDX-License-Identifier: MIT + +from __future__ import annotations + +from typing import ClassVar + + +class FrozenError(AttributeError): + """ + A frozen/immutable instance or attribute have been attempted to be + modified. + + It mirrors the behavior of ``namedtuples`` by using the same error message + and subclassing `AttributeError`. + + .. versionadded:: 20.1.0 + """ + + msg = "can't set attribute" + args: ClassVar[tuple[str]] = [msg] + + +class FrozenInstanceError(FrozenError): + """ + A frozen instance has been attempted to be modified. + + .. versionadded:: 16.1.0 + """ + + +class FrozenAttributeError(FrozenError): + """ + A frozen attribute has been attempted to be modified. + + .. versionadded:: 20.1.0 + """ + + +class AttrsAttributeNotFoundError(ValueError): + """ + An *attrs* function couldn't find an attribute that the user asked for. + + .. versionadded:: 16.2.0 + """ + + +class NotAnAttrsClassError(ValueError): + """ + A non-*attrs* class has been passed into an *attrs* function. + + .. versionadded:: 16.2.0 + """ + + +class DefaultAlreadySetError(RuntimeError): + """ + A default has been set when defining the field and is attempted to be reset + using the decorator. + + .. versionadded:: 17.1.0 + """ + + +class UnannotatedAttributeError(RuntimeError): + """ + A class with ``auto_attribs=True`` has a field without a type annotation. + + .. versionadded:: 17.3.0 + """ + + +class PythonTooOldError(RuntimeError): + """ + It was attempted to use an *attrs* feature that requires a newer Python + version. + + .. versionadded:: 18.2.0 + """ + + +class NotCallableError(TypeError): + """ + A field requiring a callable has been set with a value that is not + callable. + + .. versionadded:: 19.2.0 + """ + + def __init__(self, msg, value): + super(TypeError, self).__init__(msg, value) + self.msg = msg + self.value = value + + def __str__(self): + return str(self.msg) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/exceptions.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f2680118b404db8f5227d04d27e8439331341c4d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/exceptions.pyi @@ -0,0 +1,17 @@ +from typing import Any + +class FrozenError(AttributeError): + msg: str = ... + +class FrozenInstanceError(FrozenError): ... +class FrozenAttributeError(FrozenError): ... +class AttrsAttributeNotFoundError(ValueError): ... +class NotAnAttrsClassError(ValueError): ... +class DefaultAlreadySetError(RuntimeError): ... +class UnannotatedAttributeError(RuntimeError): ... +class PythonTooOldError(RuntimeError): ... + +class NotCallableError(TypeError): + msg: str = ... + value: Any = ... + def __init__(self, msg: str, value: Any) -> None: ... diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/filters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..689b1705a60ff110d6077bab996f8b4588e55b82 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/filters.py @@ -0,0 +1,72 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful filters for `attrs.asdict` and `attrs.astuple`. +""" + +from ._make import Attribute + + +def _split_what(what): + """ + Returns a tuple of `frozenset`s of classes and attributes. + """ + return ( + frozenset(cls for cls in what if isinstance(cls, type)), + frozenset(cls for cls in what if isinstance(cls, str)), + frozenset(cls for cls in what if isinstance(cls, Attribute)), + ) + + +def include(*what): + """ + Create a filter that only allows *what*. + + Args: + what (list[type, str, attrs.Attribute]): + What to include. Can be a type, a name, or an attribute. + + Returns: + Callable: + A callable that can be passed to `attrs.asdict`'s and + `attrs.astuple`'s *filter* argument. + + .. versionchanged:: 23.1.0 Accept strings with field names. + """ + cls, names, attrs = _split_what(what) + + def include_(attribute, value): + return ( + value.__class__ in cls + or attribute.name in names + or attribute in attrs + ) + + return include_ + + +def exclude(*what): + """ + Create a filter that does **not** allow *what*. + + Args: + what (list[type, str, attrs.Attribute]): + What to exclude. Can be a type, a name, or an attribute. + + Returns: + Callable: + A callable that can be passed to `attrs.asdict`'s and + `attrs.astuple`'s *filter* argument. + + .. versionchanged:: 23.3.0 Accept field name string as input argument + """ + cls, names, attrs = _split_what(what) + + def exclude_(attribute, value): + return not ( + value.__class__ in cls + or attribute.name in names + or attribute in attrs + ) + + return exclude_ diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/filters.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/filters.pyi new file mode 100644 index 0000000000000000000000000000000000000000..974abdcdb51152393d9c9e460c21aa025c45880c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/filters.pyi @@ -0,0 +1,6 @@ +from typing import Any + +from . import Attribute, _FilterType + +def include(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ... +def exclude(*what: type | str | Attribute[Any]) -> _FilterType[Any]: ... diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/py.typed b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/setters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/setters.py new file mode 100644 index 0000000000000000000000000000000000000000..78b08398a6713fc5fa827c2dc853e0d05de743c4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/setters.py @@ -0,0 +1,79 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly used hooks for on_setattr. +""" + +from . import _config +from .exceptions import FrozenAttributeError + + +def pipe(*setters): + """ + Run all *setters* and return the return value of the last one. + + .. versionadded:: 20.1.0 + """ + + def wrapped_pipe(instance, attrib, new_value): + rv = new_value + + for setter in setters: + rv = setter(instance, attrib, rv) + + return rv + + return wrapped_pipe + + +def frozen(_, __, ___): + """ + Prevent an attribute to be modified. + + .. versionadded:: 20.1.0 + """ + raise FrozenAttributeError + + +def validate(instance, attrib, new_value): + """ + Run *attrib*'s validator on *new_value* if it has one. + + .. versionadded:: 20.1.0 + """ + if _config._run_validators is False: + return new_value + + v = attrib.validator + if not v: + return new_value + + v(instance, attrib, new_value) + + return new_value + + +def convert(instance, attrib, new_value): + """ + Run *attrib*'s converter -- if it has one -- on *new_value* and return the + result. + + .. versionadded:: 20.1.0 + """ + c = attrib.converter + if c: + # This can be removed once we drop 3.8 and use attrs.Converter instead. + from ._make import Converter + + if not isinstance(c, Converter): + return c(new_value) + + return c(new_value, instance, attrib) + + return new_value + + +# Sentinel for disabling class-wide *on_setattr* hooks for certain attributes. +# Sphinx's autodata stopped working, so the docstring is inlined in the API +# docs. +NO_OP = object() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/setters.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/setters.pyi new file mode 100644 index 0000000000000000000000000000000000000000..73abf36e7d5b0f5f56e7fddeee716824c1c60d58 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/setters.pyi @@ -0,0 +1,20 @@ +from typing import Any, NewType, NoReturn, TypeVar + +from . import Attribute +from attrs import _OnSetAttrType + +_T = TypeVar("_T") + +def frozen( + instance: Any, attribute: Attribute[Any], new_value: Any +) -> NoReturn: ... +def pipe(*setters: _OnSetAttrType) -> _OnSetAttrType: ... +def validate(instance: Any, attribute: Attribute[_T], new_value: _T) -> _T: ... + +# convert is allowed to return Any, because they can be chained using pipe. +def convert( + instance: Any, attribute: Attribute[Any], new_value: Any +) -> Any: ... + +_NoOpType = NewType("_NoOpType", object) +NO_OP: _NoOpType diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/validators.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..e7b75525022a9d98f8153f17a0fed103b24c743b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/validators.py @@ -0,0 +1,710 @@ +# SPDX-License-Identifier: MIT + +""" +Commonly useful validators. +""" + +import operator +import re + +from contextlib import contextmanager +from re import Pattern + +from ._config import get_run_validators, set_run_validators +from ._make import _AndValidator, and_, attrib, attrs +from .converters import default_if_none +from .exceptions import NotCallableError + + +__all__ = [ + "and_", + "deep_iterable", + "deep_mapping", + "disabled", + "ge", + "get_disabled", + "gt", + "in_", + "instance_of", + "is_callable", + "le", + "lt", + "matches_re", + "max_len", + "min_len", + "not_", + "optional", + "or_", + "set_disabled", +] + + +def set_disabled(disabled): + """ + Globally disable or enable running validators. + + By default, they are run. + + Args: + disabled (bool): If `True`, disable running all validators. + + .. warning:: + + This function is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(not disabled) + + +def get_disabled(): + """ + Return a bool indicating whether validators are currently disabled or not. + + Returns: + bool:`True` if validators are currently disabled. + + .. versionadded:: 21.3.0 + """ + return not get_run_validators() + + +@contextmanager +def disabled(): + """ + Context manager that disables running validators within its context. + + .. warning:: + + This context manager is not thread-safe! + + .. versionadded:: 21.3.0 + """ + set_run_validators(False) + try: + yield + finally: + set_run_validators(True) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _InstanceOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not isinstance(value, self.type): + msg = f"'{attr.name}' must be {self.type!r} (got {value!r} that is a {value.__class__!r})." + raise TypeError( + msg, + attr, + self.type, + value, + ) + + def __repr__(self): + return f"" + + +def instance_of(type): + """ + A validator that raises a `TypeError` if the initializer is called with a + wrong type for this particular attribute (checks are performed using + `isinstance` therefore it's also valid to pass a tuple of types). + + Args: + type (type | tuple[type]): The type to check for. + + Raises: + TypeError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected type, and the value it got. + """ + return _InstanceOfValidator(type) + + +@attrs(repr=False, frozen=True, slots=True) +class _MatchesReValidator: + pattern = attrib() + match_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.match_func(value): + msg = f"'{attr.name}' must match regex {self.pattern.pattern!r} ({value!r} doesn't)" + raise ValueError( + msg, + attr, + self.pattern, + value, + ) + + def __repr__(self): + return f"" + + +def matches_re(regex, flags=0, func=None): + r""" + A validator that raises `ValueError` if the initializer is called with a + string that doesn't match *regex*. + + Args: + regex (str, re.Pattern): + A regex string or precompiled pattern to match against + + flags (int): + Flags that will be passed to the underlying re function (default 0) + + func (typing.Callable): + Which underlying `re` function to call. Valid options are + `re.fullmatch`, `re.search`, and `re.match`; the default `None` + means `re.fullmatch`. For performance reasons, the pattern is + always precompiled using `re.compile`. + + .. versionadded:: 19.2.0 + .. versionchanged:: 21.3.0 *regex* can be a pre-compiled pattern. + """ + valid_funcs = (re.fullmatch, None, re.search, re.match) + if func not in valid_funcs: + msg = "'func' must be one of {}.".format( + ", ".join( + sorted((e and e.__name__) or "None" for e in set(valid_funcs)) + ) + ) + raise ValueError(msg) + + if isinstance(regex, Pattern): + if flags: + msg = "'flags' can only be used with a string pattern; pass flags to re.compile() instead" + raise TypeError(msg) + pattern = regex + else: + pattern = re.compile(regex, flags) + + if func is re.match: + match_func = pattern.match + elif func is re.search: + match_func = pattern.search + else: + match_func = pattern.fullmatch + + return _MatchesReValidator(pattern, match_func) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _OptionalValidator: + validator = attrib() + + def __call__(self, inst, attr, value): + if value is None: + return + + self.validator(inst, attr, value) + + def __repr__(self): + return f"" + + +def optional(validator): + """ + A validator that makes an attribute optional. An optional attribute is one + which can be set to `None` in addition to satisfying the requirements of + the sub-validator. + + Args: + validator + (typing.Callable | tuple[typing.Callable] | list[typing.Callable]): + A validator (or validators) that is used for non-`None` values. + + .. versionadded:: 15.1.0 + .. versionchanged:: 17.1.0 *validator* can be a list of validators. + .. versionchanged:: 23.1.0 *validator* can also be a tuple of validators. + """ + if isinstance(validator, (list, tuple)): + return _OptionalValidator(_AndValidator(validator)) + + return _OptionalValidator(validator) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _InValidator: + options = attrib() + _original_options = attrib(hash=False) + + def __call__(self, inst, attr, value): + try: + in_options = value in self.options + except TypeError: # e.g. `1 in "abc"` + in_options = False + + if not in_options: + msg = f"'{attr.name}' must be in {self._original_options!r} (got {value!r})" + raise ValueError( + msg, + attr, + self._original_options, + value, + ) + + def __repr__(self): + return f"" + + +def in_(options): + """ + A validator that raises a `ValueError` if the initializer is called with a + value that does not belong in the *options* provided. + + The check is performed using ``value in options``, so *options* has to + support that operation. + + To keep the validator hashable, dicts, lists, and sets are transparently + transformed into a `tuple`. + + Args: + options: Allowed options. + + Raises: + ValueError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected options, and the value it got. + + .. versionadded:: 17.1.0 + .. versionchanged:: 22.1.0 + The ValueError was incomplete until now and only contained the human + readable error message. Now it contains all the information that has + been promised since 17.1.0. + .. versionchanged:: 24.1.0 + *options* that are a list, dict, or a set are now transformed into a + tuple to keep the validator hashable. + """ + repr_options = options + if isinstance(options, (list, dict, set)): + options = tuple(options) + + return _InValidator(options, repr_options) + + +@attrs(repr=False, slots=False, unsafe_hash=True) +class _IsCallableValidator: + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not callable(value): + message = ( + "'{name}' must be callable " + "(got {value!r} that is a {actual!r})." + ) + raise NotCallableError( + msg=message.format( + name=attr.name, value=value, actual=value.__class__ + ), + value=value, + ) + + def __repr__(self): + return "" + + +def is_callable(): + """ + A validator that raises a `attrs.exceptions.NotCallableError` if the + initializer is called with a value for this particular attribute that is + not callable. + + .. versionadded:: 19.1.0 + + Raises: + attrs.exceptions.NotCallableError: + With a human readable error message containing the attribute + (`attrs.Attribute`) name, and the value it got. + """ + return _IsCallableValidator() + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _DeepIterable: + member_validator = attrib(validator=is_callable()) + iterable_validator = attrib( + default=None, validator=optional(is_callable()) + ) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.iterable_validator is not None: + self.iterable_validator(inst, attr, value) + + for member in value: + self.member_validator(inst, attr, member) + + def __repr__(self): + iterable_identifier = ( + "" + if self.iterable_validator is None + else f" {self.iterable_validator!r}" + ) + return ( + f"" + ) + + +def deep_iterable(member_validator, iterable_validator=None): + """ + A validator that performs deep validation of an iterable. + + Args: + member_validator: Validator to apply to iterable members. + + iterable_validator: + Validator to apply to iterable itself (optional). + + Raises + TypeError: if any sub-validators fail + + .. versionadded:: 19.1.0 + """ + if isinstance(member_validator, (list, tuple)): + member_validator = and_(*member_validator) + return _DeepIterable(member_validator, iterable_validator) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _DeepMapping: + key_validator = attrib(validator=is_callable()) + value_validator = attrib(validator=is_callable()) + mapping_validator = attrib(default=None, validator=optional(is_callable())) + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if self.mapping_validator is not None: + self.mapping_validator(inst, attr, value) + + for key in value: + self.key_validator(inst, attr, key) + self.value_validator(inst, attr, value[key]) + + def __repr__(self): + return f"" + + +def deep_mapping(key_validator, value_validator, mapping_validator=None): + """ + A validator that performs deep validation of a dictionary. + + Args: + key_validator: Validator to apply to dictionary keys. + + value_validator: Validator to apply to dictionary values. + + mapping_validator: + Validator to apply to top-level mapping attribute (optional). + + .. versionadded:: 19.1.0 + + Raises: + TypeError: if any sub-validators fail + """ + return _DeepMapping(key_validator, value_validator, mapping_validator) + + +@attrs(repr=False, frozen=True, slots=True) +class _NumberValidator: + bound = attrib() + compare_op = attrib() + compare_func = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not self.compare_func(value, self.bound): + msg = f"'{attr.name}' must be {self.compare_op} {self.bound}: {value}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def lt(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number larger or equal to *val*. + + The validator uses `operator.lt` to compare the values. + + Args: + val: Exclusive upper bound for values. + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<", operator.lt) + + +def le(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number greater than *val*. + + The validator uses `operator.le` to compare the values. + + Args: + val: Inclusive upper bound for values. + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, "<=", operator.le) + + +def ge(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number smaller than *val*. + + The validator uses `operator.ge` to compare the values. + + Args: + val: Inclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">=", operator.ge) + + +def gt(val): + """ + A validator that raises `ValueError` if the initializer is called with a + number smaller or equal to *val*. + + The validator uses `operator.ge` to compare the values. + + Args: + val: Exclusive lower bound for values + + .. versionadded:: 21.3.0 + """ + return _NumberValidator(val, ">", operator.gt) + + +@attrs(repr=False, frozen=True, slots=True) +class _MaxLengthValidator: + max_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) > self.max_length: + msg = f"Length of '{attr.name}' must be <= {self.max_length}: {len(value)}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def max_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is longer than *length*. + + Args: + length (int): Maximum length of the string or iterable + + .. versionadded:: 21.3.0 + """ + return _MaxLengthValidator(length) + + +@attrs(repr=False, frozen=True, slots=True) +class _MinLengthValidator: + min_length = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if len(value) < self.min_length: + msg = f"Length of '{attr.name}' must be >= {self.min_length}: {len(value)}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def min_len(length): + """ + A validator that raises `ValueError` if the initializer is called + with a string or iterable that is shorter than *length*. + + Args: + length (int): Minimum length of the string or iterable + + .. versionadded:: 22.1.0 + """ + return _MinLengthValidator(length) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _SubclassOfValidator: + type = attrib() + + def __call__(self, inst, attr, value): + """ + We use a callable class to be able to change the ``__repr__``. + """ + if not issubclass(value, self.type): + msg = f"'{attr.name}' must be a subclass of {self.type!r} (got {value!r})." + raise TypeError( + msg, + attr, + self.type, + value, + ) + + def __repr__(self): + return f"" + + +def _subclass_of(type): + """ + A validator that raises a `TypeError` if the initializer is called with a + wrong type for this particular attribute (checks are performed using + `issubclass` therefore it's also valid to pass a tuple of types). + + Args: + type (type | tuple[type, ...]): The type(s) to check for. + + Raises: + TypeError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the expected type, and the value it got. + """ + return _SubclassOfValidator(type) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _NotValidator: + validator = attrib() + msg = attrib( + converter=default_if_none( + "not_ validator child '{validator!r}' " + "did not raise a captured error" + ) + ) + exc_types = attrib( + validator=deep_iterable( + member_validator=_subclass_of(Exception), + iterable_validator=instance_of(tuple), + ), + ) + + def __call__(self, inst, attr, value): + try: + self.validator(inst, attr, value) + except self.exc_types: + pass # suppress error to invert validity + else: + raise ValueError( + self.msg.format( + validator=self.validator, + exc_types=self.exc_types, + ), + attr, + self.validator, + value, + self.exc_types, + ) + + def __repr__(self): + return f"" + + +def not_(validator, *, msg=None, exc_types=(ValueError, TypeError)): + """ + A validator that wraps and logically 'inverts' the validator passed to it. + It will raise a `ValueError` if the provided validator *doesn't* raise a + `ValueError` or `TypeError` (by default), and will suppress the exception + if the provided validator *does*. + + Intended to be used with existing validators to compose logic without + needing to create inverted variants, for example, ``not_(in_(...))``. + + Args: + validator: A validator to be logically inverted. + + msg (str): + Message to raise if validator fails. Formatted with keys + ``exc_types`` and ``validator``. + + exc_types (tuple[type, ...]): + Exception type(s) to capture. Other types raised by child + validators will not be intercepted and pass through. + + Raises: + ValueError: + With a human readable error message, the attribute (of type + `attrs.Attribute`), the validator that failed to raise an + exception, the value it got, and the expected exception types. + + .. versionadded:: 22.2.0 + """ + try: + exc_types = tuple(exc_types) + except TypeError: + exc_types = (exc_types,) + return _NotValidator(validator, msg, exc_types) + + +@attrs(repr=False, slots=True, unsafe_hash=True) +class _OrValidator: + validators = attrib() + + def __call__(self, inst, attr, value): + for v in self.validators: + try: + v(inst, attr, value) + except Exception: # noqa: BLE001, PERF203, S112 + continue + else: + return + + msg = f"None of {self.validators!r} satisfied for value {value!r}" + raise ValueError(msg) + + def __repr__(self): + return f"" + + +def or_(*validators): + """ + A validator that composes multiple validators into one. + + When called on a value, it runs all wrapped validators until one of them is + satisfied. + + Args: + validators (~collections.abc.Iterable[typing.Callable]): + Arbitrary number of validators. + + Raises: + ValueError: + If no validator is satisfied. Raised with a human-readable error + message listing all the wrapped validators and the value that + failed all of them. + + .. versionadded:: 24.1.0 + """ + vals = [] + for v in validators: + vals.extend(v.validators if isinstance(v, _OrValidator) else [v]) + + return _OrValidator(tuple(vals)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/validators.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/validators.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a0fdda7c8773f791103938fca0d4b448859aff1f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attr/validators.pyi @@ -0,0 +1,86 @@ +from types import UnionType +from typing import ( + Any, + AnyStr, + Callable, + Container, + ContextManager, + Iterable, + Mapping, + Match, + Pattern, + TypeVar, + overload, +) + +from attrs import _ValidatorType +from attrs import _ValidatorArgType + +_T = TypeVar("_T") +_T1 = TypeVar("_T1") +_T2 = TypeVar("_T2") +_T3 = TypeVar("_T3") +_I = TypeVar("_I", bound=Iterable) +_K = TypeVar("_K") +_V = TypeVar("_V") +_M = TypeVar("_M", bound=Mapping) + +def set_disabled(run: bool) -> None: ... +def get_disabled() -> bool: ... +def disabled() -> ContextManager[None]: ... + +# To be more precise on instance_of use some overloads. +# If there are more than 3 items in the tuple then we fall back to Any +@overload +def instance_of(type: type[_T]) -> _ValidatorType[_T]: ... +@overload +def instance_of(type: tuple[type[_T]]) -> _ValidatorType[_T]: ... +@overload +def instance_of( + type: tuple[type[_T1], type[_T2]], +) -> _ValidatorType[_T1 | _T2]: ... +@overload +def instance_of( + type: tuple[type[_T1], type[_T2], type[_T3]], +) -> _ValidatorType[_T1 | _T2 | _T3]: ... +@overload +def instance_of(type: tuple[type, ...]) -> _ValidatorType[Any]: ... +@overload +def instance_of(type: UnionType) -> _ValidatorType[Any]: ... +def optional( + validator: ( + _ValidatorType[_T] + | list[_ValidatorType[_T]] + | tuple[_ValidatorType[_T]] + ), +) -> _ValidatorType[_T | None]: ... +def in_(options: Container[_T]) -> _ValidatorType[_T]: ... +def and_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... +def matches_re( + regex: Pattern[AnyStr] | AnyStr, + flags: int = ..., + func: Callable[[AnyStr, AnyStr, int], Match[AnyStr] | None] | None = ..., +) -> _ValidatorType[AnyStr]: ... +def deep_iterable( + member_validator: _ValidatorArgType[_T], + iterable_validator: _ValidatorType[_I] | None = ..., +) -> _ValidatorType[_I]: ... +def deep_mapping( + key_validator: _ValidatorType[_K], + value_validator: _ValidatorType[_V], + mapping_validator: _ValidatorType[_M] | None = ..., +) -> _ValidatorType[_M]: ... +def is_callable() -> _ValidatorType[_T]: ... +def lt(val: _T) -> _ValidatorType[_T]: ... +def le(val: _T) -> _ValidatorType[_T]: ... +def ge(val: _T) -> _ValidatorType[_T]: ... +def gt(val: _T) -> _ValidatorType[_T]: ... +def max_len(length: int) -> _ValidatorType[_T]: ... +def min_len(length: int) -> _ValidatorType[_T]: ... +def not_( + validator: _ValidatorType[_T], + *, + msg: str | None = None, + exc_types: type[Exception] | Iterable[type[Exception]] = ..., +) -> _ValidatorType[_T]: ... +def or_(*validators: _ValidatorType[_T]) -> _ValidatorType[_T]: ... diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/INSTALLER b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/METADATA b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..029afeeb9d40379521ba0ad9a6cdea3ae2226235 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/METADATA @@ -0,0 +1,232 @@ +Metadata-Version: 2.4 +Name: attrs +Version: 25.3.0 +Summary: Classes Without Boilerplate +Project-URL: Documentation, https://www.attrs.org/ +Project-URL: Changelog, https://www.attrs.org/en/stable/changelog.html +Project-URL: GitHub, https://github.com/python-attrs/attrs +Project-URL: Funding, https://github.com/sponsors/hynek +Project-URL: Tidelift, https://tidelift.com/subscription/pkg/pypi-attrs?utm_source=pypi-attrs&utm_medium=pypi +Author-email: Hynek Schlawack +License-Expression: MIT +License-File: LICENSE +Keywords: attribute,boilerplate,class +Classifier: Development Status :: 5 - Production/Stable +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Typing :: Typed +Requires-Python: >=3.8 +Provides-Extra: benchmark +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'benchmark' +Requires-Dist: hypothesis; extra == 'benchmark' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'benchmark' +Requires-Dist: pympler; extra == 'benchmark' +Requires-Dist: pytest-codspeed; extra == 'benchmark' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'benchmark' +Requires-Dist: pytest-xdist[psutil]; extra == 'benchmark' +Requires-Dist: pytest>=4.3.0; extra == 'benchmark' +Provides-Extra: cov +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'cov' +Requires-Dist: coverage[toml]>=5.3; extra == 'cov' +Requires-Dist: hypothesis; extra == 'cov' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'cov' +Requires-Dist: pympler; extra == 'cov' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'cov' +Requires-Dist: pytest-xdist[psutil]; extra == 'cov' +Requires-Dist: pytest>=4.3.0; extra == 'cov' +Provides-Extra: dev +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'dev' +Requires-Dist: hypothesis; extra == 'dev' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'dev' +Requires-Dist: pre-commit-uv; extra == 'dev' +Requires-Dist: pympler; extra == 'dev' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'dev' +Requires-Dist: pytest-xdist[psutil]; extra == 'dev' +Requires-Dist: pytest>=4.3.0; extra == 'dev' +Provides-Extra: docs +Requires-Dist: cogapp; extra == 'docs' +Requires-Dist: furo; extra == 'docs' +Requires-Dist: myst-parser; extra == 'docs' +Requires-Dist: sphinx; extra == 'docs' +Requires-Dist: sphinx-notfound-page; extra == 'docs' +Requires-Dist: sphinxcontrib-towncrier; extra == 'docs' +Requires-Dist: towncrier; extra == 'docs' +Provides-Extra: tests +Requires-Dist: cloudpickle; (platform_python_implementation == 'CPython') and extra == 'tests' +Requires-Dist: hypothesis; extra == 'tests' +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests' +Requires-Dist: pympler; extra == 'tests' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests' +Requires-Dist: pytest-xdist[psutil]; extra == 'tests' +Requires-Dist: pytest>=4.3.0; extra == 'tests' +Provides-Extra: tests-mypy +Requires-Dist: mypy>=1.11.1; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests-mypy' +Requires-Dist: pytest-mypy-plugins; (platform_python_implementation == 'CPython' and python_version >= '3.10') and extra == 'tests-mypy' +Description-Content-Type: text/markdown + +

    + + attrs + +

    + + +*attrs* is the Python package that will bring back the **joy** of **writing classes** by relieving you from the drudgery of implementing object protocols (aka [dunder methods](https://www.attrs.org/en/latest/glossary.html#term-dunder-methods)). +[Trusted by NASA](https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-github-profile/customizing-your-profile/personalizing-your-profile#list-of-qualifying-repositories-for-mars-2020-helicopter-contributor-achievement) for Mars missions since 2020! + +Its main goal is to help you to write **concise** and **correct** software without slowing down your code. + + +## Sponsors + +*attrs* would not be possible without our [amazing sponsors](https://github.com/sponsors/hynek). +Especially those generously supporting us at the *The Organization* tier and higher: + + + +

    + + + + + + + + + + + +

    + + + +

    + Please consider joining them to help make attrs’s maintenance more sustainable! +

    + + + +## Example + +*attrs* gives you a class decorator and a way to declaratively define the attributes on that class: + + + +```pycon +>>> from attrs import asdict, define, make_class, Factory + +>>> @define +... class SomeClass: +... a_number: int = 42 +... list_of_numbers: list[int] = Factory(list) +... +... def hard_math(self, another_number): +... return self.a_number + sum(self.list_of_numbers) * another_number + + +>>> sc = SomeClass(1, [1, 2, 3]) +>>> sc +SomeClass(a_number=1, list_of_numbers=[1, 2, 3]) + +>>> sc.hard_math(3) +19 +>>> sc == SomeClass(1, [1, 2, 3]) +True +>>> sc != SomeClass(2, [3, 2, 1]) +True + +>>> asdict(sc) +{'a_number': 1, 'list_of_numbers': [1, 2, 3]} + +>>> SomeClass() +SomeClass(a_number=42, list_of_numbers=[]) + +>>> C = make_class("C", ["a", "b"]) +>>> C("foo", "bar") +C(a='foo', b='bar') +``` + +After *declaring* your attributes, *attrs* gives you: + +- a concise and explicit overview of the class's attributes, +- a nice human-readable `__repr__`, +- equality-checking methods, +- an initializer, +- and much more, + +*without* writing dull boilerplate code again and again and *without* runtime performance penalties. + +--- + +This example uses *attrs*'s modern APIs that have been introduced in version 20.1.0, and the *attrs* package import name that has been added in version 21.3.0. +The classic APIs (`@attr.s`, `attr.ib`, plus their serious-business aliases) and the `attr` package import name will remain **indefinitely**. + +Check out [*On The Core API Names*](https://www.attrs.org/en/latest/names.html) for an in-depth explanation! + + +### Hate Type Annotations!? + +No problem! +Types are entirely **optional** with *attrs*. +Simply assign `attrs.field()` to the attributes instead of annotating them with types: + +```python +from attrs import define, field + +@define +class SomeClass: + a_number = field(default=42) + list_of_numbers = field(factory=list) +``` + + +## Data Classes + +On the tin, *attrs* might remind you of `dataclasses` (and indeed, `dataclasses` [are a descendant](https://hynek.me/articles/import-attrs/) of *attrs*). +In practice it does a lot more and is more flexible. +For instance, it allows you to define [special handling of NumPy arrays for equality checks](https://www.attrs.org/en/stable/comparison.html#customization), allows more ways to [plug into the initialization process](https://www.attrs.org/en/stable/init.html#hooking-yourself-into-initialization), has a replacement for `__init_subclass__`, and allows for stepping through the generated methods using a debugger. + +For more details, please refer to our [comparison page](https://www.attrs.org/en/stable/why.html#data-classes), but generally speaking, we are more likely to commit crimes against nature to make things work that one would expect to work, but that are quite complicated in practice. + + +## Project Information + +- [**Changelog**](https://www.attrs.org/en/stable/changelog.html) +- [**Documentation**](https://www.attrs.org/) +- [**PyPI**](https://pypi.org/project/attrs/) +- [**Source Code**](https://github.com/python-attrs/attrs) +- [**Contributing**](https://github.com/python-attrs/attrs/blob/main/.github/CONTRIBUTING.md) +- [**Third-party Extensions**](https://github.com/python-attrs/attrs/wiki/Extensions-to-attrs) +- **Get Help**: use the `python-attrs` tag on [Stack Overflow](https://stackoverflow.com/questions/tagged/python-attrs) + + +### *attrs* for Enterprise + +Available as part of the [Tidelift Subscription](https://tidelift.com/?utm_source=lifter&utm_medium=referral&utm_campaign=hynek). + +The maintainers of *attrs* and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. +Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. + +## Release Information + +### Changes + +- Restore support for generator-based `field_transformer`s. + [#1417](https://github.com/python-attrs/attrs/issues/1417) + + + +--- + +[Full changelog →](https://www.attrs.org/en/stable/changelog.html) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/RECORD b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..b04b541882326dde7bade0293de8caac5d67fe60 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/RECORD @@ -0,0 +1,55 @@ +attr/__init__.py,sha256=fOYIvt1eGSqQre4uCS3sJWKZ0mwAuC8UD6qba5OS9_U,2057 +attr/__init__.pyi,sha256=QIXnnHPoucmDWkbpNsWTP-cgJ1bn8le7DjyRa_wYdew,11281 +attr/__pycache__/__init__.cpython-312.pyc,, +attr/__pycache__/_cmp.cpython-312.pyc,, +attr/__pycache__/_compat.cpython-312.pyc,, +attr/__pycache__/_config.cpython-312.pyc,, +attr/__pycache__/_funcs.cpython-312.pyc,, +attr/__pycache__/_make.cpython-312.pyc,, +attr/__pycache__/_next_gen.cpython-312.pyc,, +attr/__pycache__/_version_info.cpython-312.pyc,, +attr/__pycache__/converters.cpython-312.pyc,, +attr/__pycache__/exceptions.cpython-312.pyc,, +attr/__pycache__/filters.cpython-312.pyc,, +attr/__pycache__/setters.cpython-312.pyc,, +attr/__pycache__/validators.cpython-312.pyc,, +attr/_cmp.py,sha256=3Nn1TjxllUYiX_nJoVnEkXoDk0hM1DYKj5DE7GZe4i0,4117 +attr/_cmp.pyi,sha256=U-_RU_UZOyPUEQzXE6RMYQQcjkZRY25wTH99sN0s7MM,368 +attr/_compat.py,sha256=4hlXbWhdDjQCDK6FKF1EgnZ3POiHgtpp54qE0nxaGHg,2704 +attr/_config.py,sha256=dGq3xR6fgZEF6UBt_L0T-eUHIB4i43kRmH0P28sJVw8,843 +attr/_funcs.py,sha256=5-tUKJtp3h5El55EcDl6GWXFp68fT8D8U7uCRN6497I,15854 +attr/_make.py,sha256=lBUPPmxiA1BeHzB6OlHoCEh--tVvM1ozXO8eXOa6g4c,96664 +attr/_next_gen.py,sha256=7FRkbtl_N017SuBhf_Vw3mw2c2pGZhtCGOzadgz7tp4,24395 +attr/_typing_compat.pyi,sha256=XDP54TUn-ZKhD62TOQebmzrwFyomhUCoGRpclb6alRA,469 +attr/_version_info.py,sha256=exSqb3b5E-fMSsgZAlEw9XcLpEgobPORCZpcaEglAM4,2121 +attr/_version_info.pyi,sha256=x_M3L3WuB7r_ULXAWjx959udKQ4HLB8l-hsc1FDGNvk,209 +attr/converters.py,sha256=GlDeOzPeTFgeBBLbj9G57Ez5lAk68uhSALRYJ_exe84,3861 +attr/converters.pyi,sha256=orU2bff-VjQa2kMDyvnMQV73oJT2WRyQuw4ZR1ym1bE,643 +attr/exceptions.py,sha256=HRFq4iybmv7-DcZwyjl6M1euM2YeJVK_hFxuaBGAngI,1977 +attr/exceptions.pyi,sha256=zZq8bCUnKAy9mDtBEw42ZhPhAUIHoTKedDQInJD883M,539 +attr/filters.py,sha256=ZBiKWLp3R0LfCZsq7X11pn9WX8NslS2wXM4jsnLOGc8,1795 +attr/filters.pyi,sha256=3J5BG-dTxltBk1_-RuNRUHrv2qu1v8v4aDNAQ7_mifA,208 +attr/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +attr/setters.py,sha256=5-dcT63GQK35ONEzSgfXCkbB7pPkaR-qv15mm4PVSzQ,1617 +attr/setters.pyi,sha256=NnVkaFU1BB4JB8E4JuXyrzTUgvtMpj8p3wBdJY7uix4,584 +attr/validators.py,sha256=WaB1HLAHHqRHWsrv_K9H-sJ7ESil3H3Cmv2d8TtVZx4,20046 +attr/validators.pyi,sha256=s2WhKPqskxbsckJfKk8zOuuB088GfgpyxcCYSNFLqNU,2603 +attrs-25.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +attrs-25.3.0.dist-info/METADATA,sha256=W38cREj7s1wqNf1fg4hVwZmL1xh0AdSp4IhtTMROinw,10993 +attrs-25.3.0.dist-info/RECORD,, +attrs-25.3.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87 +attrs-25.3.0.dist-info/licenses/LICENSE,sha256=iCEVyV38KvHutnFPjsbVy8q_Znyv-HKfQkINpj9xTp8,1109 +attrs/__init__.py,sha256=qeQJZ4O08yczSn840v9bYOaZyRE81WsVi-QCrY3krCU,1107 +attrs/__init__.pyi,sha256=nZmInocjM7tHV4AQw0vxO_fo6oJjL_PonlV9zKKW8DY,7931 +attrs/__pycache__/__init__.cpython-312.pyc,, +attrs/__pycache__/converters.cpython-312.pyc,, +attrs/__pycache__/exceptions.cpython-312.pyc,, +attrs/__pycache__/filters.cpython-312.pyc,, +attrs/__pycache__/setters.cpython-312.pyc,, +attrs/__pycache__/validators.cpython-312.pyc,, +attrs/converters.py,sha256=8kQljrVwfSTRu8INwEk8SI0eGrzmWftsT7rM0EqyohM,76 +attrs/exceptions.py,sha256=ACCCmg19-vDFaDPY9vFl199SPXCQMN_bENs4DALjzms,76 +attrs/filters.py,sha256=VOUMZug9uEU6dUuA0dF1jInUK0PL3fLgP0VBS5d-CDE,73 +attrs/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +attrs/setters.py,sha256=eL1YidYQV3T2h9_SYIZSZR1FAcHGb1TuCTy0E0Lv2SU,73 +attrs/validators.py,sha256=xcy6wD5TtTkdCG1f4XWbocPSO0faBjk5IfVJfP6SUj0,76 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/WHEEL b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..12228d414b6cfed7c39d3781c85c63256a1d7fb5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs-25.3.0.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: hatchling 1.27.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e8023ff6c5783ab98e4c689c6be8c5321eae0b05 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/__init__.py @@ -0,0 +1,69 @@ +# SPDX-License-Identifier: MIT + +from attr import ( + NOTHING, + Attribute, + AttrsInstance, + Converter, + Factory, + NothingType, + _make_getattr, + assoc, + cmp_using, + define, + evolve, + field, + fields, + fields_dict, + frozen, + has, + make_class, + mutable, + resolve_types, + validate, +) +from attr._next_gen import asdict, astuple + +from . import converters, exceptions, filters, setters, validators + + +__all__ = [ + "NOTHING", + "Attribute", + "AttrsInstance", + "Converter", + "Factory", + "NothingType", + "__author__", + "__copyright__", + "__description__", + "__doc__", + "__email__", + "__license__", + "__title__", + "__url__", + "__version__", + "__version_info__", + "asdict", + "assoc", + "astuple", + "cmp_using", + "converters", + "define", + "evolve", + "exceptions", + "field", + "fields", + "fields_dict", + "filters", + "frozen", + "has", + "make_class", + "mutable", + "resolve_types", + "setters", + "validate", + "validators", +] + +__getattr__ = _make_getattr(__name__) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/__init__.pyi b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..648fa7a344433df00fbdc2852da2281b7178bb3c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/__init__.pyi @@ -0,0 +1,263 @@ +import sys + +from typing import ( + Any, + Callable, + Mapping, + Sequence, + overload, + TypeVar, +) + +# Because we need to type our own stuff, we have to make everything from +# attr explicitly public too. +from attr import __author__ as __author__ +from attr import __copyright__ as __copyright__ +from attr import __description__ as __description__ +from attr import __email__ as __email__ +from attr import __license__ as __license__ +from attr import __title__ as __title__ +from attr import __url__ as __url__ +from attr import __version__ as __version__ +from attr import __version_info__ as __version_info__ +from attr import assoc as assoc +from attr import Attribute as Attribute +from attr import AttrsInstance as AttrsInstance +from attr import cmp_using as cmp_using +from attr import converters as converters +from attr import Converter as Converter +from attr import evolve as evolve +from attr import exceptions as exceptions +from attr import Factory as Factory +from attr import fields as fields +from attr import fields_dict as fields_dict +from attr import filters as filters +from attr import has as has +from attr import make_class as make_class +from attr import NOTHING as NOTHING +from attr import resolve_types as resolve_types +from attr import setters as setters +from attr import validate as validate +from attr import validators as validators +from attr import attrib, asdict as asdict, astuple as astuple +from attr import NothingType as NothingType + +if sys.version_info >= (3, 11): + from typing import dataclass_transform +else: + from typing_extensions import dataclass_transform + +_T = TypeVar("_T") +_C = TypeVar("_C", bound=type) + +_EqOrderType = bool | Callable[[Any], Any] +_ValidatorType = Callable[[Any, "Attribute[_T]", _T], Any] +_CallableConverterType = Callable[[Any], Any] +_ConverterType = _CallableConverterType | Converter[Any, Any] +_ReprType = Callable[[Any], str] +_ReprArgType = bool | _ReprType +_OnSetAttrType = Callable[[Any, "Attribute[Any]", Any], Any] +_OnSetAttrArgType = _OnSetAttrType | list[_OnSetAttrType] | setters._NoOpType +_FieldTransformer = Callable[ + [type, list["Attribute[Any]"]], list["Attribute[Any]"] +] +# FIXME: in reality, if multiple validators are passed they must be in a list +# or tuple, but those are invariant and so would prevent subtypes of +# _ValidatorType from working when passed in a list or tuple. +_ValidatorArgType = _ValidatorType[_T] | Sequence[_ValidatorType[_T]] + +@overload +def field( + *, + default: None = ..., + validator: None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: None = ..., + factory: None = ..., + kw_only: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> Any: ... + +# This form catches an explicit None or no default and infers the type from the +# other arguments. +@overload +def field( + *, + default: None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> _T: ... + +# This form catches an explicit default argument. +@overload +def field( + *, + default: _T, + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> _T: ... + +# This form covers type=non-Type: e.g. forward references (str), Any +@overload +def field( + *, + default: _T | None = ..., + validator: _ValidatorArgType[_T] | None = ..., + repr: _ReprArgType = ..., + hash: bool | None = ..., + init: bool = ..., + metadata: Mapping[Any, Any] | None = ..., + converter: _ConverterType + | list[_ConverterType] + | tuple[_ConverterType] + | None = ..., + factory: Callable[[], _T] | None = ..., + kw_only: bool = ..., + eq: _EqOrderType | None = ..., + order: _EqOrderType | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + alias: str | None = ..., + type: type | None = ..., +) -> Any: ... +@overload +@dataclass_transform(field_specifiers=(attrib, field)) +def define( + maybe_cls: _C, + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> _C: ... +@overload +@dataclass_transform(field_specifiers=(attrib, field)) +def define( + maybe_cls: None = ..., + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> Callable[[_C], _C]: ... + +mutable = define + +@overload +@dataclass_transform(frozen_default=True, field_specifiers=(attrib, field)) +def frozen( + maybe_cls: _C, + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> _C: ... +@overload +@dataclass_transform(frozen_default=True, field_specifiers=(attrib, field)) +def frozen( + maybe_cls: None = ..., + *, + these: dict[str, Any] | None = ..., + repr: bool = ..., + unsafe_hash: bool | None = ..., + hash: bool | None = ..., + init: bool = ..., + slots: bool = ..., + frozen: bool = ..., + weakref_slot: bool = ..., + str: bool = ..., + auto_attribs: bool = ..., + kw_only: bool = ..., + cache_hash: bool = ..., + auto_exc: bool = ..., + eq: bool | None = ..., + order: bool | None = ..., + auto_detect: bool = ..., + getstate_setstate: bool | None = ..., + on_setattr: _OnSetAttrArgType | None = ..., + field_transformer: _FieldTransformer | None = ..., + match_args: bool = ..., +) -> Callable[[_C], _C]: ... diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/converters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/converters.py new file mode 100644 index 0000000000000000000000000000000000000000..7821f6c02cca81277d1ecc87b6bdafad886d8b70 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/converters.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.converters import * # noqa: F403 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/filters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/filters.py new file mode 100644 index 0000000000000000000000000000000000000000..3080f48398e5ed8d3428ca3efeb7500633b0cb0f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/filters.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.filters import * # noqa: F403 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/validators.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/validators.py new file mode 100644 index 0000000000000000000000000000000000000000..037e124f29f32d37c1642d159bf828de44f7c349 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/attrs/validators.py @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: MIT + +from attr.validators import * # noqa: F403 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/frozenlist/_frozenlist.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/frozenlist/_frozenlist.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..61f14711a1fa2b51b2c1fd5e7e0d2f6ab75b98e5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/frozenlist/_frozenlist.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94bbe6b3cec99b973a65af4df9e254aee0ad76c4d12ab442b1ce613d14767a88 +size 789896 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4110fba54dfd83e712394eb3a9ab6d0e39452d4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/idna/__pycache__/uts46data.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26a67cd5cccd2a791bf11fcb07602adf14f4cf20adfb2ee102a3ffafc5b8ad9c +size 158863 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict-6.6.3.dist-info/INSTALLER b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict-6.6.3.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict-6.6.3.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c506324f39285a57fc1937fdbacb53b7c3a65d61 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/__init__.py @@ -0,0 +1,59 @@ +"""Multidict implementation. + +HTTP Headers and URL query string require specific data structure: +multidict. It behaves mostly like a dict but it can have +several values for the same key. +""" + +from typing import TYPE_CHECKING + +from ._abc import MultiMapping, MutableMultiMapping +from ._compat import USE_EXTENSIONS + +__all__ = ( + "MultiMapping", + "MutableMultiMapping", + "MultiDictProxy", + "CIMultiDictProxy", + "MultiDict", + "CIMultiDict", + "upstr", + "istr", + "getversion", +) + +__version__ = "6.6.3" + + +if TYPE_CHECKING or not USE_EXTENSIONS: + from ._multidict_py import ( + CIMultiDict, + CIMultiDictProxy, + MultiDict, + MultiDictProxy, + getversion, + istr, + ) +else: + from collections.abc import ItemsView, KeysView, ValuesView + + from ._multidict import ( + CIMultiDict, + CIMultiDictProxy, + MultiDict, + MultiDictProxy, + _ItemsView, + _KeysView, + _ValuesView, + getversion, + istr, + ) + + MultiMapping.register(MultiDictProxy) + MutableMultiMapping.register(MultiDict) + KeysView.register(_KeysView) + ItemsView.register(_ItemsView) + ValuesView.register(_ValuesView) + + +upstr = istr diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/_abc.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/_abc.py new file mode 100644 index 0000000000000000000000000000000000000000..54253e9e779915aa8741313563359a8d9d87ec16 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/_abc.py @@ -0,0 +1,73 @@ +import abc +from collections.abc import Iterable, Mapping, MutableMapping +from typing import TYPE_CHECKING, Protocol, TypeVar, Union, overload + +if TYPE_CHECKING: + from ._multidict_py import istr +else: + istr = str + +_V = TypeVar("_V") +_V_co = TypeVar("_V_co", covariant=True) +_T = TypeVar("_T") + + +class SupportsKeys(Protocol[_V_co]): + def keys(self) -> Iterable[str]: ... + def __getitem__(self, key: str, /) -> _V_co: ... + + +class SupportsIKeys(Protocol[_V_co]): + def keys(self) -> Iterable[istr]: ... + def __getitem__(self, key: istr, /) -> _V_co: ... + + +MDArg = Union[SupportsKeys[_V], SupportsIKeys[_V], Iterable[tuple[str, _V]], None] + + +class MultiMapping(Mapping[str, _V_co]): + @overload + def getall(self, key: str) -> list[_V_co]: ... + @overload + def getall(self, key: str, default: _T) -> Union[list[_V_co], _T]: ... + @abc.abstractmethod + def getall(self, key: str, default: _T = ...) -> Union[list[_V_co], _T]: + """Return all values for key.""" + + @overload + def getone(self, key: str) -> _V_co: ... + @overload + def getone(self, key: str, default: _T) -> Union[_V_co, _T]: ... + @abc.abstractmethod + def getone(self, key: str, default: _T = ...) -> Union[_V_co, _T]: + """Return first value for key.""" + + +class MutableMultiMapping(MultiMapping[_V], MutableMapping[str, _V]): + @abc.abstractmethod + def add(self, key: str, value: _V) -> None: + """Add value to list.""" + + @abc.abstractmethod + def extend(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: + """Add everything from arg and kwargs to the mapping.""" + + @abc.abstractmethod + def merge(self, arg: MDArg[_V] = None, /, **kwargs: _V) -> None: + """Merge into the mapping, adding non-existing keys.""" + + @overload + def popone(self, key: str) -> _V: ... + @overload + def popone(self, key: str, default: _T) -> Union[_V, _T]: ... + @abc.abstractmethod + def popone(self, key: str, default: _T = ...) -> Union[_V, _T]: + """Remove specified key and return the corresponding value.""" + + @overload + def popall(self, key: str) -> list[_V]: ... + @overload + def popall(self, key: str, default: _T) -> Union[list[_V], _T]: ... + @abc.abstractmethod + def popall(self, key: str, default: _T = ...) -> Union[list[_V], _T]: + """Remove all occurrences of key and return the list of corresponding values.""" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/_multidict.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/_multidict.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..65f8d42ad61f347c9afc8577cd9316d1f8c51ce2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/_multidict.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1db8a9a484fb95361f6353f21800f7bfdcbe4c03191d7245eb3f1d1c2e9e9ea7 +size 848672 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/py.typed b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dfe8cc048e7100a97025b954fffa31e4ff859a7d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/multidict/py.typed @@ -0,0 +1 @@ +PEP-561 marker. \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/RECORD b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..59940fac3cd4af40c5c44f70d4c00cbe8b378ee1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/RECORD @@ -0,0 +1,18 @@ +propcache-0.3.2.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +propcache-0.3.2.dist-info/METADATA,sha256=Ygo0BOTSAt7RNgbsd75FQSckFQZO3BaMudrbffqWUiI,12028 +propcache-0.3.2.dist-info/RECORD,, +propcache-0.3.2.dist-info/WHEEL,sha256=aSgG0F4rGPZtV0iTEIfy6dtHq6g67Lze3uLfk0vWn88,151 +propcache-0.3.2.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +propcache-0.3.2.dist-info/licenses/NOTICE,sha256=VtasbIEFwKUTBMIdsGDjYa-ajqCvmnXCOcKLXRNpODg,609 +propcache-0.3.2.dist-info/top_level.txt,sha256=pVF_GbqSAITPMiX27kfU3QP9-ufhRvkADmudDxWdF3w,10 +propcache/__init__.py,sha256=GYNhDM62wOtvB_-cllzXwLED-c7zf1deB_mkumDbqZ0,965 +propcache/__pycache__/__init__.cpython-312.pyc,, +propcache/__pycache__/_helpers.cpython-312.pyc,, +propcache/__pycache__/_helpers_py.cpython-312.pyc,, +propcache/__pycache__/api.cpython-312.pyc,, +propcache/_helpers.py,sha256=68SQm6kETN8Mnt9Ol26LJYgHgmB0mKy1tp92888zN4k,1553 +propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so,sha256=hHOWRJjicT7MsdlARQwq5AiCqtmjJF1kVA0BXyIqJVw,770704 +propcache/_helpers_c.pyx,sha256=sBA8vSGryIq8OZMHrNZMWhIen00-YENcI9mmyaEEHcc,2569 +propcache/_helpers_py.py,sha256=McTg1siOzGdLE8u0TlG900epqQONuN2pAD1T3xryaNo,1917 +propcache/api.py,sha256=wvgB-ypkkI5uf72VVYl2NFGc_TnzUQA2CxC7dTlL5ak,179 +propcache/py.typed,sha256=ay5OMO475PlcZ_Fbun9maHW7Y6MBTk0UXL4ztHx3Iug,14 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/WHEEL b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e21e9f2f89caabbb0f5e84c1775fbe781dd45a63 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_17_x86_64 +Tag: cp312-cp312-manylinux2014_x86_64 + diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/top_level.txt b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c9accf6226df7e4011a41ac5d6014223685cfed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache-0.3.2.dist-info/top_level.txt @@ -0,0 +1 @@ +propcache diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41bcdb8bcd84bc40c290770fd017cff9cbf4234a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/__init__.py @@ -0,0 +1,32 @@ +"""propcache: An accelerated property cache for Python classes.""" + +from typing import TYPE_CHECKING + +_PUBLIC_API = ("cached_property", "under_cached_property") + +__version__ = "0.3.2" +__all__ = () + +# Imports have moved to `propcache.api` in 0.2.0+. +# This module is now a facade for the API. +if TYPE_CHECKING: + from .api import cached_property as cached_property # noqa: F401 + from .api import under_cached_property as under_cached_property # noqa: F401 + + +def _import_facade(attr: str) -> object: + """Import the public API from the `api` module.""" + if attr in _PUBLIC_API: + from . import api # pylint: disable=import-outside-toplevel + + return getattr(api, attr) + raise AttributeError(f"module '{__package__}' has no attribute '{attr}'") + + +def _dir_facade() -> list[str]: + """Include the public API in the module's dir() output.""" + return [*_PUBLIC_API, *globals().keys()] + + +__getattr__ = _import_facade +__dir__ = _dir_facade diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..1e52895c151c952a100eeaab524fea2ef8d68f7e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers.py @@ -0,0 +1,39 @@ +import os +import sys +from typing import TYPE_CHECKING + +__all__ = ("cached_property", "under_cached_property") + + +NO_EXTENSIONS = bool(os.environ.get("PROPCACHE_NO_EXTENSIONS")) # type: bool +if sys.implementation.name != "cpython": + NO_EXTENSIONS = True + + +# isort: off +if TYPE_CHECKING: + from ._helpers_py import cached_property as cached_property_py + from ._helpers_py import under_cached_property as under_cached_property_py + + cached_property = cached_property_py + under_cached_property = under_cached_property_py +elif not NO_EXTENSIONS: # pragma: no branch + try: + from ._helpers_c import cached_property as cached_property_c # type: ignore[attr-defined, unused-ignore] + from ._helpers_c import under_cached_property as under_cached_property_c # type: ignore[attr-defined, unused-ignore] + + cached_property = cached_property_c + under_cached_property = under_cached_property_c + except ImportError: # pragma: no cover + from ._helpers_py import cached_property as cached_property_py + from ._helpers_py import under_cached_property as under_cached_property_py + + cached_property = cached_property_py # type: ignore[assignment, misc] + under_cached_property = under_cached_property_py +else: + from ._helpers_py import cached_property as cached_property_py + from ._helpers_py import under_cached_property as under_cached_property_py + + cached_property = cached_property_py # type: ignore[assignment, misc] + under_cached_property = under_cached_property_py +# isort: on diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7ad4cc3aa36841bb6f04c14a9283533d263978bb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_c.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8473964498e2713eccb1d940450c2ae40882aad9a3245d64540d015f222a255c +size 770704 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_c.pyx b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_c.pyx new file mode 100644 index 0000000000000000000000000000000000000000..84cdd49a4ef458c271f644c640807fdc4faa579b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_c.pyx @@ -0,0 +1,86 @@ +# cython: language_level=3, freethreading_compatible=True +from types import GenericAlias + + +cdef _sentinel = object() + +cdef class under_cached_property: + """Use as a class method decorator. It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + + """ + + cdef readonly object wrapped + cdef object name + + def __init__(self, wrapped): + self.wrapped = wrapped + self.name = wrapped.__name__ + + @property + def __doc__(self): + return self.wrapped.__doc__ + + def __get__(self, inst, owner): + if inst is None: + return self + cdef dict cache = inst._cache + val = cache.get(self.name, _sentinel) + if val is _sentinel: + val = self.wrapped(inst) + cache[self.name] = val + return val + + def __set__(self, inst, value): + raise AttributeError("cached property is read-only") + + __class_getitem__ = classmethod(GenericAlias) + + +cdef class cached_property: + """Use as a class method decorator. It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + + """ + + cdef readonly object func + cdef object name + + def __init__(self, func): + self.func = func + self.name = None + + @property + def __doc__(self): + return self.func.__doc__ + + def __set_name__(self, owner, name): + if self.name is None: + self.name = name + elif name != self.name: + raise TypeError( + "Cannot assign the same cached_property to two different names " + f"({self.name!r} and {name!r})." + ) + + def __get__(self, inst, owner): + if inst is None: + return self + if self.name is None: + raise TypeError( + "Cannot use cached_property instance" + " without calling __set_name__ on it.") + cdef dict cache = inst.__dict__ + val = cache.get(self.name, _sentinel) + if val is _sentinel: + val = self.func(inst) + cache[self.name] = val + return val + + __class_getitem__ = classmethod(GenericAlias) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_py.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_py.py new file mode 100644 index 0000000000000000000000000000000000000000..90432ca1064ff333778689b1265cd7cca91ac347 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/_helpers_py.py @@ -0,0 +1,60 @@ +"""Various helper functions.""" + +import sys +from collections.abc import Mapping +from functools import cached_property +from typing import Any, Callable, Generic, Optional, Protocol, TypeVar, Union, overload + +__all__ = ("under_cached_property", "cached_property") + + +if sys.version_info >= (3, 11): + from typing import Self +else: + Self = Any + +_T = TypeVar("_T") +# We use Mapping to make it possible to use TypedDict, but this isn't +# technically type safe as we need to assign into the dict. +_Cache = TypeVar("_Cache", bound=Mapping[str, Any]) + + +class _CacheImpl(Protocol[_Cache]): + _cache: _Cache + + +class under_cached_property(Generic[_T]): + """Use as a class method decorator. + + It operates almost exactly like + the Python `@property` decorator, but it puts the result of the + method it decorates into the instance dict after the first call, + effectively replacing the function it decorates with an instance + variable. It is, in Python parlance, a data descriptor. + """ + + def __init__(self, wrapped: Callable[[Any], _T]) -> None: + self.wrapped = wrapped + self.__doc__ = wrapped.__doc__ + self.name = wrapped.__name__ + + @overload + def __get__(self, inst: None, owner: Optional[type[object]] = None) -> Self: ... + + @overload + def __get__(self, inst: _CacheImpl[Any], owner: Optional[type[object]] = None) -> _T: ... # type: ignore[misc] + + def __get__( + self, inst: Optional[_CacheImpl[Any]], owner: Optional[type[object]] = None + ) -> Union[_T, Self]: + if inst is None: + return self + try: + return inst._cache[self.name] # type: ignore[no-any-return] + except KeyError: + val = self.wrapped(inst) + inst._cache[self.name] = val + return val + + def __set__(self, inst: _CacheImpl[Any], value: _T) -> None: + raise AttributeError("cached property is read-only") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/api.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/api.py new file mode 100644 index 0000000000000000000000000000000000000000..22389e6337f8f77681b61de5e45d1ae6d474d39b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/api.py @@ -0,0 +1,8 @@ +"""Public API of the property caching library.""" + +from ._helpers import cached_property, under_cached_property + +__all__ = ( + "cached_property", + "under_cached_property", +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/py.typed b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dcf2c804da5e19d617a03a6c68aa128d1d1f89a0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/propcache/py.typed @@ -0,0 +1 @@ +# Placeholder diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/INSTALLER b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/METADATA b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..b1fe93ff44dd7b1cd39276c2b397005a6077978c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/METADATA @@ -0,0 +1,68 @@ +Metadata-Version: 2.4 +Name: typing_extensions +Version: 4.14.1 +Summary: Backported and Experimental Type Hints for Python 3.9+ +Keywords: annotations,backport,checker,checking,function,hinting,hints,type,typechecking,typehinting,typehints,typing +Author-email: "Guido van Rossum, Jukka Lehtosalo, Łukasz Langa, Michael Lee" +Requires-Python: >=3.9 +Description-Content-Type: text/markdown +License-Expression: PSF-2.0 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Environment :: Console +Classifier: Intended Audience :: Developers +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Programming Language :: Python :: 3.14 +Classifier: Topic :: Software Development +License-File: LICENSE +Project-URL: Bug Tracker, https://github.com/python/typing_extensions/issues +Project-URL: Changes, https://github.com/python/typing_extensions/blob/main/CHANGELOG.md +Project-URL: Documentation, https://typing-extensions.readthedocs.io/ +Project-URL: Home, https://github.com/python/typing_extensions +Project-URL: Q & A, https://github.com/python/typing/discussions +Project-URL: Repository, https://github.com/python/typing_extensions + +# Typing Extensions + +[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing) + +[Documentation](https://typing-extensions.readthedocs.io/en/latest/#) – +[PyPI](https://pypi.org/project/typing-extensions/) + +## Overview + +The `typing_extensions` module serves two related purposes: + +- Enable use of new type system features on older Python versions. For example, + `typing.TypeGuard` is new in Python 3.10, but `typing_extensions` allows + users on previous Python versions to use it too. +- Enable experimentation with new type system PEPs before they are accepted and + added to the `typing` module. + +`typing_extensions` is treated specially by static type checkers such as +mypy and pyright. Objects defined in `typing_extensions` are treated the same +way as equivalent forms in `typing`. + +`typing_extensions` uses +[Semantic Versioning](https://semver.org/). The +major version will be incremented only for backwards-incompatible changes. +Therefore, it's safe to depend +on `typing_extensions` like this: `typing_extensions >=x.y, <(x+1)`, +where `x.y` is the first version that includes all features you need. + +## Included items + +See [the documentation](https://typing-extensions.readthedocs.io/en/latest/#) for a +complete listing of module contents. + +## Contributing + +See [CONTRIBUTING.md](https://github.com/python/typing_extensions/blob/main/CONTRIBUTING.md) +for how to contribute to `typing_extensions`. + diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/RECORD b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..944ae23d8b8567922fe17a2a9a0473c5e55a7a12 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/RECORD @@ -0,0 +1,7 @@ +__pycache__/typing_extensions.cpython-312.pyc,, +typing_extensions-4.14.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +typing_extensions-4.14.1.dist-info/METADATA,sha256=8LS3enF0w3KyL4WYimlFfskcnkARg-sv_L6tHbPMS5s,2995 +typing_extensions-4.14.1.dist-info/RECORD,, +typing_extensions-4.14.1.dist-info/WHEEL,sha256=G2gURzTEtmeR8nrdXUJfNiB3VYVxigPQ-bEQujpNiNs,82 +typing_extensions-4.14.1.dist-info/licenses/LICENSE,sha256=Oy-B_iHRgcSZxZolbI4ZaEVdZonSaaqFNzv7avQdo78,13936 +typing_extensions.py,sha256=Fh0lt5ZCgnzs7tyAhHOAfL0Zr829KYUxiR543ClwVgw,157408 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/WHEEL b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..d8b9936dad9ab2513fa6979f411560d3b6b57e37 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions-4.14.1.dist-info/WHEEL @@ -0,0 +1,4 @@ +Wheel-Version: 1.0 +Generator: flit 3.12.0 +Root-Is-Purelib: true +Tag: py3-none-any diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..efa09d55236d7607a0a869eb7ab9ef4d6254231f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/typing_extensions.py @@ -0,0 +1,4244 @@ +import abc +import builtins +import collections +import collections.abc +import contextlib +import enum +import functools +import inspect +import io +import keyword +import operator +import sys +import types as _types +import typing +import warnings + +if sys.version_info >= (3, 14): + import annotationlib + +__all__ = [ + # Super-special typing primitives. + 'Any', + 'ClassVar', + 'Concatenate', + 'Final', + 'LiteralString', + 'ParamSpec', + 'ParamSpecArgs', + 'ParamSpecKwargs', + 'Self', + 'Type', + 'TypeVar', + 'TypeVarTuple', + 'Unpack', + + # ABCs (from collections.abc). + 'Awaitable', + 'AsyncIterator', + 'AsyncIterable', + 'Coroutine', + 'AsyncGenerator', + 'AsyncContextManager', + 'Buffer', + 'ChainMap', + + # Concrete collection types. + 'ContextManager', + 'Counter', + 'Deque', + 'DefaultDict', + 'NamedTuple', + 'OrderedDict', + 'TypedDict', + + # Structural checks, a.k.a. protocols. + 'SupportsAbs', + 'SupportsBytes', + 'SupportsComplex', + 'SupportsFloat', + 'SupportsIndex', + 'SupportsInt', + 'SupportsRound', + 'Reader', + 'Writer', + + # One-off things. + 'Annotated', + 'assert_never', + 'assert_type', + 'clear_overloads', + 'dataclass_transform', + 'deprecated', + 'Doc', + 'evaluate_forward_ref', + 'get_overloads', + 'final', + 'Format', + 'get_annotations', + 'get_args', + 'get_origin', + 'get_original_bases', + 'get_protocol_members', + 'get_type_hints', + 'IntVar', + 'is_protocol', + 'is_typeddict', + 'Literal', + 'NewType', + 'overload', + 'override', + 'Protocol', + 'Sentinel', + 'reveal_type', + 'runtime', + 'runtime_checkable', + 'Text', + 'TypeAlias', + 'TypeAliasType', + 'TypeForm', + 'TypeGuard', + 'TypeIs', + 'TYPE_CHECKING', + 'Never', + 'NoReturn', + 'ReadOnly', + 'Required', + 'NotRequired', + 'NoDefault', + 'NoExtraItems', + + # Pure aliases, have always been in typing + 'AbstractSet', + 'AnyStr', + 'BinaryIO', + 'Callable', + 'Collection', + 'Container', + 'Dict', + 'ForwardRef', + 'FrozenSet', + 'Generator', + 'Generic', + 'Hashable', + 'IO', + 'ItemsView', + 'Iterable', + 'Iterator', + 'KeysView', + 'List', + 'Mapping', + 'MappingView', + 'Match', + 'MutableMapping', + 'MutableSequence', + 'MutableSet', + 'Optional', + 'Pattern', + 'Reversible', + 'Sequence', + 'Set', + 'Sized', + 'TextIO', + 'Tuple', + 'Union', + 'ValuesView', + 'cast', + 'no_type_check', + 'no_type_check_decorator', +] + +# for backward compatibility +PEP_560 = True +GenericMeta = type +_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta") + +# Added with bpo-45166 to 3.10.1+ and some 3.9 versions +_FORWARD_REF_HAS_CLASS = "__forward_is_class__" in typing.ForwardRef.__slots__ + +# The functions below are modified copies of typing internal helpers. +# They are needed by _ProtocolMeta and they provide support for PEP 646. + + +class _Sentinel: + def __repr__(self): + return "" + + +_marker = _Sentinel() + + +if sys.version_info >= (3, 10): + def _should_collect_from_parameters(t): + return isinstance( + t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType) + ) +else: + def _should_collect_from_parameters(t): + return isinstance(t, (typing._GenericAlias, _types.GenericAlias)) + + +NoReturn = typing.NoReturn + +# Some unconstrained type variables. These are used by the container types. +# (These are not for export.) +T = typing.TypeVar('T') # Any type. +KT = typing.TypeVar('KT') # Key type. +VT = typing.TypeVar('VT') # Value type. +T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. +T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. + + +if sys.version_info >= (3, 11): + from typing import Any +else: + + class _AnyMeta(type): + def __instancecheck__(self, obj): + if self is Any: + raise TypeError("typing_extensions.Any cannot be used with isinstance()") + return super().__instancecheck__(obj) + + def __repr__(self): + if self is Any: + return "typing_extensions.Any" + return super().__repr__() + + class Any(metaclass=_AnyMeta): + """Special type indicating an unconstrained type. + - Any is compatible with every type. + - Any assumed to have all methods. + - All values assumed to be instances of Any. + Note that all the above statements are true from the point of view of + static type checkers. At runtime, Any should not be used with instance + checks. + """ + def __new__(cls, *args, **kwargs): + if cls is Any: + raise TypeError("Any cannot be instantiated") + return super().__new__(cls, *args, **kwargs) + + +ClassVar = typing.ClassVar + +# Vendored from cpython typing._SpecialFrom +# Having a separate class means that instances will not be rejected by +# typing._type_check. +class _SpecialForm(typing._Final, _root=True): + __slots__ = ('_name', '__doc__', '_getitem') + + def __init__(self, getitem): + self._getitem = getitem + self._name = getitem.__name__ + self.__doc__ = getitem.__doc__ + + def __getattr__(self, item): + if item in {'__name__', '__qualname__'}: + return self._name + + raise AttributeError(item) + + def __mro_entries__(self, bases): + raise TypeError(f"Cannot subclass {self!r}") + + def __repr__(self): + return f'typing_extensions.{self._name}' + + def __reduce__(self): + return self._name + + def __call__(self, *args, **kwds): + raise TypeError(f"Cannot instantiate {self!r}") + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + def __instancecheck__(self, obj): + raise TypeError(f"{self} cannot be used with isinstance()") + + def __subclasscheck__(self, cls): + raise TypeError(f"{self} cannot be used with issubclass()") + + @typing._tp_cache + def __getitem__(self, parameters): + return self._getitem(self, parameters) + + +# Note that inheriting from this class means that the object will be +# rejected by typing._type_check, so do not use it if the special form +# is arguably valid as a type by itself. +class _ExtensionsSpecialForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + +Final = typing.Final + +if sys.version_info >= (3, 11): + final = typing.final +else: + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + +def IntVar(name): + return typing.TypeVar(name) + + +# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8 +if sys.version_info >= (3, 10, 1): + Literal = typing.Literal +else: + def _flatten_literal_params(parameters): + """An internal helper for Literal creation: flatten Literals among parameters""" + params = [] + for p in parameters: + if isinstance(p, _LiteralGenericAlias): + params.extend(p.__args__) + else: + params.append(p) + return tuple(params) + + def _value_and_type_iter(params): + for p in params: + yield p, type(p) + + class _LiteralGenericAlias(typing._GenericAlias, _root=True): + def __eq__(self, other): + if not isinstance(other, _LiteralGenericAlias): + return NotImplemented + these_args_deduped = set(_value_and_type_iter(self.__args__)) + other_args_deduped = set(_value_and_type_iter(other.__args__)) + return these_args_deduped == other_args_deduped + + def __hash__(self): + return hash(frozenset(_value_and_type_iter(self.__args__))) + + class _LiteralForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, doc: str): + self._name = 'Literal' + self._doc = self.__doc__ = doc + + def __getitem__(self, parameters): + if not isinstance(parameters, tuple): + parameters = (parameters,) + + parameters = _flatten_literal_params(parameters) + + val_type_pairs = list(_value_and_type_iter(parameters)) + try: + deduped_pairs = set(val_type_pairs) + except TypeError: + # unhashable parameters + pass + else: + # similar logic to typing._deduplicate on Python 3.9+ + if len(deduped_pairs) < len(val_type_pairs): + new_parameters = [] + for pair in val_type_pairs: + if pair in deduped_pairs: + new_parameters.append(pair[0]) + deduped_pairs.remove(pair) + assert not deduped_pairs, deduped_pairs + parameters = tuple(new_parameters) + + return _LiteralGenericAlias(self, parameters) + + Literal = _LiteralForm(doc="""\ + A type that can be used to indicate to type checkers + that the corresponding value has a value literally equivalent + to the provided parameter. For example: + + var: Literal[4] = 4 + + The type checker understands that 'var' is literally equal to + the value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime + checking verifying that the parameter is actually a value + instead of a type.""") + + +_overload_dummy = typing._overload_dummy + + +if hasattr(typing, "get_overloads"): # 3.11+ + overload = typing.overload + get_overloads = typing.get_overloads + clear_overloads = typing.clear_overloads +else: + # {module: {qualname: {firstlineno: func}}} + _overload_registry = collections.defaultdict( + functools.partial(collections.defaultdict, dict) + ) + + def overload(func): + """Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + + The overloads for a function can be retrieved at runtime using the + get_overloads() function. + """ + # classmethod and staticmethod + f = getattr(func, "__func__", func) + try: + _overload_registry[f.__module__][f.__qualname__][ + f.__code__.co_firstlineno + ] = func + except AttributeError: + # Not a normal function; ignore. + pass + return _overload_dummy + + def get_overloads(func): + """Return all defined overloads for *func* as a sequence.""" + # classmethod and staticmethod + f = getattr(func, "__func__", func) + if f.__module__ not in _overload_registry: + return [] + mod_dict = _overload_registry[f.__module__] + if f.__qualname__ not in mod_dict: + return [] + return list(mod_dict[f.__qualname__].values()) + + def clear_overloads(): + """Clear all overloads in the registry.""" + _overload_registry.clear() + + +# This is not a real generic class. Don't use outside annotations. +Type = typing.Type + +# Various ABCs mimicking those in collections.abc. +# A few are simply re-exported for completeness. +Awaitable = typing.Awaitable +Coroutine = typing.Coroutine +AsyncIterable = typing.AsyncIterable +AsyncIterator = typing.AsyncIterator +Deque = typing.Deque +DefaultDict = typing.DefaultDict +OrderedDict = typing.OrderedDict +Counter = typing.Counter +ChainMap = typing.ChainMap +Text = typing.Text +TYPE_CHECKING = typing.TYPE_CHECKING + + +if sys.version_info >= (3, 13, 0, "beta"): + from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator +else: + def _is_dunder(attr): + return attr.startswith('__') and attr.endswith('__') + + + class _SpecialGenericAlias(typing._SpecialGenericAlias, _root=True): + def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()): + super().__init__(origin, nparams, inst=inst, name=name) + self._defaults = defaults + + def __setattr__(self, attr, val): + allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'} + if _is_dunder(attr) or attr in allowed_attrs: + object.__setattr__(self, attr, val) + else: + setattr(self.__origin__, attr, val) + + @typing._tp_cache + def __getitem__(self, params): + if not isinstance(params, tuple): + params = (params,) + msg = "Parameters to generic types must be types." + params = tuple(typing._type_check(p, msg) for p in params) + if ( + self._defaults + and len(params) < self._nparams + and len(params) + len(self._defaults) >= self._nparams + ): + params = (*params, *self._defaults[len(params) - self._nparams:]) + actual_len = len(params) + + if actual_len != self._nparams: + if self._defaults: + expected = f"at least {self._nparams - len(self._defaults)}" + else: + expected = str(self._nparams) + if not self._nparams: + raise TypeError(f"{self} is not a generic class") + raise TypeError( + f"Too {'many' if actual_len > self._nparams else 'few'}" + f" arguments for {self};" + f" actual {actual_len}, expected {expected}" + ) + return self.copy_with(params) + + _NoneType = type(None) + Generator = _SpecialGenericAlias( + collections.abc.Generator, 3, defaults=(_NoneType, _NoneType) + ) + AsyncGenerator = _SpecialGenericAlias( + collections.abc.AsyncGenerator, 2, defaults=(_NoneType,) + ) + ContextManager = _SpecialGenericAlias( + contextlib.AbstractContextManager, + 2, + name="ContextManager", + defaults=(typing.Optional[bool],) + ) + AsyncContextManager = _SpecialGenericAlias( + contextlib.AbstractAsyncContextManager, + 2, + name="AsyncContextManager", + defaults=(typing.Optional[bool],) + ) + + +_PROTO_ALLOWLIST = { + 'collections.abc': [ + 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable', + 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer', + ], + 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'], + 'typing_extensions': ['Buffer'], +} + + +_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | { + "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__", + "__final__", +} + + +def _get_protocol_attrs(cls): + attrs = set() + for base in cls.__mro__[:-1]: # without object + if base.__name__ in {'Protocol', 'Generic'}: + continue + annotations = getattr(base, '__annotations__', {}) + for attr in (*base.__dict__, *annotations): + if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS): + attrs.add(attr) + return attrs + + +def _caller(depth=1, default='__main__'): + try: + return sys._getframemodulename(depth + 1) or default + except AttributeError: # For platforms without _getframemodulename() + pass + try: + return sys._getframe(depth + 1).f_globals.get('__name__', default) + except (AttributeError, ValueError): # For platforms without _getframe() + pass + return None + + +# `__match_args__` attribute was removed from protocol members in 3.13, +# we want to backport this change to older Python versions. +if sys.version_info >= (3, 13): + Protocol = typing.Protocol +else: + def _allow_reckless_class_checks(depth=2): + """Allow instance and class checks for special stdlib modules. + The abc and functools modules indiscriminately call isinstance() and + issubclass() on the whole MRO of a user class, which may contain protocols. + """ + return _caller(depth) in {'abc', 'functools', None} + + def _no_init(self, *args, **kwargs): + if type(self)._is_protocol: + raise TypeError('Protocols cannot be instantiated') + + def _type_check_issubclass_arg_1(arg): + """Raise TypeError if `arg` is not an instance of `type` + in `issubclass(arg, )`. + + In most cases, this is verified by type.__subclasscheck__. + Checking it again unnecessarily would slow down issubclass() checks, + so, we don't perform this check unless we absolutely have to. + + For various error paths, however, + we want to ensure that *this* error message is shown to the user + where relevant, rather than a typing.py-specific error message. + """ + if not isinstance(arg, type): + # Same error message as for issubclass(1, int). + raise TypeError('issubclass() arg 1 must be a class') + + # Inheriting from typing._ProtocolMeta isn't actually desirable, + # but is necessary to allow typing.Protocol and typing_extensions.Protocol + # to mix without getting TypeErrors about "metaclass conflict" + class _ProtocolMeta(type(typing.Protocol)): + # This metaclass is somewhat unfortunate, + # but is necessary for several reasons... + # + # NOTE: DO NOT call super() in any methods in this class + # That would call the methods on typing._ProtocolMeta on Python <=3.11 + # and those are slow + def __new__(mcls, name, bases, namespace, **kwargs): + if name == "Protocol" and len(bases) < 2: + pass + elif {Protocol, typing.Protocol} & set(bases): + for base in bases: + if not ( + base in {object, typing.Generic, Protocol, typing.Protocol} + or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, []) + or is_protocol(base) + ): + raise TypeError( + f"Protocols can only inherit from other protocols, " + f"got {base!r}" + ) + return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs) + + def __init__(cls, *args, **kwargs): + abc.ABCMeta.__init__(cls, *args, **kwargs) + if getattr(cls, "_is_protocol", False): + cls.__protocol_attrs__ = _get_protocol_attrs(cls) + + def __subclasscheck__(cls, other): + if cls is Protocol: + return type.__subclasscheck__(cls, other) + if ( + getattr(cls, '_is_protocol', False) + and not _allow_reckless_class_checks() + ): + if not getattr(cls, '_is_runtime_protocol', False): + _type_check_issubclass_arg_1(other) + raise TypeError( + "Instance and class checks can only be used with " + "@runtime_checkable protocols" + ) + if ( + # this attribute is set by @runtime_checkable: + cls.__non_callable_proto_members__ + and cls.__dict__.get("__subclasshook__") is _proto_hook + ): + _type_check_issubclass_arg_1(other) + non_method_attrs = sorted(cls.__non_callable_proto_members__) + raise TypeError( + "Protocols with non-method members don't support issubclass()." + f" Non-method members: {str(non_method_attrs)[1:-1]}." + ) + return abc.ABCMeta.__subclasscheck__(cls, other) + + def __instancecheck__(cls, instance): + # We need this method for situations where attributes are + # assigned in __init__. + if cls is Protocol: + return type.__instancecheck__(cls, instance) + if not getattr(cls, "_is_protocol", False): + # i.e., it's a concrete subclass of a protocol + return abc.ABCMeta.__instancecheck__(cls, instance) + + if ( + not getattr(cls, '_is_runtime_protocol', False) and + not _allow_reckless_class_checks() + ): + raise TypeError("Instance and class checks can only be used with" + " @runtime_checkable protocols") + + if abc.ABCMeta.__instancecheck__(cls, instance): + return True + + for attr in cls.__protocol_attrs__: + try: + val = inspect.getattr_static(instance, attr) + except AttributeError: + break + # this attribute is set by @runtime_checkable: + if val is None and attr not in cls.__non_callable_proto_members__: + break + else: + return True + + return False + + def __eq__(cls, other): + # Hack so that typing.Generic.__class_getitem__ + # treats typing_extensions.Protocol + # as equivalent to typing.Protocol + if abc.ABCMeta.__eq__(cls, other) is True: + return True + return cls is Protocol and other is typing.Protocol + + # This has to be defined, or the abc-module cache + # complains about classes with this metaclass being unhashable, + # if we define only __eq__! + def __hash__(cls) -> int: + return type.__hash__(cls) + + @classmethod + def _proto_hook(cls, other): + if not cls.__dict__.get('_is_protocol', False): + return NotImplemented + + for attr in cls.__protocol_attrs__: + for base in other.__mro__: + # Check if the members appears in the class dictionary... + if attr in base.__dict__: + if base.__dict__[attr] is None: + return NotImplemented + break + + # ...or in annotations, if it is a sub-protocol. + annotations = getattr(base, '__annotations__', {}) + if ( + isinstance(annotations, collections.abc.Mapping) + and attr in annotations + and is_protocol(other) + ): + break + else: + return NotImplemented + return True + + class Protocol(typing.Generic, metaclass=_ProtocolMeta): + __doc__ = typing.Protocol.__doc__ + __slots__ = () + _is_protocol = True + _is_runtime_protocol = False + + def __init_subclass__(cls, *args, **kwargs): + super().__init_subclass__(*args, **kwargs) + + # Determine if this is a protocol or a concrete subclass. + if not cls.__dict__.get('_is_protocol', False): + cls._is_protocol = any(b is Protocol for b in cls.__bases__) + + # Set (or override) the protocol subclass hook. + if '__subclasshook__' not in cls.__dict__: + cls.__subclasshook__ = _proto_hook + + # Prohibit instantiation for protocol classes + if cls._is_protocol and cls.__init__ is Protocol.__init__: + cls.__init__ = _no_init + + +if sys.version_info >= (3, 13): + runtime_checkable = typing.runtime_checkable +else: + def runtime_checkable(cls): + """Mark a protocol class as a runtime protocol. + + Such protocol can be used with isinstance() and issubclass(). + Raise TypeError if applied to a non-protocol class. + This allows a simple-minded structural check very similar to + one trick ponies in collections.abc such as Iterable. + + For example:: + + @runtime_checkable + class Closable(Protocol): + def close(self): ... + + assert isinstance(open('/some/file'), Closable) + + Warning: this will check only the presence of the required methods, + not their type signatures! + """ + if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False): + raise TypeError(f'@runtime_checkable can be only applied to protocol classes,' + f' got {cls!r}') + cls._is_runtime_protocol = True + + # typing.Protocol classes on <=3.11 break if we execute this block, + # because typing.Protocol classes on <=3.11 don't have a + # `__protocol_attrs__` attribute, and this block relies on the + # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+ + # break if we *don't* execute this block, because *they* assume that all + # protocol classes have a `__non_callable_proto_members__` attribute + # (which this block sets) + if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2): + # PEP 544 prohibits using issubclass() + # with protocols that have non-method members. + # See gh-113320 for why we compute this attribute here, + # rather than in `_ProtocolMeta.__init__` + cls.__non_callable_proto_members__ = set() + for attr in cls.__protocol_attrs__: + try: + is_callable = callable(getattr(cls, attr, None)) + except Exception as e: + raise TypeError( + f"Failed to determine whether protocol member {attr!r} " + "is a method member" + ) from e + else: + if not is_callable: + cls.__non_callable_proto_members__.add(attr) + + return cls + + +# The "runtime" alias exists for backwards compatibility. +runtime = runtime_checkable + + +# Our version of runtime-checkable protocols is faster on Python <=3.11 +if sys.version_info >= (3, 12): + SupportsInt = typing.SupportsInt + SupportsFloat = typing.SupportsFloat + SupportsComplex = typing.SupportsComplex + SupportsBytes = typing.SupportsBytes + SupportsIndex = typing.SupportsIndex + SupportsAbs = typing.SupportsAbs + SupportsRound = typing.SupportsRound +else: + @runtime_checkable + class SupportsInt(Protocol): + """An ABC with one abstract method __int__.""" + __slots__ = () + + @abc.abstractmethod + def __int__(self) -> int: + pass + + @runtime_checkable + class SupportsFloat(Protocol): + """An ABC with one abstract method __float__.""" + __slots__ = () + + @abc.abstractmethod + def __float__(self) -> float: + pass + + @runtime_checkable + class SupportsComplex(Protocol): + """An ABC with one abstract method __complex__.""" + __slots__ = () + + @abc.abstractmethod + def __complex__(self) -> complex: + pass + + @runtime_checkable + class SupportsBytes(Protocol): + """An ABC with one abstract method __bytes__.""" + __slots__ = () + + @abc.abstractmethod + def __bytes__(self) -> bytes: + pass + + @runtime_checkable + class SupportsIndex(Protocol): + __slots__ = () + + @abc.abstractmethod + def __index__(self) -> int: + pass + + @runtime_checkable + class SupportsAbs(Protocol[T_co]): + """ + An ABC with one abstract method __abs__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __abs__(self) -> T_co: + pass + + @runtime_checkable + class SupportsRound(Protocol[T_co]): + """ + An ABC with one abstract method __round__ that is covariant in its return type. + """ + __slots__ = () + + @abc.abstractmethod + def __round__(self, ndigits: int = 0) -> T_co: + pass + + +if hasattr(io, "Reader") and hasattr(io, "Writer"): + Reader = io.Reader + Writer = io.Writer +else: + @runtime_checkable + class Reader(Protocol[T_co]): + """Protocol for simple I/O reader instances. + + This protocol only supports blocking I/O. + """ + + __slots__ = () + + @abc.abstractmethod + def read(self, size: int = ..., /) -> T_co: + """Read data from the input stream and return it. + + If *size* is specified, at most *size* items (bytes/characters) will be + read. + """ + + @runtime_checkable + class Writer(Protocol[T_contra]): + """Protocol for simple I/O writer instances. + + This protocol only supports blocking I/O. + """ + + __slots__ = () + + @abc.abstractmethod + def write(self, data: T_contra, /) -> int: + """Write *data* to the output stream and return the number of items written.""" # noqa: E501 + + +_NEEDS_SINGLETONMETA = ( + not hasattr(typing, "NoDefault") or not hasattr(typing, "NoExtraItems") +) + +if _NEEDS_SINGLETONMETA: + class SingletonMeta(type): + def __setattr__(cls, attr, value): + # TypeError is consistent with the behavior of NoneType + raise TypeError( + f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}" + ) + + +if hasattr(typing, "NoDefault"): + NoDefault = typing.NoDefault +else: + class NoDefaultType(metaclass=SingletonMeta): + """The type of the NoDefault singleton.""" + + __slots__ = () + + def __new__(cls): + return globals().get("NoDefault") or object.__new__(cls) + + def __repr__(self): + return "typing_extensions.NoDefault" + + def __reduce__(self): + return "NoDefault" + + NoDefault = NoDefaultType() + del NoDefaultType + +if hasattr(typing, "NoExtraItems"): + NoExtraItems = typing.NoExtraItems +else: + class NoExtraItemsType(metaclass=SingletonMeta): + """The type of the NoExtraItems singleton.""" + + __slots__ = () + + def __new__(cls): + return globals().get("NoExtraItems") or object.__new__(cls) + + def __repr__(self): + return "typing_extensions.NoExtraItems" + + def __reduce__(self): + return "NoExtraItems" + + NoExtraItems = NoExtraItemsType() + del NoExtraItemsType + +if _NEEDS_SINGLETONMETA: + del SingletonMeta + + +# Update this to something like >=3.13.0b1 if and when +# PEP 728 is implemented in CPython +_PEP_728_IMPLEMENTED = False + +if _PEP_728_IMPLEMENTED: + # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" + # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 + # The standard library TypedDict below Python 3.11 does not store runtime + # information about optional and required keys when using Required or NotRequired. + # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11. + # Aaaand on 3.12 we add __orig_bases__ to TypedDict + # to enable better runtime introspection. + # On 3.13 we deprecate some odd ways of creating TypedDicts. + # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier. + # PEP 728 (still pending) makes more changes. + TypedDict = typing.TypedDict + _TypedDictMeta = typing._TypedDictMeta + is_typeddict = typing.is_typeddict +else: + # 3.10.0 and later + _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters + + def _get_typeddict_qualifiers(annotation_type): + while True: + annotation_origin = get_origin(annotation_type) + if annotation_origin is Annotated: + annotation_args = get_args(annotation_type) + if annotation_args: + annotation_type = annotation_args[0] + else: + break + elif annotation_origin is Required: + yield Required + annotation_type, = get_args(annotation_type) + elif annotation_origin is NotRequired: + yield NotRequired + annotation_type, = get_args(annotation_type) + elif annotation_origin is ReadOnly: + yield ReadOnly + annotation_type, = get_args(annotation_type) + else: + break + + class _TypedDictMeta(type): + + def __new__(cls, name, bases, ns, *, total=True, closed=None, + extra_items=NoExtraItems): + """Create new typed dict class object. + + This method is called when TypedDict is subclassed, + or when TypedDict is instantiated. This way + TypedDict supports all three syntax forms described in its docstring. + Subclasses and instances of TypedDict return actual dictionaries. + """ + for base in bases: + if type(base) is not _TypedDictMeta and base is not typing.Generic: + raise TypeError('cannot inherit from both a TypedDict type ' + 'and a non-TypedDict base class') + if closed is not None and extra_items is not NoExtraItems: + raise TypeError(f"Cannot combine closed={closed!r} and extra_items") + + if any(issubclass(b, typing.Generic) for b in bases): + generic_base = (typing.Generic,) + else: + generic_base = () + + ns_annotations = ns.pop('__annotations__', None) + + # typing.py generally doesn't let you inherit from plain Generic, unless + # the name of the class happens to be "Protocol" + tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns) + tp_dict.__name__ = name + if tp_dict.__qualname__ == "Protocol": + tp_dict.__qualname__ = name + + if not hasattr(tp_dict, '__orig_bases__'): + tp_dict.__orig_bases__ = bases + + annotations = {} + own_annotate = None + if ns_annotations is not None: + own_annotations = ns_annotations + elif sys.version_info >= (3, 14): + if hasattr(annotationlib, "get_annotate_from_class_namespace"): + own_annotate = annotationlib.get_annotate_from_class_namespace(ns) + else: + # 3.14.0a7 and earlier + own_annotate = ns.get("__annotate__") + if own_annotate is not None: + own_annotations = annotationlib.call_annotate_function( + own_annotate, Format.FORWARDREF, owner=tp_dict + ) + else: + own_annotations = {} + else: + own_annotations = {} + msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" + if _TAKES_MODULE: + own_checked_annotations = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own_annotations.items() + } + else: + own_checked_annotations = { + n: typing._type_check(tp, msg) + for n, tp in own_annotations.items() + } + required_keys = set() + optional_keys = set() + readonly_keys = set() + mutable_keys = set() + extra_items_type = extra_items + + for base in bases: + base_dict = base.__dict__ + + if sys.version_info <= (3, 14): + annotations.update(base_dict.get('__annotations__', {})) + required_keys.update(base_dict.get('__required_keys__', ())) + optional_keys.update(base_dict.get('__optional_keys__', ())) + readonly_keys.update(base_dict.get('__readonly_keys__', ())) + mutable_keys.update(base_dict.get('__mutable_keys__', ())) + + # This was specified in an earlier version of PEP 728. Support + # is retained for backwards compatibility, but only for Python + # 3.13 and lower. + if (closed and sys.version_info < (3, 14) + and "__extra_items__" in own_checked_annotations): + annotation_type = own_checked_annotations.pop("__extra_items__") + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + if Required in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "Required" + ) + if NotRequired in qualifiers: + raise TypeError( + "Special key __extra_items__ does not support " + "NotRequired" + ) + extra_items_type = annotation_type + + annotations.update(own_checked_annotations) + for annotation_key, annotation_type in own_checked_annotations.items(): + qualifiers = set(_get_typeddict_qualifiers(annotation_type)) + + if Required in qualifiers: + required_keys.add(annotation_key) + elif NotRequired in qualifiers: + optional_keys.add(annotation_key) + elif total: + required_keys.add(annotation_key) + else: + optional_keys.add(annotation_key) + if ReadOnly in qualifiers: + mutable_keys.discard(annotation_key) + readonly_keys.add(annotation_key) + else: + mutable_keys.add(annotation_key) + readonly_keys.discard(annotation_key) + + if sys.version_info >= (3, 14): + def __annotate__(format): + annos = {} + for base in bases: + if base is Generic: + continue + base_annotate = base.__annotate__ + if base_annotate is None: + continue + base_annos = annotationlib.call_annotate_function( + base_annotate, format, owner=base) + annos.update(base_annos) + if own_annotate is not None: + own = annotationlib.call_annotate_function( + own_annotate, format, owner=tp_dict) + if format != Format.STRING: + own = { + n: typing._type_check(tp, msg, module=tp_dict.__module__) + for n, tp in own.items() + } + elif format == Format.STRING: + own = annotationlib.annotations_to_string(own_annotations) + elif format in (Format.FORWARDREF, Format.VALUE): + own = own_checked_annotations + else: + raise NotImplementedError(format) + annos.update(own) + return annos + + tp_dict.__annotate__ = __annotate__ + else: + tp_dict.__annotations__ = annotations + tp_dict.__required_keys__ = frozenset(required_keys) + tp_dict.__optional_keys__ = frozenset(optional_keys) + tp_dict.__readonly_keys__ = frozenset(readonly_keys) + tp_dict.__mutable_keys__ = frozenset(mutable_keys) + tp_dict.__total__ = total + tp_dict.__closed__ = closed + tp_dict.__extra_items__ = extra_items_type + return tp_dict + + __call__ = dict # static method + + def __subclasscheck__(cls, other): + # Typed dicts are only for static structural subtyping. + raise TypeError('TypedDict does not support instance and class checks') + + __instancecheck__ = __subclasscheck__ + + _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {}) + + def _create_typeddict( + typename, + fields, + /, + *, + typing_is_inline, + total, + closed, + extra_items, + **kwargs, + ): + if fields is _marker or fields is None: + if fields is _marker: + deprecated_thing = ( + "Failing to pass a value for the 'fields' parameter" + ) + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + + example = f"`{typename} = TypedDict({typename!r}, {{}})`" + deprecation_msg = ( + f"{deprecated_thing} is deprecated and will be disallowed in " + "Python 3.15. To create a TypedDict class with 0 fields " + "using the functional syntax, pass an empty dictionary, e.g. " + ) + example + "." + warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2) + # Support a field called "closed" + if closed is not False and closed is not True and closed is not None: + kwargs["closed"] = closed + closed = None + # Or "extra_items" + if extra_items is not NoExtraItems: + kwargs["extra_items"] = extra_items + extra_items = NoExtraItems + fields = kwargs + elif kwargs: + raise TypeError("TypedDict takes either a dict or keyword arguments," + " but not both") + if kwargs: + if sys.version_info >= (3, 13): + raise TypeError("TypedDict takes no keyword arguments") + warnings.warn( + "The kwargs-based syntax for TypedDict definitions is deprecated " + "in Python 3.11, will be removed in Python 3.13, and may not be " + "understood by third-party type checkers.", + DeprecationWarning, + stacklevel=2, + ) + + ns = {'__annotations__': dict(fields)} + module = _caller(depth=4 if typing_is_inline else 2) + if module is not None: + # Setting correct module is necessary to make typed dict classes + # pickleable. + ns['__module__'] = module + + td = _TypedDictMeta(typename, (), ns, total=total, closed=closed, + extra_items=extra_items) + td.__orig_bases__ = (TypedDict,) + return td + + class _TypedDictSpecialForm(_SpecialForm, _root=True): + def __call__( + self, + typename, + fields=_marker, + /, + *, + total=True, + closed=None, + extra_items=NoExtraItems, + **kwargs + ): + return _create_typeddict( + typename, + fields, + typing_is_inline=False, + total=total, + closed=closed, + extra_items=extra_items, + **kwargs, + ) + + def __mro_entries__(self, bases): + return (_TypedDict,) + + @_TypedDictSpecialForm + def TypedDict(self, args): + """A simple typed namespace. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type such that a type checker will expect all + instances to have a certain set of keys, where each key is + associated with a value of a consistent type. This expectation + is not checked at runtime. + + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via the Point2D.__annotations__ dict, and + the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. + TypedDict supports an additional equivalent form:: + + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + By default, all keys must be present in a TypedDict. It is possible + to override this by specifying totality:: + + class Point2D(TypedDict, total=False): + x: int + y: int + + This means that a Point2D TypedDict can have any of the keys omitted. A type + checker is only expected to support a literal False or True as the value of + the total argument. True is the default, and makes all items defined in the + class body be required. + + The Required and NotRequired special forms can also be used to mark + individual keys as being required or not required:: + + class Point2D(TypedDict): + x: int # the "x" key must always be present (Required is the default) + y: NotRequired[int] # the "y" key can be omitted + + See PEP 655 for more details on Required and NotRequired. + """ + # This runs when creating inline TypedDicts: + if not isinstance(args, dict): + raise TypeError( + "TypedDict[...] should be used with a single dict argument" + ) + + return _create_typeddict( + "", + args, + typing_is_inline=True, + total=True, + closed=True, + extra_items=NoExtraItems, + ) + + _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta) + + def is_typeddict(tp): + """Check if an annotation is a TypedDict class + + For example:: + class Film(TypedDict): + title: str + year: int + + is_typeddict(Film) # => True + is_typeddict(Union[list, str]) # => False + """ + return isinstance(tp, _TYPEDDICT_TYPES) + + +if hasattr(typing, "assert_type"): + assert_type = typing.assert_type + +else: + def assert_type(val, typ, /): + """Assert (to the type checker) that the value is of the given type. + + When the type checker encounters a call to assert_type(), it + emits an error if the value is not of the specified type:: + + def greet(name: str) -> None: + assert_type(name, str) # ok + assert_type(name, int) # type checker error + + At runtime this returns the first argument unchanged and otherwise + does nothing. + """ + return val + + +if hasattr(typing, "ReadOnly"): # 3.13+ + get_type_hints = typing.get_type_hints +else: # <=3.13 + # replaces _strip_annotations() + def _strip_extras(t): + """Strips Annotated, Required and NotRequired from a given type.""" + if isinstance(t, typing._AnnotatedAlias): + return _strip_extras(t.__origin__) + if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly): + return _strip_extras(t.__args__[0]) + if isinstance(t, typing._GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return t.copy_with(stripped_args) + if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return _types.GenericAlias(t.__origin__, stripped_args) + if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType): + stripped_args = tuple(_strip_extras(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + return functools.reduce(operator.or_, stripped_args) + + return t + + def get_type_hints(obj, globalns=None, localns=None, include_extras=False): + """Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, adds Optional[t] if a + default value equal to None is set and recursively replaces all + 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' + (unless 'include_extras=True'). + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + """ + hint = typing.get_type_hints( + obj, globalns=globalns, localns=localns, include_extras=True + ) + if sys.version_info < (3, 11): + _clean_optional(obj, hint, globalns, localns) + if include_extras: + return hint + return {k: _strip_extras(t) for k, t in hint.items()} + + _NoneType = type(None) + + def _could_be_inserted_optional(t): + """detects Union[..., None] pattern""" + if not isinstance(t, typing._UnionGenericAlias): + return False + # Assume if last argument is not None they are user defined + if t.__args__[-1] is not _NoneType: + return False + return True + + # < 3.11 + def _clean_optional(obj, hints, globalns=None, localns=None): + # reverts injected Union[..., None] cases from typing.get_type_hints + # when a None default value is used. + # see https://github.com/python/typing_extensions/issues/310 + if not hints or isinstance(obj, type): + return + defaults = typing._get_defaults(obj) # avoid accessing __annotations___ + if not defaults: + return + original_hints = obj.__annotations__ + for name, value in hints.items(): + # Not a Union[..., None] or replacement conditions not fullfilled + if (not _could_be_inserted_optional(value) + or name not in defaults + or defaults[name] is not None + ): + continue + original_value = original_hints[name] + # value=NoneType should have caused a skip above but check for safety + if original_value is None: + original_value = _NoneType + # Forward reference + if isinstance(original_value, str): + if globalns is None: + if isinstance(obj, _types.ModuleType): + globalns = obj.__dict__ + else: + nsobj = obj + # Find globalns for the unwrapped object. + while hasattr(nsobj, '__wrapped__'): + nsobj = nsobj.__wrapped__ + globalns = getattr(nsobj, '__globals__', {}) + if localns is None: + localns = globalns + elif localns is None: + localns = globalns + + original_value = ForwardRef( + original_value, + is_argument=not isinstance(obj, _types.ModuleType) + ) + original_evaluated = typing._eval_type(original_value, globalns, localns) + # Compare if values differ. Note that even if equal + # value might be cached by typing._tp_cache contrary to original_evaluated + if original_evaluated != value or ( + # 3.10: ForwardRefs of UnionType might be turned into _UnionGenericAlias + hasattr(_types, "UnionType") + and isinstance(original_evaluated, _types.UnionType) + and not isinstance(value, _types.UnionType) + ): + hints[name] = original_evaluated + +# Python 3.9 has get_origin() and get_args() but those implementations don't support +# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do. +if sys.version_info[:2] >= (3, 10): + get_origin = typing.get_origin + get_args = typing.get_args +# 3.9 +else: + def get_origin(tp): + """Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar + and Annotated. Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + get_origin(P.args) is P + """ + if isinstance(tp, typing._AnnotatedAlias): + return Annotated + if isinstance(tp, (typing._BaseGenericAlias, _types.GenericAlias, + ParamSpecArgs, ParamSpecKwargs)): + return tp.__origin__ + if tp is typing.Generic: + return typing.Generic + return None + + def get_args(tp): + """Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + """ + if isinstance(tp, typing._AnnotatedAlias): + return (tp.__origin__, *tp.__metadata__) + if isinstance(tp, (typing._GenericAlias, _types.GenericAlias)): + res = tp.__args__ + if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: + res = (list(res[:-1]), res[-1]) + return res + return () + + +# 3.10+ +if hasattr(typing, 'TypeAlias'): + TypeAlias = typing.TypeAlias +# 3.9 +else: + @_ExtensionsSpecialForm + def TypeAlias(self, parameters): + """Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + raise TypeError(f"{self} is not subscriptable") + + +def _set_default(type_param, default): + type_param.has_default = lambda: default is not NoDefault + type_param.__default__ = default + + +def _set_module(typevarlike): + # for pickling: + def_mod = _caller(depth=2) + if def_mod != 'typing_extensions': + typevarlike.__module__ = def_mod + + +class _DefaultMixin: + """Mixin for TypeVarLike defaults.""" + + __slots__ = () + __init__ = _set_default + + +# Classes using this metaclass must provide a _backported_typevarlike ClassVar +class _TypeVarLikeMeta(type): + def __instancecheck__(cls, __instance: Any) -> bool: + return isinstance(__instance, cls._backported_typevarlike) + + +if _PEP_696_IMPLEMENTED: + from typing import TypeVar +else: + # Add default and infer_variance parameters from PEP 696 and 695 + class TypeVar(metaclass=_TypeVarLikeMeta): + """Type variable.""" + + _backported_typevarlike = typing.TypeVar + + def __new__(cls, name, *constraints, bound=None, + covariant=False, contravariant=False, + default=NoDefault, infer_variance=False): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant, + infer_variance=infer_variance) + else: + typevar = typing.TypeVar(name, *constraints, bound=bound, + covariant=covariant, contravariant=contravariant) + if infer_variance and (covariant or contravariant): + raise ValueError("Variance cannot be specified with infer_variance.") + typevar.__infer_variance__ = infer_variance + + _set_default(typevar, default) + _set_module(typevar) + + def _tvar_prepare_subst(alias, args): + if ( + typevar.has_default() + and alias.__parameters__.index(typevar) == len(args) + ): + args += (typevar.__default__,) + return args + + typevar.__typing_prepare_subst__ = _tvar_prepare_subst + return typevar + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type") + + +# Python 3.10+ has PEP 612 +if hasattr(typing, 'ParamSpecArgs'): + ParamSpecArgs = typing.ParamSpecArgs + ParamSpecKwargs = typing.ParamSpecKwargs +# 3.9 +else: + class _Immutable: + """Mixin to indicate that object should not be copied.""" + __slots__ = () + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + class ParamSpecArgs(_Immutable): + """The args for a ParamSpec object. + + Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. + + ParamSpecArgs objects have a reference back to their ParamSpec: + + P.args.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.args" + + def __eq__(self, other): + if not isinstance(other, ParamSpecArgs): + return NotImplemented + return self.__origin__ == other.__origin__ + + class ParamSpecKwargs(_Immutable): + """The kwargs for a ParamSpec object. + + Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. + + ParamSpecKwargs objects have a reference back to their ParamSpec: + + P.kwargs.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return f"{self.__origin__.__name__}.kwargs" + + def __eq__(self, other): + if not isinstance(other, ParamSpecKwargs): + return NotImplemented + return self.__origin__ == other.__origin__ + + +if _PEP_696_IMPLEMENTED: + from typing import ParamSpec + +# 3.10+ +elif hasattr(typing, 'ParamSpec'): + + # Add default parameter - PEP 696 + class ParamSpec(metaclass=_TypeVarLikeMeta): + """Parameter specification.""" + + _backported_typevarlike = typing.ParamSpec + + def __new__(cls, name, *, bound=None, + covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + if hasattr(typing, "TypeAliasType"): + # PEP 695 implemented, can pass infer_variance to typing.TypeVar + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant, + infer_variance=infer_variance) + else: + paramspec = typing.ParamSpec(name, bound=bound, + covariant=covariant, + contravariant=contravariant) + paramspec.__infer_variance__ = infer_variance + + _set_default(paramspec, default) + _set_module(paramspec) + + def _paramspec_prepare_subst(alias, args): + params = alias.__parameters__ + i = params.index(paramspec) + if i == len(args) and paramspec.has_default(): + args = [*args, paramspec.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {alias}") + # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612. + if len(params) == 1 and not typing._is_param_expr(args[0]): + assert i == 0 + args = (args,) + # Convert lists to tuples to help other libraries cache the results. + elif isinstance(args[i], list): + args = (*args[:i], tuple(args[i]), *args[i + 1:]) + return args + + paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst + return paramspec + + def __init_subclass__(cls) -> None: + raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type") + +# 3.9 +else: + + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + class ParamSpec(list, _DefaultMixin): + """Parameter specification variable. + + Usage:: + + P = ParamSpec('P') + + Parameter specification variables exist primarily for the benefit of static + type checkers. They are used to forward the parameter types of one + callable to another callable, a pattern commonly found in higher order + functions and decorators. They are only valid when used in ``Concatenate``, + or s the first argument to ``Callable``. In Python 3.10 and higher, + they are also supported in user-defined Generics at runtime. + See class Generic for more information on generic types. An + example for annotating a decorator:: + + T = TypeVar('T') + P = ParamSpec('P') + + def add_logging(f: Callable[P, T]) -> Callable[P, T]: + '''A type-safe decorator to add logging to a function.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + logging.info(f'{f.__name__} was called') + return f(*args, **kwargs) + return inner + + @add_logging + def add_two(x: float, y: float) -> float: + '''Add two numbers together.''' + return x + y + + Parameter specification variables defined with covariant=True or + contravariant=True can be used to declare covariant or contravariant + generic types. These keyword arguments are valid, but their actual semantics + are yet to be decided. See PEP 612 for details. + + Parameter specification variables can be introspected. e.g.: + + P.__name__ == 'T' + P.__bound__ == None + P.__covariant__ == False + P.__contravariant__ == False + + Note that only parameter specification variables defined in global scope can + be pickled. + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + @property + def args(self): + return ParamSpecArgs(self) + + @property + def kwargs(self): + return ParamSpecKwargs(self) + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False, + infer_variance=False, default=NoDefault): + list.__init__(self, [self]) + self.__name__ = name + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + self.__infer_variance__ = bool(infer_variance) + if bound: + self.__bound__ = typing._type_check(bound, 'Bound must be a type.') + else: + self.__bound__ = None + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __repr__(self): + if self.__infer_variance__: + prefix = '' + elif self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + # Hack to get typing._type_check to pass. + def __call__(self, *args, **kwargs): + pass + + +# 3.9 +if not hasattr(typing, 'Concatenate'): + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + + # 3.9.0-1 + if not hasattr(typing, '_type_convert'): + def _type_convert(arg, module=None, *, allow_special_forms=False): + """For converting None to type(None), and strings to ForwardRef.""" + if arg is None: + return type(None) + if isinstance(arg, str): + if sys.version_info <= (3, 9, 6): + return ForwardRef(arg) + if sys.version_info <= (3, 9, 7): + return ForwardRef(arg, module=module) + return ForwardRef(arg, module=module, is_class=allow_special_forms) + return arg + else: + _type_convert = typing._type_convert + + class _ConcatenateGenericAlias(list): + + # Trick Generic into looking into this for __parameters__. + __class__ = typing._GenericAlias + + def __init__(self, origin, args): + super().__init__(args) + self.__origin__ = origin + self.__args__ = args + + def __repr__(self): + _type_repr = typing._type_repr + return (f'{_type_repr(self.__origin__)}' + f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]') + + def __hash__(self): + return hash((self.__origin__, self.__args__)) + + # Hack to get typing._type_check to pass in Generic. + def __call__(self, *args, **kwargs): + pass + + @property + def __parameters__(self): + return tuple( + tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec)) + ) + + # 3.9 used by __getitem__ below + def copy_with(self, params): + if isinstance(params[-1], _ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + elif isinstance(params[-1], (list, tuple)): + return (*params[:-1], *params[-1]) + elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + return self.__class__(self.__origin__, params) + + # 3.9; accessed during GenericAlias.__getitem__ when substituting + def __getitem__(self, args): + if self.__origin__ in (Generic, Protocol): + # Can't subscript Generic[...] or Protocol[...]. + raise TypeError(f"Cannot subscript already-subscripted {self}") + if not self.__parameters__: + raise TypeError(f"{self} is not a generic class") + + if not isinstance(args, tuple): + args = (args,) + args = _unpack_args(*(_type_convert(p) for p in args)) + params = self.__parameters__ + for param in params: + prepare = getattr(param, "__typing_prepare_subst__", None) + if prepare is not None: + args = prepare(self, args) + # 3.9 & typing.ParamSpec + elif isinstance(param, ParamSpec): + i = params.index(param) + if ( + i == len(args) + and getattr(param, '__default__', NoDefault) is not NoDefault + ): + args = [*args, param.__default__] + if i >= len(args): + raise TypeError(f"Too few arguments for {self}") + # Special case for Z[[int, str, bool]] == Z[int, str, bool] + if len(params) == 1 and not _is_param_expr(args[0]): + assert i == 0 + args = (args,) + elif ( + isinstance(args[i], list) + # 3.9 + # This class inherits from list do not convert + and not isinstance(args[i], _ConcatenateGenericAlias) + ): + args = (*args[:i], tuple(args[i]), *args[i + 1:]) + + alen = len(args) + plen = len(params) + if alen != plen: + raise TypeError( + f"Too {'many' if alen > plen else 'few'} arguments for {self};" + f" actual {alen}, expected {plen}" + ) + + subst = dict(zip(self.__parameters__, args)) + # determine new args + new_args = [] + for arg in self.__args__: + if isinstance(arg, type): + new_args.append(arg) + continue + if isinstance(arg, TypeVar): + arg = subst[arg] + if ( + (isinstance(arg, typing._GenericAlias) and _is_unpack(arg)) + or ( + hasattr(_types, "GenericAlias") + and isinstance(arg, _types.GenericAlias) + and getattr(arg, "__unpacked__", False) + ) + ): + raise TypeError(f"{arg} is not valid as type argument") + + elif isinstance(arg, + typing._GenericAlias + if not hasattr(_types, "GenericAlias") else + (typing._GenericAlias, _types.GenericAlias) + ): + subparams = arg.__parameters__ + if subparams: + subargs = tuple(subst[x] for x in subparams) + arg = arg[subargs] + new_args.append(arg) + return self.copy_with(tuple(new_args)) + +# 3.10+ +else: + _ConcatenateGenericAlias = typing._ConcatenateGenericAlias + + # 3.10 + if sys.version_info < (3, 11): + + class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True): + # needed for checks in collections.abc.Callable to accept this class + __module__ = "typing" + + def copy_with(self, params): + if isinstance(params[-1], (list, tuple)): + return (*params[:-1], *params[-1]) + if isinstance(params[-1], typing._ConcatenateGenericAlias): + params = (*params[:-1], *params[-1].__args__) + elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + return super(typing._ConcatenateGenericAlias, self).copy_with(params) + + def __getitem__(self, args): + value = super().__getitem__(args) + if isinstance(value, tuple) and any(_is_unpack(t) for t in value): + return tuple(_unpack_args(*(n for n in value))) + return value + + +# 3.9.2 +class _EllipsisDummy: ... + + +# <=3.10 +def _create_concatenate_alias(origin, parameters): + if parameters[-1] is ... and sys.version_info < (3, 9, 2): + # Hack: Arguments must be types, replace it with one. + parameters = (*parameters[:-1], _EllipsisDummy) + if sys.version_info >= (3, 10, 3): + concatenate = _ConcatenateGenericAlias(origin, parameters, + _typevar_types=(TypeVar, ParamSpec), + _paramspec_tvars=True) + else: + concatenate = _ConcatenateGenericAlias(origin, parameters) + if parameters[-1] is not _EllipsisDummy: + return concatenate + # Remove dummy again + concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ... + for p in concatenate.__args__) + if sys.version_info < (3, 10): + # backport needs __args__ adjustment only + return concatenate + concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__ + if p is not _EllipsisDummy) + return concatenate + + +# <=3.10 +@typing._tp_cache +def _concatenate_getitem(self, parameters): + if parameters == (): + raise TypeError("Cannot take a Concatenate of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable or ellipsis.") + msg = "Concatenate[arg, ...]: each arg must be a type." + parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]), + parameters[-1]) + return _create_concatenate_alias(self, parameters) + + +# 3.11+; Concatenate does not accept ellipsis in 3.10 +if sys.version_info >= (3, 11): + Concatenate = typing.Concatenate +# <=3.10 +else: + @_ExtensionsSpecialForm + def Concatenate(self, parameters): + """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + return _concatenate_getitem(self, parameters) + + +# 3.10+ +if hasattr(typing, 'TypeGuard'): + TypeGuard = typing.TypeGuard +# 3.9 +else: + @_ExtensionsSpecialForm + def TypeGuard(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +# 3.13+ +if hasattr(typing, 'TypeIs'): + TypeIs = typing.TypeIs +# <=3.12 +else: + @_ExtensionsSpecialForm + def TypeIs(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type narrower function. ``TypeIs`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeIs[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeIs`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the intersection of the type inside ``TypeIs`` and the argument's + previously known type. + + For example:: + + def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]: + return hasattr(val, '__await__') + + def f(val: Union[int, Awaitable[int]]) -> int: + if is_awaitable(val): + assert_type(val, Awaitable[int]) + else: + assert_type(val, int) + + ``TypeIs`` also works with type variables. For more information, see + PEP 742 (Narrowing types with TypeIs). + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +# 3.14+? +if hasattr(typing, 'TypeForm'): + TypeForm = typing.TypeForm +# <=3.13 +else: + class _TypeFormForm(_ExtensionsSpecialForm, _root=True): + # TypeForm(X) is equivalent to X but indicates to the type checker + # that the object is a TypeForm. + def __call__(self, obj, /): + return obj + + @_TypeFormForm + def TypeForm(self, parameters): + """A special form representing the value that results from the evaluation + of a type expression. This value encodes the information supplied in the + type expression, and it represents the type described by that type expression. + + When used in a type expression, TypeForm describes a set of type form objects. + It accepts a single type argument, which must be a valid type expression. + ``TypeForm[T]`` describes the set of all type form objects that represent + the type T or types that are assignable to T. + + Usage: + + def cast[T](typ: TypeForm[T], value: Any) -> T: ... + + reveal_type(cast(int, "x")) # int + + See PEP 747 for more information. + """ + item = typing._type_check(parameters, f'{self} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + + + +if hasattr(typing, "LiteralString"): # 3.11+ + LiteralString = typing.LiteralString +else: + @_SpecialForm + def LiteralString(self, params): + """Represents an arbitrary literal string. + + Example:: + + from typing_extensions import LiteralString + + def query(sql: LiteralString) -> ...: + ... + + query("SELECT * FROM table") # ok + query(f"SELECT * FROM {input()}") # not ok + + See PEP 675 for details. + + """ + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Self"): # 3.11+ + Self = typing.Self +else: + @_SpecialForm + def Self(self, params): + """Used to spell the type of "self" in classes. + + Example:: + + from typing import Self + + class ReturnsSelf: + def parse(self, data: bytes) -> Self: + ... + return self + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, "Never"): # 3.11+ + Never = typing.Never +else: + @_SpecialForm + def Never(self, params): + """The bottom type, a type that has no members. + + This can be used to define a function that should never be + called, or a function that never returns:: + + from typing_extensions import Never + + def never_call_me(arg: Never) -> None: + pass + + def int_or_str(arg: int | str) -> None: + never_call_me(arg) # type checker error + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + never_call_me(arg) # ok, arg is of type Never + + """ + + raise TypeError(f"{self} is not subscriptable") + + +if hasattr(typing, 'Required'): # 3.11+ + Required = typing.Required + NotRequired = typing.NotRequired +else: # <=3.10 + @_ExtensionsSpecialForm + def Required(self, parameters): + """A special typing construct to mark a key of a total=False TypedDict + as required. For example: + + class Movie(TypedDict, total=False): + title: Required[str] + year: int + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + + There is no runtime checking that a required key is actually provided + when instantiating a related TypedDict. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + @_ExtensionsSpecialForm + def NotRequired(self, parameters): + """A special typing construct to mark a key of a TypedDict as + potentially missing. For example: + + class Movie(TypedDict): + title: str + year: NotRequired[int] + + m = Movie( + title='The Matrix', # typechecker error if key is omitted + year=1999, + ) + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +if hasattr(typing, 'ReadOnly'): + ReadOnly = typing.ReadOnly +else: # <=3.12 + @_ExtensionsSpecialForm + def ReadOnly(self, parameters): + """A special typing construct to mark an item of a TypedDict as read-only. + + For example: + + class Movie(TypedDict): + title: ReadOnly[str] + year: int + + def mutate_movie(m: Movie) -> None: + m["year"] = 1992 # allowed + m["title"] = "The Matrix" # typechecker error + + There is no runtime checking for this property. + """ + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return typing._GenericAlias(self, (item,)) + + +_UNPACK_DOC = """\ +Type unpack operator. + +The type unpack operator takes the child types from some container type, +such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For +example: + + # For some generic class `Foo`: + Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str] + + Ts = TypeVarTuple('Ts') + # Specifies that `Bar` is generic in an arbitrary number of types. + # (Think of `Ts` as a tuple of an arbitrary number of individual + # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the + # `Generic[]`.) + class Bar(Generic[Unpack[Ts]]): ... + Bar[int] # Valid + Bar[int, str] # Also valid + +From Python 3.11, this can also be done using the `*` operator: + + Foo[*tuple[int, str]] + class Bar(Generic[*Ts]): ... + +The operator can also be used along with a `TypedDict` to annotate +`**kwargs` in a function signature. For instance: + + class Movie(TypedDict): + name: str + year: int + + # This function expects two keyword arguments - *name* of type `str` and + # *year* of type `int`. + def foo(**kwargs: Unpack[Movie]): ... + +Note that there is only some runtime checking of this operator. Not +everything the runtime allows may be accepted by static type checkers. + +For more information, see PEP 646 and PEP 692. +""" + + +if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[] + Unpack = typing.Unpack + + def _is_unpack(obj): + return get_origin(obj) is Unpack + +else: # <=3.11 + class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True): + def __init__(self, getitem): + super().__init__(getitem) + self.__doc__ = _UNPACK_DOC + + class _UnpackAlias(typing._GenericAlias, _root=True): + if sys.version_info < (3, 11): + # needed for compatibility with Generic[Unpack[Ts]] + __class__ = typing.TypeVar + + @property + def __typing_unpacked_tuple_args__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + arg, = self.__args__ + if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)): + if arg.__origin__ is not tuple: + raise TypeError("Unpack[...] must be used with a tuple type") + return arg.__args__ + return None + + @property + def __typing_is_unpacked_typevartuple__(self): + assert self.__origin__ is Unpack + assert len(self.__args__) == 1 + return isinstance(self.__args__[0], TypeVarTuple) + + def __getitem__(self, args): + if self.__typing_is_unpacked_typevartuple__: + return args + return super().__getitem__(args) + + @_UnpackSpecialForm + def Unpack(self, parameters): + item = typing._type_check(parameters, f'{self._name} accepts only a single type.') + return _UnpackAlias(self, (item,)) + + def _is_unpack(obj): + return isinstance(obj, _UnpackAlias) + + +def _unpack_args(*args): + newargs = [] + for arg in args: + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs is not None and (not (subargs and subargs[-1] is ...)): + newargs.extend(subargs) + else: + newargs.append(arg) + return newargs + + +if _PEP_696_IMPLEMENTED: + from typing import TypeVarTuple + +elif hasattr(typing, "TypeVarTuple"): # 3.11+ + + # Add default parameter - PEP 696 + class TypeVarTuple(metaclass=_TypeVarLikeMeta): + """Type variable tuple.""" + + _backported_typevarlike = typing.TypeVarTuple + + def __new__(cls, name, *, default=NoDefault): + tvt = typing.TypeVarTuple(name) + _set_default(tvt, default) + _set_module(tvt) + + def _typevartuple_prepare_subst(alias, args): + params = alias.__parameters__ + typevartuple_index = params.index(tvt) + for param in params[typevartuple_index + 1:]: + if isinstance(param, TypeVarTuple): + raise TypeError( + f"More than one TypeVarTuple parameter in {alias}" + ) + + alen = len(args) + plen = len(params) + left = typevartuple_index + right = plen - typevartuple_index - 1 + var_tuple_index = None + fillarg = None + for k, arg in enumerate(args): + if not isinstance(arg, type): + subargs = getattr(arg, '__typing_unpacked_tuple_args__', None) + if subargs and len(subargs) == 2 and subargs[-1] is ...: + if var_tuple_index is not None: + raise TypeError( + "More than one unpacked " + "arbitrary-length tuple argument" + ) + var_tuple_index = k + fillarg = subargs[0] + if var_tuple_index is not None: + left = min(left, var_tuple_index) + right = min(right, alen - var_tuple_index - 1) + elif left + right > alen: + raise TypeError(f"Too few arguments for {alias};" + f" actual {alen}, expected at least {plen - 1}") + if left == alen - right and tvt.has_default(): + replacement = _unpack_args(tvt.__default__) + else: + replacement = args[left: alen - right] + + return ( + *args[:left], + *([fillarg] * (typevartuple_index - left)), + replacement, + *([fillarg] * (plen - right - left - typevartuple_index - 1)), + *args[alen - right:], + ) + + tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst + return tvt + + def __init_subclass__(self, *args, **kwds): + raise TypeError("Cannot subclass special typing classes") + +else: # <=3.10 + class TypeVarTuple(_DefaultMixin): + """Type variable tuple. + + Usage:: + + Ts = TypeVarTuple('Ts') + + In the same way that a normal type variable is a stand-in for a single + type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* + type such as ``Tuple[int, str]``. + + Type variable tuples can be used in ``Generic`` declarations. + Consider the following example:: + + class Array(Generic[*Ts]): ... + + The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, + where ``T1`` and ``T2`` are type variables. To use these type variables + as type parameters of ``Array``, we must *unpack* the type variable tuple using + the star operator: ``*Ts``. The signature of ``Array`` then behaves + as if we had simply written ``class Array(Generic[T1, T2]): ...``. + In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows + us to parameterise the class with an *arbitrary* number of type parameters. + + Type variable tuples can be used anywhere a normal ``TypeVar`` can. + This includes class definitions, as shown above, as well as function + signatures and variable annotations:: + + class Array(Generic[*Ts]): + + def __init__(self, shape: Tuple[*Ts]): + self._shape: Tuple[*Ts] = shape + + def get_shape(self) -> Tuple[*Ts]: + return self._shape + + shape = (Height(480), Width(640)) + x: Array[Height, Width] = Array(shape) + y = abs(x) # Inferred type is Array[Height, Width] + z = x + x # ... is Array[Height, Width] + x.get_shape() # ... is tuple[Height, Width] + + """ + + # Trick Generic __parameters__. + __class__ = typing.TypeVar + + def __iter__(self): + yield self.__unpacked__ + + def __init__(self, name, *, default=NoDefault): + self.__name__ = name + _DefaultMixin.__init__(self, default) + + # for pickling: + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + self.__unpacked__ = Unpack[self] + + def __repr__(self): + return self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(self, *args, **kwds): + if '_root' not in kwds: + raise TypeError("Cannot subclass special typing classes") + + +if hasattr(typing, "reveal_type"): # 3.11+ + reveal_type = typing.reveal_type +else: # <=3.10 + def reveal_type(obj: T, /) -> T: + """Reveal the inferred type of a variable. + + When a static type checker encounters a call to ``reveal_type()``, + it will emit the inferred type of the argument:: + + x: int = 1 + reveal_type(x) + + Running a static type checker (e.g., ``mypy``) on this example + will produce output similar to 'Revealed type is "builtins.int"'. + + At runtime, the function prints the runtime type of the + argument and returns it unchanged. + + """ + print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr) + return obj + + +if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+ + _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH +else: # <=3.10 + _ASSERT_NEVER_REPR_MAX_LENGTH = 100 + + +if hasattr(typing, "assert_never"): # 3.11+ + assert_never = typing.assert_never +else: # <=3.10 + def assert_never(arg: Never, /) -> Never: + """Assert to the type checker that a line of code is unreachable. + + Example:: + + def int_or_str(arg: int | str) -> None: + match arg: + case int(): + print("It's an int") + case str(): + print("It's a str") + case _: + assert_never(arg) + + If a type checker finds that a call to assert_never() is + reachable, it will emit an error. + + At runtime, this throws an exception when called. + + """ + value = repr(arg) + if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH: + value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...' + raise AssertionError(f"Expected code to be unreachable, but got: {value}") + + +if sys.version_info >= (3, 12): # 3.12+ + # dataclass_transform exists in 3.11 but lacks the frozen_default parameter + dataclass_transform = typing.dataclass_transform +else: # <=3.11 + def dataclass_transform( + *, + eq_default: bool = True, + order_default: bool = False, + kw_only_default: bool = False, + frozen_default: bool = False, + field_specifiers: typing.Tuple[ + typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], + ... + ] = (), + **kwargs: typing.Any, + ) -> typing.Callable[[T], T]: + """Decorator that marks a function, class, or metaclass as providing + dataclass-like behavior. + + Example: + + from typing_extensions import dataclass_transform + + _T = TypeVar("_T") + + # Used on a decorator function + @dataclass_transform() + def create_model(cls: type[_T]) -> type[_T]: + ... + return cls + + @create_model + class CustomerModel: + id: int + name: str + + # Used on a base class + @dataclass_transform() + class ModelBase: ... + + class CustomerModel(ModelBase): + id: int + name: str + + # Used on a metaclass + @dataclass_transform() + class ModelMeta(type): ... + + class ModelBase(metaclass=ModelMeta): ... + + class CustomerModel(ModelBase): + id: int + name: str + + Each of the ``CustomerModel`` classes defined in this example will now + behave similarly to a dataclass created with the ``@dataclasses.dataclass`` + decorator. For example, the type checker will synthesize an ``__init__`` + method. + + The arguments to this decorator can be used to customize this behavior: + - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be + True or False if it is omitted by the caller. + - ``order_default`` indicates whether the ``order`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``kw_only_default`` indicates whether the ``kw_only`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``frozen_default`` indicates whether the ``frozen`` parameter is + assumed to be True or False if it is omitted by the caller. + - ``field_specifiers`` specifies a static list of supported classes + or functions that describe fields, similar to ``dataclasses.field()``. + + At runtime, this decorator records its arguments in the + ``__dataclass_transform__`` attribute on the decorated object. + + See PEP 681 for details. + + """ + def decorator(cls_or_fn): + cls_or_fn.__dataclass_transform__ = { + "eq_default": eq_default, + "order_default": order_default, + "kw_only_default": kw_only_default, + "frozen_default": frozen_default, + "field_specifiers": field_specifiers, + "kwargs": kwargs, + } + return cls_or_fn + return decorator + + +if hasattr(typing, "override"): # 3.12+ + override = typing.override +else: # <=3.11 + _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any]) + + def override(arg: _F, /) -> _F: + """Indicate that a method is intended to override a method in a base class. + + Usage: + + class Base: + def method(self) -> None: + pass + + class Child(Base): + @override + def method(self) -> None: + super().method() + + When this decorator is applied to a method, the type checker will + validate that it overrides a method with the same name on a base class. + This helps prevent bugs that may occur when a base class is changed + without an equivalent change to a child class. + + There is no runtime checking of these properties. The decorator + sets the ``__override__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + + See PEP 698 for details. + + """ + try: + arg.__override__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return arg + + +# Python 3.13.3+ contains a fix for the wrapped __new__ +if sys.version_info >= (3, 13, 3): + deprecated = warnings.deprecated +else: + _T = typing.TypeVar("_T") + + class deprecated: + """Indicate that a class, function or overload is deprecated. + + When this decorator is applied to an object, the type checker + will generate a diagnostic on usage of the deprecated object. + + Usage: + + @deprecated("Use B instead") + class A: + pass + + @deprecated("Use g instead") + def f(): + pass + + @overload + @deprecated("int support is deprecated") + def g(x: int) -> int: ... + @overload + def g(x: str) -> int: ... + + The warning specified by *category* will be emitted at runtime + on use of deprecated objects. For functions, that happens on calls; + for classes, on instantiation and on creation of subclasses. + If the *category* is ``None``, no warning is emitted at runtime. + The *stacklevel* determines where the + warning is emitted. If it is ``1`` (the default), the warning + is emitted at the direct caller of the deprecated object; if it + is higher, it is emitted further up the stack. + Static type checker behavior is not affected by the *category* + and *stacklevel* arguments. + + The deprecation message passed to the decorator is saved in the + ``__deprecated__`` attribute on the decorated object. + If applied to an overload, the decorator + must be after the ``@overload`` decorator for the attribute to + exist on the overload as returned by ``get_overloads()``. + + See PEP 702 for details. + + """ + def __init__( + self, + message: str, + /, + *, + category: typing.Optional[typing.Type[Warning]] = DeprecationWarning, + stacklevel: int = 1, + ) -> None: + if not isinstance(message, str): + raise TypeError( + "Expected an object of type str for 'message', not " + f"{type(message).__name__!r}" + ) + self.message = message + self.category = category + self.stacklevel = stacklevel + + def __call__(self, arg: _T, /) -> _T: + # Make sure the inner functions created below don't + # retain a reference to self. + msg = self.message + category = self.category + stacklevel = self.stacklevel + if category is None: + arg.__deprecated__ = msg + return arg + elif isinstance(arg, type): + import functools + from types import MethodType + + original_new = arg.__new__ + + @functools.wraps(original_new) + def __new__(cls, /, *args, **kwargs): + if cls is arg: + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + if original_new is not object.__new__: + return original_new(cls, *args, **kwargs) + # Mirrors a similar check in object.__new__. + elif cls.__init__ is object.__init__ and (args or kwargs): + raise TypeError(f"{cls.__name__}() takes no arguments") + else: + return original_new(cls) + + arg.__new__ = staticmethod(__new__) + + original_init_subclass = arg.__init_subclass__ + # We need slightly different behavior if __init_subclass__ + # is a bound method (likely if it was implemented in Python) + if isinstance(original_init_subclass, MethodType): + original_init_subclass = original_init_subclass.__func__ + + @functools.wraps(original_init_subclass) + def __init_subclass__(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return original_init_subclass(*args, **kwargs) + + arg.__init_subclass__ = classmethod(__init_subclass__) + # Or otherwise, which likely means it's a builtin such as + # object's implementation of __init_subclass__. + else: + @functools.wraps(original_init_subclass) + def __init_subclass__(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return original_init_subclass(*args, **kwargs) + + arg.__init_subclass__ = __init_subclass__ + + arg.__deprecated__ = __new__.__deprecated__ = msg + __init_subclass__.__deprecated__ = msg + return arg + elif callable(arg): + import asyncio.coroutines + import functools + import inspect + + @functools.wraps(arg) + def wrapper(*args, **kwargs): + warnings.warn(msg, category=category, stacklevel=stacklevel + 1) + return arg(*args, **kwargs) + + if asyncio.coroutines.iscoroutinefunction(arg): + if sys.version_info >= (3, 12): + wrapper = inspect.markcoroutinefunction(wrapper) + else: + wrapper._is_coroutine = asyncio.coroutines._is_coroutine + + arg.__deprecated__ = wrapper.__deprecated__ = msg + return wrapper + else: + raise TypeError( + "@deprecated decorator with non-None category must be applied to " + f"a class or callable, not {arg!r}" + ) + +if sys.version_info < (3, 10): + def _is_param_expr(arg): + return arg is ... or isinstance( + arg, (tuple, list, ParamSpec, _ConcatenateGenericAlias) + ) +else: + def _is_param_expr(arg): + return arg is ... or isinstance( + arg, + ( + tuple, + list, + ParamSpec, + _ConcatenateGenericAlias, + typing._ConcatenateGenericAlias, + ), + ) + + +# We have to do some monkey patching to deal with the dual nature of +# Unpack/TypeVarTuple: +# - We want Unpack to be a kind of TypeVar so it gets accepted in +# Generic[Unpack[Ts]] +# - We want it to *not* be treated as a TypeVar for the purposes of +# counting generic parameters, so that when we subscript a generic, +# the runtime doesn't try to substitute the Unpack with the subscripted type. +if not hasattr(typing, "TypeVarTuple"): + def _check_generic(cls, parameters, elen=_marker): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + # If substituting a single ParamSpec with multiple arguments + # we do not check the count + if (inspect.isclass(cls) and issubclass(cls, typing.Generic) + and len(cls.__parameters__) == 1 + and isinstance(cls.__parameters__[0], ParamSpec) + and parameters + and not _is_param_expr(parameters[0]) + ): + # Generic modifies parameters variable, but here we cannot do this + return + + if not elen: + raise TypeError(f"{cls} is not a generic class") + if elen is _marker: + if not hasattr(cls, "__parameters__") or not cls.__parameters__: + raise TypeError(f"{cls} is not a generic class") + elen = len(cls.__parameters__) + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters) + if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples): + return + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + things = "arguments" if sys.version_info >= (3, 10) else "parameters" + raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}" + f" for {cls}; actual {alen}, expected {expect_val}") +else: + # Python 3.11+ + + def _check_generic(cls, parameters, elen): + """Check correct count for parameters of a generic cls (internal helper). + + This gives a nice error message in case of count mismatch. + """ + if not elen: + raise TypeError(f"{cls} is not a generic class") + alen = len(parameters) + if alen != elen: + expect_val = elen + if hasattr(cls, "__parameters__"): + parameters = [p for p in cls.__parameters__ if not _is_unpack(p)] + + # deal with TypeVarLike defaults + # required TypeVarLikes cannot appear after a defaulted one. + if alen < elen: + # since we validate TypeVarLike default in _collect_type_vars + # or _collect_parameters we can safely check parameters[alen] + if ( + getattr(parameters[alen], '__default__', NoDefault) + is not NoDefault + ): + return + + num_default_tv = sum(getattr(p, '__default__', NoDefault) + is not NoDefault for p in parameters) + + elen -= num_default_tv + + expect_val = f"at least {elen}" + + raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments" + f" for {cls}; actual {alen}, expected {expect_val}") + +if not _PEP_696_IMPLEMENTED: + typing._check_generic = _check_generic + + +def _has_generic_or_protocol_as_origin() -> bool: + try: + frame = sys._getframe(2) + # - Catch AttributeError: not all Python implementations have sys._getframe() + # - Catch ValueError: maybe we're called from an unexpected module + # and the call stack isn't deep enough + except (AttributeError, ValueError): + return False # err on the side of leniency + else: + # If we somehow get invoked from outside typing.py, + # also err on the side of leniency + if frame.f_globals.get("__name__") != "typing": + return False + origin = frame.f_locals.get("origin") + # Cannot use "in" because origin may be an object with a buggy __eq__ that + # throws an error. + return origin is typing.Generic or origin is Protocol or origin is typing.Protocol + + +_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)} + + +def _is_unpacked_typevartuple(x) -> bool: + if get_origin(x) is not Unpack: + return False + args = get_args(x) + return ( + bool(args) + and len(args) == 1 + and type(args[0]) in _TYPEVARTUPLE_TYPES + ) + + +# Python 3.11+ _collect_type_vars was renamed to _collect_parameters +if hasattr(typing, '_collect_type_vars'): + def _collect_type_vars(types, typevar_types=None): + """Collect all type variable contained in types in order of + first appearance (lexicographic order). For example:: + + _collect_type_vars((T, List[S, T])) == (T, S) + """ + if typevar_types is None: + typevar_types = typing.TypeVar + tvars = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with a default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in types: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + elif ( + isinstance(t, typevar_types) and not isinstance(t, _UnpackAlias) + and t not in tvars + ): + if enforce_default_ordering: + has_default = getattr(t, '__default__', NoDefault) is not NoDefault + if has_default: + if type_var_tuple_encountered: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + tvars.append(t) + if _should_collect_from_parameters(t): + tvars.extend([t for t in t.__parameters__ if t not in tvars]) + elif isinstance(t, tuple): + # Collect nested type_vars + # tuple wrapped by _prepare_paramspec_params(cls, params) + for x in t: + for collected in _collect_type_vars([x]): + if collected not in tvars: + tvars.append(collected) + return tuple(tvars) + + typing._collect_type_vars = _collect_type_vars +else: + def _collect_parameters(args): + """Collect all type variables and parameter specifications in args + in order of first appearance (lexicographic order). + + For example:: + + assert _collect_parameters((T, Callable[P, T])) == (T, P) + """ + parameters = [] + + # A required TypeVarLike cannot appear after a TypeVarLike with default + # if it was a direct call to `Generic[]` or `Protocol[]` + enforce_default_ordering = _has_generic_or_protocol_as_origin() + default_encountered = False + + # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple + type_var_tuple_encountered = False + + for t in args: + if isinstance(t, type): + # We don't want __parameters__ descriptor of a bare Python class. + pass + elif isinstance(t, tuple): + # `t` might be a tuple, when `ParamSpec` is substituted with + # `[T, int]`, or `[int, *Ts]`, etc. + for x in t: + for collected in _collect_parameters([x]): + if collected not in parameters: + parameters.append(collected) + elif hasattr(t, '__typing_subst__'): + if t not in parameters: + if enforce_default_ordering: + has_default = ( + getattr(t, '__default__', NoDefault) is not NoDefault + ) + + if type_var_tuple_encountered and has_default: + raise TypeError('Type parameter with a default' + ' follows TypeVarTuple') + + if has_default: + default_encountered = True + elif default_encountered: + raise TypeError(f'Type parameter {t!r} without a default' + ' follows type parameter with a default') + + parameters.append(t) + else: + if _is_unpacked_typevartuple(t): + type_var_tuple_encountered = True + for x in getattr(t, '__parameters__', ()): + if x not in parameters: + parameters.append(x) + + return tuple(parameters) + + if not _PEP_696_IMPLEMENTED: + typing._collect_parameters = _collect_parameters + +# Backport typing.NamedTuple as it exists in Python 3.13. +# In 3.11, the ability to define generic `NamedTuple`s was supported. +# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8. +# On 3.12, we added __orig_bases__ to call-based NamedTuples +# On 3.13, we deprecated kwargs-based NamedTuples +if sys.version_info >= (3, 13): + NamedTuple = typing.NamedTuple +else: + def _make_nmtuple(name, types, module, defaults=()): + fields = [n for n, t in types] + annotations = {n: typing._type_check(t, f"field {n} annotation must be a type") + for n, t in types} + nm_tpl = collections.namedtuple(name, fields, + defaults=defaults, module=module) + nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations + return nm_tpl + + _prohibited_namedtuple_fields = typing._prohibited + _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'}) + + class _NamedTupleMeta(type): + def __new__(cls, typename, bases, ns): + assert _NamedTuple in bases + for base in bases: + if base is not _NamedTuple and base is not typing.Generic: + raise TypeError( + 'can only inherit from a NamedTuple type and Generic') + bases = tuple(tuple if base is _NamedTuple else base for base in bases) + if "__annotations__" in ns: + types = ns["__annotations__"] + elif "__annotate__" in ns: + # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated + types = ns["__annotate__"](1) + else: + types = {} + default_names = [] + for field_name in types: + if field_name in ns: + default_names.append(field_name) + elif default_names: + raise TypeError(f"Non-default namedtuple field {field_name} " + f"cannot follow default field" + f"{'s' if len(default_names) > 1 else ''} " + f"{', '.join(default_names)}") + nm_tpl = _make_nmtuple( + typename, types.items(), + defaults=[ns[n] for n in default_names], + module=ns['__module__'] + ) + nm_tpl.__bases__ = bases + if typing.Generic in bases: + if hasattr(typing, '_generic_class_getitem'): # 3.12+ + nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem) + else: + class_getitem = typing.Generic.__class_getitem__.__func__ + nm_tpl.__class_getitem__ = classmethod(class_getitem) + # update from user namespace without overriding special namedtuple attributes + for key, val in ns.items(): + if key in _prohibited_namedtuple_fields: + raise AttributeError("Cannot overwrite NamedTuple attribute " + key) + elif key not in _special_namedtuple_fields: + if key not in nm_tpl._fields: + setattr(nm_tpl, key, ns[key]) + try: + set_name = type(val).__set_name__ + except AttributeError: + pass + else: + try: + set_name(val, nm_tpl, key) + except BaseException as e: + msg = ( + f"Error calling __set_name__ on {type(val).__name__!r} " + f"instance {key!r} in {typename!r}" + ) + # BaseException.add_note() existed on py311, + # but the __set_name__ machinery didn't start + # using add_note() until py312. + # Making sure exceptions are raised in the same way + # as in "normal" classes seems most important here. + if sys.version_info >= (3, 12): + e.add_note(msg) + raise + else: + raise RuntimeError(msg) from e + + if typing.Generic in bases: + nm_tpl.__init_subclass__() + return nm_tpl + + _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {}) + + def _namedtuple_mro_entries(bases): + assert NamedTuple in bases + return (_NamedTuple,) + + def NamedTuple(typename, fields=_marker, /, **kwargs): + """Typed version of namedtuple. + + Usage:: + + class Employee(NamedTuple): + name: str + id: int + + This is equivalent to:: + + Employee = collections.namedtuple('Employee', ['name', 'id']) + + The resulting class has an extra __annotations__ attribute, giving a + dict that maps field names to types. (The field names are also in + the _fields attribute, which is part of the namedtuple API.) + An alternative equivalent functional syntax is also accepted:: + + Employee = NamedTuple('Employee', [('name', str), ('id', int)]) + """ + if fields is _marker: + if kwargs: + deprecated_thing = "Creating NamedTuple classes using keyword arguments" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "Use the class-based or functional syntax instead." + ) + else: + deprecated_thing = "Failing to pass a value for the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif fields is None: + if kwargs: + raise TypeError( + "Cannot pass `None` as the 'fields' parameter " + "and also specify fields using keyword arguments" + ) + else: + deprecated_thing = "Passing `None` as the 'fields' parameter" + example = f"`{typename} = NamedTuple({typename!r}, [])`" + deprecation_msg = ( + "{name} is deprecated and will be disallowed in Python {remove}. " + "To create a NamedTuple class with 0 fields " + "using the functional syntax, " + "pass an empty list, e.g. " + ) + example + "." + elif kwargs: + raise TypeError("Either list of fields or keywords" + " can be provided to NamedTuple, not both") + if fields is _marker or fields is None: + warnings.warn( + deprecation_msg.format(name=deprecated_thing, remove="3.15"), + DeprecationWarning, + stacklevel=2, + ) + fields = kwargs.items() + nt = _make_nmtuple(typename, fields, module=_caller()) + nt.__orig_bases__ = (NamedTuple,) + return nt + + NamedTuple.__mro_entries__ = _namedtuple_mro_entries + + +if hasattr(collections.abc, "Buffer"): + Buffer = collections.abc.Buffer +else: + class Buffer(abc.ABC): # noqa: B024 + """Base class for classes that implement the buffer protocol. + + The buffer protocol allows Python objects to expose a low-level + memory buffer interface. Before Python 3.12, it is not possible + to implement the buffer protocol in pure Python code, or even + to check whether a class implements the buffer protocol. In + Python 3.12 and higher, the ``__buffer__`` method allows access + to the buffer protocol from Python code, and the + ``collections.abc.Buffer`` ABC allows checking whether a class + implements the buffer protocol. + + To indicate support for the buffer protocol in earlier versions, + inherit from this ABC, either in a stub file or at runtime, + or use ABC registration. This ABC provides no methods, because + there is no Python-accessible methods shared by pre-3.12 buffer + classes. It is useful primarily for static checks. + + """ + + # As a courtesy, register the most common stdlib buffer classes. + Buffer.register(memoryview) + Buffer.register(bytearray) + Buffer.register(bytes) + + +# Backport of types.get_original_bases, available on 3.12+ in CPython +if hasattr(_types, "get_original_bases"): + get_original_bases = _types.get_original_bases +else: + def get_original_bases(cls, /): + """Return the class's "original" bases prior to modification by `__mro_entries__`. + + Examples:: + + from typing import TypeVar, Generic + from typing_extensions import NamedTuple, TypedDict + + T = TypeVar("T") + class Foo(Generic[T]): ... + class Bar(Foo[int], float): ... + class Baz(list[str]): ... + Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) + Spam = TypedDict("Spam", {"a": int, "b": str}) + + assert get_original_bases(Bar) == (Foo[int], float) + assert get_original_bases(Baz) == (list[str],) + assert get_original_bases(Eggs) == (NamedTuple,) + assert get_original_bases(Spam) == (TypedDict,) + assert get_original_bases(int) == (object,) + """ + try: + return cls.__dict__.get("__orig_bases__", cls.__bases__) + except AttributeError: + raise TypeError( + f'Expected an instance of type, not {type(cls).__name__!r}' + ) from None + + +# NewType is a class on Python 3.10+, making it pickleable +# The error message for subclassing instances of NewType was improved on 3.11+ +if sys.version_info >= (3, 11): + NewType = typing.NewType +else: + class NewType: + """NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy callable that simply returns its argument. Usage:: + UserId = NewType('UserId', int) + def name_by_id(user_id: UserId) -> str: + ... + UserId('user') # Fails type check + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + num = UserId(5) + 1 # type: int + """ + + def __call__(self, obj, /): + return obj + + def __init__(self, name, tp): + self.__qualname__ = name + if '.' in name: + name = name.rpartition('.')[-1] + self.__name__ = name + self.__supertype__ = tp + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __mro_entries__(self, bases): + # We defined __mro_entries__ to get a better error message + # if a user attempts to subclass a NewType instance. bpo-46170 + supercls_name = self.__name__ + + class Dummy: + def __init_subclass__(cls): + subcls_name = cls.__name__ + raise TypeError( + f"Cannot subclass an instance of NewType. " + f"Perhaps you were looking for: " + f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`" + ) + + return (Dummy,) + + def __repr__(self): + return f'{self.__module__}.{self.__qualname__}' + + def __reduce__(self): + return self.__qualname__ + + if sys.version_info >= (3, 10): + # PEP 604 methods + # It doesn't make sense to have these methods on Python <3.10 + + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + +if sys.version_info >= (3, 14): + TypeAliasType = typing.TypeAliasType +# <=3.13 +else: + if sys.version_info >= (3, 12): + # 3.12-3.13 + def _is_unionable(obj): + """Corresponds to is_unionable() in unionobject.c in CPython.""" + return obj is None or isinstance(obj, ( + type, + _types.GenericAlias, + _types.UnionType, + typing.TypeAliasType, + TypeAliasType, + )) + else: + # <=3.11 + def _is_unionable(obj): + """Corresponds to is_unionable() in unionobject.c in CPython.""" + return obj is None or isinstance(obj, ( + type, + _types.GenericAlias, + _types.UnionType, + TypeAliasType, + )) + + if sys.version_info < (3, 10): + # Copied and pasted from https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Objects/genericaliasobject.c#L568-L582, + # so that we emulate the behaviour of `types.GenericAlias` + # on the latest versions of CPython + _ATTRIBUTE_DELEGATION_EXCLUSIONS = frozenset({ + "__class__", + "__bases__", + "__origin__", + "__args__", + "__unpacked__", + "__parameters__", + "__typing_unpacked_tuple_args__", + "__mro_entries__", + "__reduce_ex__", + "__reduce__", + "__copy__", + "__deepcopy__", + }) + + class _TypeAliasGenericAlias(typing._GenericAlias, _root=True): + def __getattr__(self, attr): + if attr in _ATTRIBUTE_DELEGATION_EXCLUSIONS: + return object.__getattr__(self, attr) + return getattr(self.__origin__, attr) + + + class TypeAliasType: + """Create named, parameterized type aliases. + + This provides a backport of the new `type` statement in Python 3.12: + + type ListOrSet[T] = list[T] | set[T] + + is equivalent to: + + T = TypeVar("T") + ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) + + The name ListOrSet can then be used as an alias for the type it refers to. + + The type_params argument should contain all the type parameters used + in the value of the type alias. If the alias is not generic, this + argument is omitted. + + Static type checkers should only support type aliases declared using + TypeAliasType that follow these rules: + + - The first argument (the name) must be a string literal. + - The TypeAliasType instance must be immediately assigned to a variable + of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, + as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). + + """ + + def __init__(self, name: str, value, *, type_params=()): + if not isinstance(name, str): + raise TypeError("TypeAliasType name must be a string") + if not isinstance(type_params, tuple): + raise TypeError("type_params must be a tuple") + self.__value__ = value + self.__type_params__ = type_params + + default_value_encountered = False + parameters = [] + for type_param in type_params: + if ( + not isinstance(type_param, (TypeVar, TypeVarTuple, ParamSpec)) + # <=3.11 + # Unpack Backport passes isinstance(type_param, TypeVar) + or _is_unpack(type_param) + ): + raise TypeError(f"Expected a type param, got {type_param!r}") + has_default = ( + getattr(type_param, '__default__', NoDefault) is not NoDefault + ) + if default_value_encountered and not has_default: + raise TypeError(f"non-default type parameter '{type_param!r}'" + " follows default type parameter") + if has_default: + default_value_encountered = True + if isinstance(type_param, TypeVarTuple): + parameters.extend(type_param) + else: + parameters.append(type_param) + self.__parameters__ = tuple(parameters) + def_mod = _caller() + if def_mod != 'typing_extensions': + self.__module__ = def_mod + # Setting this attribute closes the TypeAliasType from further modification + self.__name__ = name + + def __setattr__(self, name: str, value: object, /) -> None: + if hasattr(self, "__name__"): + self._raise_attribute_error(name) + super().__setattr__(name, value) + + def __delattr__(self, name: str, /) -> Never: + self._raise_attribute_error(name) + + def _raise_attribute_error(self, name: str) -> Never: + # Match the Python 3.12 error messages exactly + if name == "__name__": + raise AttributeError("readonly attribute") + elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}: + raise AttributeError( + f"attribute '{name}' of 'typing.TypeAliasType' objects " + "is not writable" + ) + else: + raise AttributeError( + f"'typing.TypeAliasType' object has no attribute '{name}'" + ) + + def __repr__(self) -> str: + return self.__name__ + + if sys.version_info < (3, 11): + def _check_single_param(self, param, recursion=0): + # Allow [], [int], [int, str], [int, ...], [int, T] + if param is ...: + return ... + if param is None: + return None + # Note in <= 3.9 _ConcatenateGenericAlias inherits from list + if isinstance(param, list) and recursion == 0: + return [self._check_single_param(arg, recursion+1) + for arg in param] + return typing._type_check( + param, f'Subscripting {self.__name__} requires a type.' + ) + + def _check_parameters(self, parameters): + if sys.version_info < (3, 11): + return tuple( + self._check_single_param(item) + for item in parameters + ) + return tuple(typing._type_check( + item, f'Subscripting {self.__name__} requires a type.' + ) + for item in parameters + ) + + def __getitem__(self, parameters): + if not self.__type_params__: + raise TypeError("Only generic type aliases are subscriptable") + if not isinstance(parameters, tuple): + parameters = (parameters,) + # Using 3.9 here will create problems with Concatenate + if sys.version_info >= (3, 10): + return _types.GenericAlias(self, parameters) + type_vars = _collect_type_vars(parameters) + parameters = self._check_parameters(parameters) + alias = _TypeAliasGenericAlias(self, parameters) + # alias.__parameters__ is not complete if Concatenate is present + # as it is converted to a list from which no parameters are extracted. + if alias.__parameters__ != type_vars: + alias.__parameters__ = type_vars + return alias + + def __reduce__(self): + return self.__name__ + + def __init_subclass__(cls, *args, **kwargs): + raise TypeError( + "type 'typing_extensions.TypeAliasType' is not an acceptable base type" + ) + + # The presence of this method convinces typing._type_check + # that TypeAliasTypes are types. + def __call__(self): + raise TypeError("Type alias is not callable") + + if sys.version_info >= (3, 10): + def __or__(self, right): + # For forward compatibility with 3.12, reject Unions + # that are not accepted by the built-in Union. + if not _is_unionable(right): + return NotImplemented + return typing.Union[self, right] + + def __ror__(self, left): + if not _is_unionable(left): + return NotImplemented + return typing.Union[left, self] + + +if hasattr(typing, "is_protocol"): + is_protocol = typing.is_protocol + get_protocol_members = typing.get_protocol_members +else: + def is_protocol(tp: type, /) -> bool: + """Return True if the given type is a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, is_protocol + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> is_protocol(P) + True + >>> is_protocol(int) + False + """ + return ( + isinstance(tp, type) + and getattr(tp, '_is_protocol', False) + and tp is not Protocol + and tp is not typing.Protocol + ) + + def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]: + """Return the set of members defined in a Protocol. + + Example:: + + >>> from typing_extensions import Protocol, get_protocol_members + >>> class P(Protocol): + ... def a(self) -> str: ... + ... b: int + >>> get_protocol_members(P) + frozenset({'a', 'b'}) + + Raise a TypeError for arguments that are not Protocols. + """ + if not is_protocol(tp): + raise TypeError(f'{tp!r} is not a Protocol') + if hasattr(tp, '__protocol_attrs__'): + return frozenset(tp.__protocol_attrs__) + return frozenset(_get_protocol_attrs(tp)) + + +if hasattr(typing, "Doc"): + Doc = typing.Doc +else: + class Doc: + """Define the documentation of a type annotation using ``Annotated``, to be + used in class attributes, function and method parameters, return values, + and variables. + + The value should be a positional-only string literal to allow static tools + like editors and documentation generators to use it. + + This complements docstrings. + + The string value passed is available in the attribute ``documentation``. + + Example:: + + >>> from typing_extensions import Annotated, Doc + >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ... + """ + def __init__(self, documentation: str, /) -> None: + self.documentation = documentation + + def __repr__(self) -> str: + return f"Doc({self.documentation!r})" + + def __hash__(self) -> int: + return hash(self.documentation) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Doc): + return NotImplemented + return self.documentation == other.documentation + + +_CapsuleType = getattr(_types, "CapsuleType", None) + +if _CapsuleType is None: + try: + import _socket + except ImportError: + pass + else: + _CAPI = getattr(_socket, "CAPI", None) + if _CAPI is not None: + _CapsuleType = type(_CAPI) + +if _CapsuleType is not None: + CapsuleType = _CapsuleType + __all__.append("CapsuleType") + + +if sys.version_info >= (3,14): + from annotationlib import Format, get_annotations +else: + class Format(enum.IntEnum): + VALUE = 1 + VALUE_WITH_FAKE_GLOBALS = 2 + FORWARDREF = 3 + STRING = 4 + + def get_annotations(obj, *, globals=None, locals=None, eval_str=False, + format=Format.VALUE): + """Compute the annotations dict for an object. + + obj may be a callable, class, or module. + Passing in an object of any other type raises TypeError. + + Returns a dict. get_annotations() returns a new dict every time + it's called; calling it twice on the same object will return two + different but equivalent dicts. + + This is a backport of `inspect.get_annotations`, which has been + in the standard library since Python 3.10. See the standard library + documentation for more: + + https://docs.python.org/3/library/inspect.html#inspect.get_annotations + + This backport adds the *format* argument introduced by PEP 649. The + three formats supported are: + * VALUE: the annotations are returned as-is. This is the default and + it is compatible with the behavior on previous Python versions. + * FORWARDREF: return annotations as-is if possible, but replace any + undefined names with ForwardRef objects. The implementation proposed by + PEP 649 relies on language changes that cannot be backported; the + typing-extensions implementation simply returns the same result as VALUE. + * STRING: return annotations as strings, in a format close to the original + source. Again, this behavior cannot be replicated directly in a backport. + As an approximation, typing-extensions retrieves the annotations under + VALUE semantics and then stringifies them. + + The purpose of this backport is to allow users who would like to use + FORWARDREF or STRING semantics once PEP 649 is implemented, but who also + want to support earlier Python versions, to simply write: + + typing_extensions.get_annotations(obj, format=Format.FORWARDREF) + + """ + format = Format(format) + if format is Format.VALUE_WITH_FAKE_GLOBALS: + raise ValueError( + "The VALUE_WITH_FAKE_GLOBALS format is for internal use only" + ) + + if eval_str and format is not Format.VALUE: + raise ValueError("eval_str=True is only supported with format=Format.VALUE") + + if isinstance(obj, type): + # class + obj_dict = getattr(obj, '__dict__', None) + if obj_dict and hasattr(obj_dict, 'get'): + ann = obj_dict.get('__annotations__', None) + if isinstance(ann, _types.GetSetDescriptorType): + ann = None + else: + ann = None + + obj_globals = None + module_name = getattr(obj, '__module__', None) + if module_name: + module = sys.modules.get(module_name, None) + if module: + obj_globals = getattr(module, '__dict__', None) + obj_locals = dict(vars(obj)) + unwrap = obj + elif isinstance(obj, _types.ModuleType): + # module + ann = getattr(obj, '__annotations__', None) + obj_globals = obj.__dict__ + obj_locals = None + unwrap = None + elif callable(obj): + # this includes types.Function, types.BuiltinFunctionType, + # types.BuiltinMethodType, functools.partial, functools.singledispatch, + # "class funclike" from Lib/test/test_inspect... on and on it goes. + ann = getattr(obj, '__annotations__', None) + obj_globals = getattr(obj, '__globals__', None) + obj_locals = None + unwrap = obj + elif hasattr(obj, '__annotations__'): + ann = obj.__annotations__ + obj_globals = obj_locals = unwrap = None + else: + raise TypeError(f"{obj!r} is not a module, class, or callable.") + + if ann is None: + return {} + + if not isinstance(ann, dict): + raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None") + + if not ann: + return {} + + if not eval_str: + if format is Format.STRING: + return { + key: value if isinstance(value, str) else typing._type_repr(value) + for key, value in ann.items() + } + return dict(ann) + + if unwrap is not None: + while True: + if hasattr(unwrap, '__wrapped__'): + unwrap = unwrap.__wrapped__ + continue + if isinstance(unwrap, functools.partial): + unwrap = unwrap.func + continue + break + if hasattr(unwrap, "__globals__"): + obj_globals = unwrap.__globals__ + + if globals is None: + globals = obj_globals + if locals is None: + locals = obj_locals or {} + + # "Inject" type parameters into the local namespace + # (unless they are shadowed by assignments *in* the local namespace), + # as a way of emulating annotation scopes when calling `eval()` + if type_params := getattr(obj, "__type_params__", ()): + locals = {param.__name__: param for param in type_params} | locals + + return_value = {key: + value if not isinstance(value, str) else eval(value, globals, locals) + for key, value in ann.items() } + return return_value + + +if hasattr(typing, "evaluate_forward_ref"): + evaluate_forward_ref = typing.evaluate_forward_ref +else: + # Implements annotationlib.ForwardRef.evaluate + def _eval_with_owner( + forward_ref, *, owner=None, globals=None, locals=None, type_params=None + ): + if forward_ref.__forward_evaluated__: + return forward_ref.__forward_value__ + if getattr(forward_ref, "__cell__", None) is not None: + try: + value = forward_ref.__cell__.cell_contents + except ValueError: + pass + else: + forward_ref.__forward_evaluated__ = True + forward_ref.__forward_value__ = value + return value + if owner is None: + owner = getattr(forward_ref, "__owner__", None) + + if ( + globals is None + and getattr(forward_ref, "__forward_module__", None) is not None + ): + globals = getattr( + sys.modules.get(forward_ref.__forward_module__, None), "__dict__", None + ) + if globals is None: + globals = getattr(forward_ref, "__globals__", None) + if globals is None: + if isinstance(owner, type): + module_name = getattr(owner, "__module__", None) + if module_name: + module = sys.modules.get(module_name, None) + if module: + globals = getattr(module, "__dict__", None) + elif isinstance(owner, _types.ModuleType): + globals = getattr(owner, "__dict__", None) + elif callable(owner): + globals = getattr(owner, "__globals__", None) + + # If we pass None to eval() below, the globals of this module are used. + if globals is None: + globals = {} + + if locals is None: + locals = {} + if isinstance(owner, type): + locals.update(vars(owner)) + + if type_params is None and owner is not None: + # "Inject" type parameters into the local namespace + # (unless they are shadowed by assignments *in* the local namespace), + # as a way of emulating annotation scopes when calling `eval()` + type_params = getattr(owner, "__type_params__", None) + + # type parameters require some special handling, + # as they exist in their own scope + # but `eval()` does not have a dedicated parameter for that scope. + # For classes, names in type parameter scopes should override + # names in the global scope (which here are called `localns`!), + # but should in turn be overridden by names in the class scope + # (which here are called `globalns`!) + if type_params is not None: + globals = dict(globals) + locals = dict(locals) + for param in type_params: + param_name = param.__name__ + if ( + _FORWARD_REF_HAS_CLASS and not forward_ref.__forward_is_class__ + ) or param_name not in globals: + globals[param_name] = param + locals.pop(param_name, None) + + arg = forward_ref.__forward_arg__ + if arg.isidentifier() and not keyword.iskeyword(arg): + if arg in locals: + value = locals[arg] + elif arg in globals: + value = globals[arg] + elif hasattr(builtins, arg): + return getattr(builtins, arg) + else: + raise NameError(arg) + else: + code = forward_ref.__forward_code__ + value = eval(code, globals, locals) + forward_ref.__forward_evaluated__ = True + forward_ref.__forward_value__ = value + return value + + def evaluate_forward_ref( + forward_ref, + *, + owner=None, + globals=None, + locals=None, + type_params=None, + format=None, + _recursive_guard=frozenset(), + ): + """Evaluate a forward reference as a type hint. + + This is similar to calling the ForwardRef.evaluate() method, + but unlike that method, evaluate_forward_ref() also: + + * Recursively evaluates forward references nested within the type hint. + * Rejects certain objects that are not valid type hints. + * Replaces type hints that evaluate to None with types.NoneType. + * Supports the *FORWARDREF* and *STRING* formats. + + *forward_ref* must be an instance of ForwardRef. *owner*, if given, + should be the object that holds the annotations that the forward reference + derived from, such as a module, class object, or function. It is used to + infer the namespaces to use for looking up names. *globals* and *locals* + can also be explicitly given to provide the global and local namespaces. + *type_params* is a tuple of type parameters that are in scope when + evaluating the forward reference. This parameter must be provided (though + it may be an empty tuple) if *owner* is not given and the forward reference + does not already have an owner set. *format* specifies the format of the + annotation and is a member of the annotationlib.Format enum. + + """ + if format == Format.STRING: + return forward_ref.__forward_arg__ + if forward_ref.__forward_arg__ in _recursive_guard: + return forward_ref + + # Evaluate the forward reference + try: + value = _eval_with_owner( + forward_ref, + owner=owner, + globals=globals, + locals=locals, + type_params=type_params, + ) + except NameError: + if format == Format.FORWARDREF: + return forward_ref + else: + raise + + if isinstance(value, str): + value = ForwardRef(value) + + # Recursively evaluate the type + if isinstance(value, ForwardRef): + if getattr(value, "__forward_module__", True) is not None: + globals = None + return evaluate_forward_ref( + value, + globals=globals, + locals=locals, + type_params=type_params, owner=owner, + _recursive_guard=_recursive_guard, format=format + ) + if sys.version_info < (3, 12, 5) and type_params: + # Make use of type_params + locals = dict(locals) if locals else {} + for tvar in type_params: + if tvar.__name__ not in locals: # lets not overwrite something present + locals[tvar.__name__] = tvar + if sys.version_info < (3, 12, 5): + return typing._eval_type( + value, + globals, + locals, + recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, + ) + else: + return typing._eval_type( + value, + globals, + locals, + type_params, + recursive_guard=_recursive_guard | {forward_ref.__forward_arg__}, + ) + + +class Sentinel: + """Create a unique sentinel object. + + *name* should be the name of the variable to which the return value shall be assigned. + + *repr*, if supplied, will be used for the repr of the sentinel object. + If not provided, "" will be used. + """ + + def __init__( + self, + name: str, + repr: typing.Optional[str] = None, + ): + self._name = name + self._repr = repr if repr is not None else f'<{name}>' + + def __repr__(self): + return self._repr + + if sys.version_info < (3, 11): + # The presence of this method convinces typing._type_check + # that Sentinels are types. + def __call__(self, *args, **kwargs): + raise TypeError(f"{type(self).__name__!r} object is not callable") + + if sys.version_info >= (3, 10): + def __or__(self, other): + return typing.Union[self, other] + + def __ror__(self, other): + return typing.Union[other, self] + + def __getstate__(self): + raise TypeError(f"Cannot pickle {type(self).__name__!r} object") + + +# Aliases for items that are in typing in all supported versions. +# We use hasattr() checks so this library will continue to import on +# future versions of Python that may remove these names. +_typing_names = [ + "AbstractSet", + "AnyStr", + "BinaryIO", + "Callable", + "Collection", + "Container", + "Dict", + "FrozenSet", + "Hashable", + "IO", + "ItemsView", + "Iterable", + "Iterator", + "KeysView", + "List", + "Mapping", + "MappingView", + "Match", + "MutableMapping", + "MutableSequence", + "MutableSet", + "Optional", + "Pattern", + "Reversible", + "Sequence", + "Set", + "Sized", + "TextIO", + "Tuple", + "Union", + "ValuesView", + "cast", + "no_type_check", + "no_type_check_decorator", + # This is private, but it was defined by typing_extensions for a long time + # and some users rely on it. + "_AnnotatedAlias", +] +globals().update( + {name: getattr(typing, name) for name in _typing_names if hasattr(typing, name)} +) +# These are defined unconditionally because they are used in +# typing-extensions itself. +Generic = typing.Generic +ForwardRef = typing.ForwardRef +Annotated = typing.Annotated diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/INSTALLER b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/METADATA b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..1e411d8f16ed2993132b521ce537997b204a6c6b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/METADATA @@ -0,0 +1,2427 @@ +Metadata-Version: 2.4 +Name: yarl +Version: 1.20.1 +Summary: Yet another URL library +Home-page: https://github.com/aio-libs/yarl +Author: Andrew Svetlov +Author-email: andrew.svetlov@gmail.com +Maintainer: aiohttp team +Maintainer-email: team@aiohttp.org +License: Apache-2.0 +Project-URL: Chat: Matrix, https://matrix.to/#/#aio-libs:matrix.org +Project-URL: Chat: Matrix Space, https://matrix.to/#/#aio-libs-space:matrix.org +Project-URL: CI: GitHub Workflows, https://github.com/aio-libs/yarl/actions?query=branch:master +Project-URL: Code of Conduct, https://github.com/aio-libs/.github/blob/master/CODE_OF_CONDUCT.md +Project-URL: Coverage: codecov, https://codecov.io/github/aio-libs/yarl +Project-URL: Docs: Changelog, https://yarl.aio-libs.org/en/latest/changes/ +Project-URL: Docs: RTD, https://yarl.aio-libs.org +Project-URL: GitHub: issues, https://github.com/aio-libs/yarl/issues +Project-URL: GitHub: repo, https://github.com/aio-libs/yarl +Keywords: cython,cext,yarl +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Programming Language :: Cython +Classifier: Programming Language :: Python +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3.12 +Classifier: Programming Language :: Python :: 3.13 +Classifier: Topic :: Internet :: WWW/HTTP +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Requires-Python: >=3.9 +Description-Content-Type: text/x-rst +License-File: LICENSE +License-File: NOTICE +Requires-Dist: idna>=2.0 +Requires-Dist: multidict>=4.0 +Requires-Dist: propcache>=0.2.1 +Dynamic: license-file + +yarl +==== + +The module provides handy URL class for URL parsing and changing. + +.. image:: https://github.com/aio-libs/yarl/workflows/CI/badge.svg + :target: https://github.com/aio-libs/yarl/actions?query=workflow%3ACI + :align: right + +.. image:: https://codecov.io/gh/aio-libs/yarl/graph/badge.svg?flag=pytest + :target: https://app.codecov.io/gh/aio-libs/yarl?flags[]=pytest + :alt: Codecov coverage for the pytest-driven measurements + +.. image:: https://img.shields.io/endpoint?url=https://codspeed.io/badge.json + :target: https://codspeed.io/aio-libs/yarl + +.. image:: https://badge.fury.io/py/yarl.svg + :target: https://badge.fury.io/py/yarl + +.. image:: https://readthedocs.org/projects/yarl/badge/?version=latest + :target: https://yarl.aio-libs.org + +.. image:: https://img.shields.io/pypi/pyversions/yarl.svg + :target: https://pypi.python.org/pypi/yarl + +.. image:: https://img.shields.io/matrix/aio-libs:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs:matrix.org + :alt: Matrix Room — #aio-libs:matrix.org + +.. image:: https://img.shields.io/matrix/aio-libs-space:matrix.org?label=Discuss%20on%20Matrix%20at%20%23aio-libs-space%3Amatrix.org&logo=matrix&server_fqdn=matrix.org&style=flat + :target: https://matrix.to/#/%23aio-libs-space:matrix.org + :alt: Matrix Space — #aio-libs-space:matrix.org + + +Introduction +------------ + +Url is constructed from ``str``: + +.. code-block:: pycon + + >>> from yarl import URL + >>> url = URL('https://www.python.org/~guido?arg=1#frag') + >>> url + URL('https://www.python.org/~guido?arg=1#frag') + +All url parts: *scheme*, *user*, *password*, *host*, *port*, *path*, +*query* and *fragment* are accessible by properties: + +.. code-block:: pycon + + >>> url.scheme + 'https' + >>> url.host + 'www.python.org' + >>> url.path + '/~guido' + >>> url.query_string + 'arg=1' + >>> url.query + + >>> url.fragment + 'frag' + +All url manipulations produce a new url object: + +.. code-block:: pycon + + >>> url = URL('https://www.python.org') + >>> url / 'foo' / 'bar' + URL('https://www.python.org/foo/bar') + >>> url / 'foo' % {'bar': 'baz'} + URL('https://www.python.org/foo?bar=baz') + +Strings passed to constructor and modification methods are +automatically encoded giving canonical representation as result: + +.. code-block:: pycon + + >>> url = URL('https://www.python.org/шлях') + >>> url + URL('https://www.python.org/%D1%88%D0%BB%D1%8F%D1%85') + +Regular properties are *percent-decoded*, use ``raw_`` versions for +getting *encoded* strings: + +.. code-block:: pycon + + >>> url.path + '/шлях' + + >>> url.raw_path + '/%D1%88%D0%BB%D1%8F%D1%85' + +Human readable representation of URL is available as ``.human_repr()``: + +.. code-block:: pycon + + >>> url.human_repr() + 'https://www.python.org/шлях' + +For full documentation please read https://yarl.aio-libs.org. + + +Installation +------------ + +:: + + $ pip install yarl + +The library is Python 3 only! + +PyPI contains binary wheels for Linux, Windows and MacOS. If you want to install +``yarl`` on another operating system where wheels are not provided, +the tarball will be used to compile the library from +the source code. It requires a C compiler and and Python headers installed. + +To skip the compilation you must explicitly opt-in by using a PEP 517 +configuration setting ``pure-python``, or setting the ``YARL_NO_EXTENSIONS`` +environment variable to a non-empty value, e.g.: + +.. code-block:: console + + $ pip install yarl --config-settings=pure-python=false + +Please note that the pure-Python (uncompiled) version is much slower. However, +PyPy always uses a pure-Python implementation, and, as such, it is unaffected +by this variable. + +Dependencies +------------ + +YARL requires multidict_ and propcache_ libraries. + + +API documentation +------------------ + +The documentation is located at https://yarl.aio-libs.org. + + +Why isn't boolean supported by the URL query API? +------------------------------------------------- + +There is no standard for boolean representation of boolean values. + +Some systems prefer ``true``/``false``, others like ``yes``/``no``, ``on``/``off``, +``Y``/``N``, ``1``/``0``, etc. + +``yarl`` cannot make an unambiguous decision on how to serialize ``bool`` values because +it is specific to how the end-user's application is built and would be different for +different apps. The library doesn't accept booleans in the API; a user should convert +bools into strings using own preferred translation protocol. + + +Comparison with other URL libraries +------------------------------------ + +* furl (https://pypi.python.org/pypi/furl) + + The library has rich functionality but the ``furl`` object is mutable. + + I'm afraid to pass this object into foreign code: who knows if the + code will modify my url in a terrible way while I just want to send URL + with handy helpers for accessing URL properties. + + ``furl`` has other non-obvious tricky things but the main objection + is mutability. + +* URLObject (https://pypi.python.org/pypi/URLObject) + + URLObject is immutable, that's pretty good. + + Every URL change generates a new URL object. + + But the library doesn't do any decode/encode transformations leaving the + end user to cope with these gory details. + + +Source code +----------- + +The project is hosted on GitHub_ + +Please file an issue on the `bug tracker +`_ if you have found a bug +or have some suggestion in order to improve the library. + +Discussion list +--------------- + +*aio-libs* google group: https://groups.google.com/forum/#!forum/aio-libs + +Feel free to post your questions and ideas here. + + +Authors and License +------------------- + +The ``yarl`` package is written by Andrew Svetlov. + +It's *Apache 2* licensed and freely available. + + +.. _GitHub: https://github.com/aio-libs/yarl + +.. _multidict: https://github.com/aio-libs/multidict + +.. _propcache: https://github.com/aio-libs/propcache + +========= +Changelog +========= + +.. + You should *NOT* be adding new change log entries to this file, this + file is managed by towncrier. You *may* edit previous change logs to + fix problems like typo corrections or such. + To add a new change log entry, please see + https://pip.pypa.io/en/latest/development/#adding-a-news-entry + we named the news folder "changes". + + WARNING: Don't drop the next directive! + +.. towncrier release notes start + +1.20.1 +====== + +*(2025-06-09)* + + +Bug fixes +--------- + +- Started raising a ``ValueError`` exception raised for corrupted + IPv6 URL values. + + These fixes the issue where exception ``IndexError`` was + leaking from the internal code because of not being handled and + transformed into a user-facing error. The problem was happening + under the following conditions: empty IPv6 URL, brackets in + reverse order. + + -- by `@MaelPic `__. + + *Related issues and pull requests on GitHub:* + `#1512 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Updated to use Cython 3.1 universally across the build path -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1514 `__. + +- Made Cython line tracing opt-in via the ``with-cython-tracing`` build config setting -- by `@bdraco `__. + + Previously, line tracing was enabled by default in ``pyproject.toml``, which caused build issues for some users and made wheels nearly twice as slow. + Now line tracing is only enabled when explicitly requested via ``pip install . --config-setting=with-cython-tracing=true`` or by setting the ``YARL_CYTHON_TRACING`` environment variable. + + *Related issues and pull requests on GitHub:* + `#1521 `__. + + +---- + + +1.20.0 +====== + +*(2025-04-16)* + + +Features +-------- + +- Implemented support for the free-threaded build of CPython 3.13 -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1456 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Started building wheels for the free-threaded build of CPython 3.13 -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1456 `__. + + +---- + + +1.19.0 +====== + +*(2025-04-05)* + + +Bug fixes +--------- + +- Fixed entire name being re-encoded when using ``yarl.URL.with_suffix()`` -- by `@NTFSvolume `__. + + *Related issues and pull requests on GitHub:* + `#1468 `__. + + +Features +-------- + +- Started building armv7l wheels for manylinux -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1495 `__. + + +Contributor-facing changes +-------------------------- + +- GitHub Actions CI/CD is now configured to manage caching pip-ecosystem + dependencies using `re-actors/cache-python-deps`_ -- an action by + `@webknjaz `__ that takes into account ABI stability and the exact + version of Python runtime. + + .. _`re-actors/cache-python-deps`: + https://github.com/marketplace/actions/cache-python-deps + + *Related issues and pull requests on GitHub:* + `#1471 `__. + +- Increased minimum `propcache`_ version to 0.2.1 to fix failing tests -- by `@bdraco `__. + + .. _`propcache`: + https://github.com/aio-libs/propcache + + *Related issues and pull requests on GitHub:* + `#1479 `__. + +- Added all hidden folders to pytest's ``norecursedirs`` to prevent it + from trying to collect tests there -- by `@lysnikolaou `__. + + *Related issues and pull requests on GitHub:* + `#1480 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved accuracy of type annotations -- by `@Dreamsorcerer `__. + + *Related issues and pull requests on GitHub:* + `#1484 `__. + +- Improved performance of parsing query strings -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1493 `__, `#1497 `__. + +- Improved performance of the C unquoter -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1496 `__, `#1498 `__. + + +---- + + +1.18.3 +====== + +*(2024-12-01)* + + +Bug fixes +--------- + +- Fixed uppercase ASCII hosts being rejected by ``URL.build()()`` and ``yarl.URL.with_host()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#954 `__, `#1442 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performances of multiple path properties on cache miss -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1443 `__. + + +---- + + +1.18.2 +====== + +*(2024-11-29)* + + +No significant changes. + + +---- + + +1.18.1 +====== + +*(2024-11-29)* + + +Miscellaneous internal changes +------------------------------ + +- Improved cache performance when ``~yarl.URL`` objects are constructed from ``yarl.URL.build()`` with ``encoded=True`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1432 `__. + +- Improved cache performance for operations that produce a new ``~yarl.URL`` object -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1434 `__, `#1436 `__. + + +---- + + +1.18.0 +====== + +*(2024-11-21)* + + +Features +-------- + +- Added ``keep_query`` and ``keep_fragment`` flags in the ``yarl.URL.with_path()``, ``yarl.URL.with_name()`` and ``yarl.URL.with_suffix()`` methods, allowing users to optionally retain the query string and fragment in the resulting URL when replacing the path -- by `@paul-nameless `__. + + *Related issues and pull requests on GitHub:* + `#111 `__, `#1421 `__. + + +Contributor-facing changes +-------------------------- + +- Started running downstream ``aiohttp`` tests in CI -- by `@Cycloctane `__. + + *Related issues and pull requests on GitHub:* + `#1415 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of converting ``~yarl.URL`` to a string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1422 `__. + + +---- + + +1.17.2 +====== + +*(2024-11-17)* + + +Bug fixes +--------- + +- Stopped implicitly allowing the use of Cython pre-release versions when + building the distribution package -- by `@ajsanchezsanz `__ and + `@markgreene74 `__. + + *Related issues and pull requests on GitHub:* + `#1411 `__, `#1412 `__. + +- Fixed a bug causing ``~yarl.URL.port`` to return the default port when the given port was zero + -- by `@gmacon `__. + + *Related issues and pull requests on GitHub:* + `#1413 `__. + + +Features +-------- + +- Make error messages include details of incorrect type when ``port`` is not int in ``yarl.URL.build()``. + -- by `@Cycloctane `__. + + *Related issues and pull requests on GitHub:* + `#1414 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Stopped implicitly allowing the use of Cython pre-release versions when + building the distribution package -- by `@ajsanchezsanz `__ and + `@markgreene74 `__. + + *Related issues and pull requests on GitHub:* + `#1411 `__, `#1412 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the ``yarl.URL.joinpath()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1418 `__. + + +---- + + +1.17.1 +====== + +*(2024-10-30)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of many ``~yarl.URL`` methods -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1396 `__, `#1397 `__, `#1398 `__. + +- Improved performance of passing a `dict` or `str` to ``yarl.URL.extend_query()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1401 `__. + + +---- + + +1.17.0 +====== + +*(2024-10-28)* + + +Features +-------- + +- Added ``~yarl.URL.host_port_subcomponent`` which returns the ``3986#section-3.2.2`` host and ``3986#section-3.2.3`` port subcomponent -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1375 `__. + + +---- + + +1.16.0 +====== + +*(2024-10-21)* + + +Bug fixes +--------- + +- Fixed blocking I/O to load Python code when creating a new ``~yarl.URL`` with non-ascii characters in the network location part -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1342 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Migrated to using a single cache for encoding hosts -- by `@bdraco `__. + + Passing ``ip_address_size`` and ``host_validate_size`` to ``yarl.cache_configure()`` is deprecated in favor of the new ``encode_host_size`` parameter and will be removed in a future release. For backwards compatibility, the old parameters affect the ``encode_host`` cache size. + + *Related issues and pull requests on GitHub:* + `#1348 `__, `#1357 `__, `#1363 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of constructing ``~yarl.URL`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1336 `__. + +- Improved performance of calling ``yarl.URL.build()`` and constructing unencoded ``~yarl.URL`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1345 `__. + +- Reworked the internal encoding cache to improve performance on cache hit -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1369 `__. + + +---- + + +1.15.5 +====== + +*(2024-10-18)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the ``yarl.URL.joinpath()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1304 `__. + +- Improved performance of the ``yarl.URL.extend_query()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1305 `__. + +- Improved performance of the ``yarl.URL.origin()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1306 `__. + +- Improved performance of the ``yarl.URL.with_path()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1307 `__. + +- Improved performance of the ``yarl.URL.with_query()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1308 `__, `#1328 `__. + +- Improved performance of the ``yarl.URL.update_query()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1309 `__, `#1327 `__. + +- Improved performance of the ``yarl.URL.join()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1313 `__. + +- Improved performance of ``~yarl.URL`` equality checks -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1315 `__. + +- Improved performance of ``~yarl.URL`` methods that modify the network location -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1316 `__. + +- Improved performance of the ``yarl.URL.with_fragment()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1317 `__. + +- Improved performance of calculating the hash of ``~yarl.URL`` objects -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1318 `__. + +- Improved performance of the ``yarl.URL.relative()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1319 `__. + +- Improved performance of the ``yarl.URL.with_name()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1320 `__. + +- Improved performance of ``~yarl.URL.parent`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1321 `__. + +- Improved performance of the ``yarl.URL.with_scheme()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1322 `__. + + +---- + + +1.15.4 +====== + +*(2024-10-16)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the quoter when all characters are safe -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1288 `__. + +- Improved performance of unquoting strings -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1292 `__, `#1293 `__. + +- Improved performance of calling ``yarl.URL.build()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1297 `__. + + +---- + + +1.15.3 +====== + +*(2024-10-15)* + + +Bug fixes +--------- + +- Fixed ``yarl.URL.build()`` failing to validate paths must start with a ``/`` when passing ``authority`` -- by `@bdraco `__. + + The validation only worked correctly when passing ``host``. + + *Related issues and pull requests on GitHub:* + `#1265 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Removed support for Python 3.8 as it has reached end of life -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1203 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of constructing ``~yarl.URL`` when the net location is only the host -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1271 `__. + + +---- + + +1.15.2 +====== + +*(2024-10-13)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of converting ``~yarl.URL`` to a string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1234 `__. + +- Improved performance of ``yarl.URL.joinpath()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1248 `__, `#1250 `__. + +- Improved performance of constructing query strings from ``~multidict.MultiDict`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1256 `__. + +- Improved performance of constructing query strings with ``int`` values -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1259 `__. + + +---- + + +1.15.1 +====== + +*(2024-10-12)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of calling ``yarl.URL.build()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1222 `__. + +- Improved performance of all ``~yarl.URL`` methods that create new ``~yarl.URL`` objects -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1226 `__. + +- Improved performance of ``~yarl.URL`` methods that modify the network location -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1229 `__. + + +---- + + +1.15.0 +====== + +*(2024-10-11)* + + +Bug fixes +--------- + +- Fixed validation with ``yarl.URL.with_scheme()`` when passed scheme is not lowercase -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1189 `__. + + +Features +-------- + +- Started building ``armv7l`` wheels -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1204 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of constructing unencoded ``~yarl.URL`` objects -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1188 `__. + +- Added a cache for parsing hosts to reduce overhead of encoding ``~yarl.URL`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1190 `__. + +- Improved performance of constructing query strings from ``~collections.abc.Mapping`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1193 `__. + +- Improved performance of converting ``~yarl.URL`` objects to strings -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1198 `__. + + +---- + + +1.14.0 +====== + +*(2024-10-08)* + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Switched to using the ``propcache`` package for property caching + -- by `@bdraco `__. + + The ``propcache`` package is derived from the property caching + code in ``yarl`` and has been broken out to avoid maintaining it for multiple + projects. + + *Related issues and pull requests on GitHub:* + `#1169 `__. + + +Contributor-facing changes +-------------------------- + +- Started testing with Hypothesis -- by `@webknjaz `__ and `@bdraco `__. + + Special thanks to `@Zac-HD `__ for helping us get started with this framework. + + *Related issues and pull requests on GitHub:* + `#860 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of ``yarl.URL.is_default_port()`` when no explicit port is set -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1168 `__. + +- Improved performance of converting ``~yarl.URL`` to a string when no explicit port is set -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1170 `__. + +- Improved performance of the ``yarl.URL.origin()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1175 `__. + +- Improved performance of encoding hosts -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1176 `__. + + +---- + + +1.13.1 +====== + +*(2024-09-27)* + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of calling ``yarl.URL.build()`` with ``authority`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1163 `__. + + +---- + + +1.13.0 +====== + +*(2024-09-26)* + + +Bug fixes +--------- + +- Started rejecting ASCII hostnames with invalid characters. For host strings that + look like authority strings, the exception message includes advice on what to do + instead -- by `@mjpieters `__. + + *Related issues and pull requests on GitHub:* + `#880 `__, `#954 `__. + +- Fixed IPv6 addresses missing brackets when the ``~yarl.URL`` was converted to a string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1157 `__, `#1158 `__. + + +Features +-------- + +- Added ``~yarl.URL.host_subcomponent`` which returns the ``3986#section-3.2.2`` host subcomponent -- by `@bdraco `__. + + The only current practical difference between ``~yarl.URL.raw_host`` and ``~yarl.URL.host_subcomponent`` is that IPv6 addresses are returned bracketed. + + *Related issues and pull requests on GitHub:* + `#1159 `__. + + +---- + + +1.12.1 +====== + +*(2024-09-23)* + + +No significant changes. + + +---- + + +1.12.0 +====== + +*(2024-09-23)* + + +Features +-------- + +- Added ``~yarl.URL.path_safe`` to be able to fetch the path without ``%2F`` and ``%25`` decoded -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1150 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Restore decoding ``%2F`` (``/``) in ``URL.path`` -- by `@bdraco `__. + + This change restored the behavior before `#1057 `__. + + *Related issues and pull requests on GitHub:* + `#1151 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of processing paths -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1143 `__. + + +---- + + +1.11.1 +====== + +*(2024-09-09)* + + +Bug fixes +--------- + +- Allowed scheme replacement for relative URLs if the scheme does not require a host -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#280 `__, `#1138 `__. + +- Allowed empty host for URL schemes other than the special schemes listed in the WHATWG URL spec -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1136 `__. + + +Features +-------- + +- Loosened restriction on integers as query string values to allow classes that implement ``__int__`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1139 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of normalizing paths -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1137 `__. + + +---- + + +1.11.0 +====== + +*(2024-09-08)* + + +Features +-------- + +- Added ``URL.extend_query()()`` method, which can be used to extend parameters without replacing same named keys -- by `@bdraco `__. + + This method was primarily added to replace the inefficient hand rolled method currently used in ``aiohttp``. + + *Related issues and pull requests on GitHub:* + `#1128 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of the Cython ``cached_property`` implementation -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1122 `__. + +- Simplified computing ports by removing unnecessary code -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1123 `__. + +- Improved performance of encoding non IPv6 hosts -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1125 `__. + +- Improved performance of ``URL.build()()`` when the path, query string, or fragment is an empty string -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1126 `__. + +- Improved performance of the ``URL.update_query()()`` method -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1130 `__. + +- Improved performance of processing query string changes when arguments are ``str`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1131 `__. + + +---- + + +1.10.0 +====== + +*(2024-09-06)* + + +Bug fixes +--------- + +- Fixed joining a path when the existing path was empty -- by `@bdraco `__. + + A regression in ``URL.join()()`` was introduced in `#1082 `__. + + *Related issues and pull requests on GitHub:* + `#1118 `__. + + +Features +-------- + +- Added ``URL.without_query_params()()`` method, to drop some parameters from query string -- by `@hongquan `__. + + *Related issues and pull requests on GitHub:* + `#774 `__, `#898 `__, `#1010 `__. + +- The previously protected types ``_SimpleQuery``, ``_QueryVariable``, and ``_Query`` are now available for use externally as ``SimpleQuery``, ``QueryVariable``, and ``Query`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1050 `__, `#1113 `__. + + +Contributor-facing changes +-------------------------- + +- Replaced all ``~typing.Optional`` with ``~typing.Union`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1095 `__. + + +Miscellaneous internal changes +------------------------------ + +- Significantly improved performance of parsing the network location -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1112 `__. + +- Added internal types to the cache to prevent future refactoring errors -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1117 `__. + + +---- + + +1.9.11 +====== + +*(2024-09-04)* + + +Bug fixes +--------- + +- Fixed a ``TypeError`` with ``MultiDictProxy`` and Python 3.8 -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1084 `__, `#1105 `__, `#1107 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of encoding hosts -- by `@bdraco `__. + + Previously, the library would unconditionally try to parse a host as an IP Address. The library now avoids trying to parse a host as an IP Address if the string is not in one of the formats described in ``3986#section-3.2.2``. + + *Related issues and pull requests on GitHub:* + `#1104 `__. + + +---- + + +1.9.10 +====== + +*(2024-09-04)* + + +Bug fixes +--------- + +- ``URL.join()()`` has been changed to match + ``3986`` and align with + ``/ operation()`` and ``URL.joinpath()()`` + when joining URLs with empty segments. + Previously ``urllib.parse.urljoin`` was used, + which has known issues with empty segments + (`python/cpython#84774 `_). + + Due to the semantics of ``URL.join()()``, joining an + URL with scheme requires making it relative, prefixing with ``./``. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/").join(URL("./https://github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + Empty segments are honored in the base as well as the joined part. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/https://").join(URL("github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + + -- by `@commonism `__ + + This change initially appeared in 1.9.5 but was reverted in 1.9.6 to resolve a problem with query string handling. + + *Related issues and pull requests on GitHub:* + `#1039 `__, `#1082 `__. + + +Features +-------- + +- Added ``~yarl.URL.absolute`` which is now preferred over ``URL.is_absolute()`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1100 `__. + + +---- + + +1.9.9 +===== + +*(2024-09-04)* + + +Bug fixes +--------- + +- Added missing type on ``~yarl.URL.port`` -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1097 `__. + + +---- + + +1.9.8 +===== + +*(2024-09-03)* + + +Features +-------- + +- Covered the ``~yarl.URL`` object with types -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1084 `__. + +- Cache parsing of IP Addresses when encoding hosts -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1086 `__. + + +Contributor-facing changes +-------------------------- + +- Covered the ``~yarl.URL`` object with types -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1084 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of handling ports -- by `@bdraco `__. + + *Related issues and pull requests on GitHub:* + `#1081 `__. + + +---- + + +1.9.7 +===== + +*(2024-09-01)* + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Removed support ``3986#section-3.2.3`` port normalization when the scheme is not one of ``http``, ``https``, ``wss``, or ``ws`` -- by `@bdraco `__. + + Support for port normalization was recently added in `#1033 `__ and contained code that would do blocking I/O if the scheme was not one of the four listed above. The code has been removed because this library is intended to be safe for usage with ``asyncio``. + + *Related issues and pull requests on GitHub:* + `#1076 `__. + + +Miscellaneous internal changes +------------------------------ + +- Improved performance of property caching -- by `@bdraco `__. + + The ``reify`` implementation from ``aiohttp`` was adapted to replace the internal ``cached_property`` implementation. + + *Related issues and pull requests on GitHub:* + `#1070 `__. + + +---- + + +1.9.6 +===== + +*(2024-08-30)* + + +Bug fixes +--------- + +- Reverted ``3986`` compatible ``URL.join()()`` honoring empty segments which was introduced in `#1039 `__. + + This change introduced a regression handling query string parameters with joined URLs. The change was reverted to maintain compatibility with the previous behavior. + + *Related issues and pull requests on GitHub:* + `#1067 `__. + + +---- + + +1.9.5 +===== + +*(2024-08-30)* + + +Bug fixes +--------- + +- Joining URLs with empty segments has been changed + to match ``3986``. + + Previously empty segments would be removed from path, + breaking use-cases such as + + .. code-block:: python + + URL("https://web.archive.org/web/") / "https://github.com/" + + Now ``/ operation()`` and ``URL.joinpath()()`` + keep empty segments, but do not introduce new empty segments. + e.g. + + .. code-block:: python + + URL("https://example.org/") / "" + + does not introduce an empty segment. + + -- by `@commonism `__ and `@youtux `__ + + *Related issues and pull requests on GitHub:* + `#1026 `__. + +- The default protocol ports of well-known URI schemes are now taken into account + during the normalization of the URL string representation in accordance with + ``3986#section-3.2.3``. + + Specified ports are removed from the ``str`` representation of a ``~yarl.URL`` + if the port matches the scheme's default port -- by `@commonism `__. + + *Related issues and pull requests on GitHub:* + `#1033 `__. + +- ``URL.join()()`` has been changed to match + ``3986`` and align with + ``/ operation()`` and ``URL.joinpath()()`` + when joining URLs with empty segments. + Previously ``urllib.parse.urljoin`` was used, + which has known issues with empty segments + (`python/cpython#84774 `_). + + Due to the semantics of ``URL.join()()``, joining an + URL with scheme requires making it relative, prefixing with ``./``. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/").join(URL("./https://github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + Empty segments are honored in the base as well as the joined part. + + .. code-block:: pycon + + >>> URL("https://web.archive.org/web/https://").join(URL("github.com/aio-libs/yarl")) + URL('https://web.archive.org/web/https://github.com/aio-libs/yarl') + + + + -- by `@commonism `__ + + *Related issues and pull requests on GitHub:* + `#1039 `__. + + +Removals and backward incompatible breaking changes +--------------------------------------------------- + +- Stopped decoding ``%2F`` (``/``) in ``URL.path``, as this could lead to code incorrectly treating it as a path separator + -- by `@Dreamsorcerer `__. + + *Related issues and pull requests on GitHub:* + `#1057 `__. + +- Dropped support for Python 3.7 -- by `@Dreamsorcerer `__. + + *Related issues and pull requests on GitHub:* + `#1016 `__. + + +Improved documentation +---------------------- + +- On the ``Contributing docs`` page, + a link to the ``Towncrier philosophy`` has been fixed. + + *Related issues and pull requests on GitHub:* + `#981 `__. + +- The pre-existing ``/ magic method()`` + has been documented in the API reference -- by `@commonism `__. + + *Related issues and pull requests on GitHub:* + `#1026 `__. + + +Packaging updates and notes for downstreams +------------------------------------------- + +- A flaw in the logic for copying the project directory into a + temporary folder that led to infinite recursion when ``TMPDIR`` + was set to a project subdirectory path. This was happening in Fedora + and its downstream due to the use of `pyproject-rpm-macros + `__. It was + only reproducible with ``pip wheel`` and was not affecting the + ``pyproject-build`` users. + + -- by `@hroncok `__ and `@webknjaz `__ + + *Related issues and pull requests on GitHub:* + `#992 `__, `#1014 `__. + +- Support Python 3.13 and publish non-free-threaded wheels + + *Related issues and pull requests on GitHub:* + `#1054 `__. + + +Contributor-facing changes +-------------------------- + +- The CI/CD setup has been updated to test ``arm64`` wheels + under macOS 14, except for Python 3.7 that is unsupported + in that environment -- by `@webknjaz `__. + + *Related issues and pull requests on GitHub:* + `#1015 `__. + +- Removed unused type ignores and casts -- by `@hauntsaninja `__. + + *Related issues and pull requests on GitHub:* + `#1031 `__. + + +Miscellaneous internal changes +------------------------------ + +- ``port``, ``scheme``, and ``raw_host`` are now ``cached_property`` -- by `@bdraco `__. + + ``aiohttp`` accesses these properties quite often, which cause ``urllib`` to build the ``_hostinfo`` property every time. ``port``, ``scheme``, and ``raw_host`` are now cached properties, which will improve performance. + + *Related issues and pull requests on GitHub:* + `#1044 `__, `#1058 `__. + + +---- + + +1.9.4 (2023-12-06) +================== + +Bug fixes +--------- + +- Started raising ``TypeError`` when a string value is passed into + ``yarl.URL.build()`` as the ``port`` argument -- by `@commonism `__. + + Previously the empty string as port would create malformed URLs when rendered as string representations. (`#883 `__) + + +Packaging updates and notes for downstreams +------------------------------------------- + +- The leading ``--`` has been dropped from the `PEP 517 `__ in-tree build + backend config setting names. ``--pure-python`` is now just ``pure-python`` + -- by `@webknjaz `__. + + The usage now looks as follows: + + .. code-block:: console + + $ python -m build \ + --config-setting=pure-python=true \ + --config-setting=with-cython-tracing=true + + (`#963 `__) + + +Contributor-facing changes +-------------------------- + +- A step-by-step ``Release Guide`` guide has + been added, describing how to release *yarl* -- by `@webknjaz `__. + + This is primarily targeting maintainers. (`#960 `__) +- Coverage collection has been implemented for the Cython modules + -- by `@webknjaz `__. + + It will also be reported to Codecov from any non-release CI jobs. + + To measure coverage in a development environment, *yarl* can be + installed in editable mode: + + .. code-block:: console + + $ python -Im pip install -e . + + Editable install produces C-files required for the Cython coverage + plugin to map the measurements back to the PYX-files. + + `#961 `__ + +- It is now possible to request line tracing in Cython builds using the + ``with-cython-tracing`` `PEP 517 `__ config setting + -- `@webknjaz `__. + + This can be used in CI and development environment to measure coverage + on Cython modules, but is not normally useful to the end-users or + downstream packagers. + + Here's a usage example: + + .. code-block:: console + + $ python -Im pip install . --config-settings=with-cython-tracing=true + + For editable installs, this setting is on by default. Otherwise, it's + off unless requested explicitly. + + The following produces C-files required for the Cython coverage + plugin to map the measurements back to the PYX-files: + + .. code-block:: console + + $ python -Im pip install -e . + + Alternatively, the ``YARL_CYTHON_TRACING=1`` environment variable + can be set to do the same as the `PEP 517 `__ config setting. + + `#962 `__ + + +1.9.3 (2023-11-20) +================== + +Bug fixes +--------- + +- Stopped dropping trailing slashes in ``yarl.URL.joinpath()`` -- by `@gmacon `__. (`#862 `__, `#866 `__) +- Started accepting string subclasses in ``yarl.URL.__truediv__()`` operations (``URL / segment``) -- by `@mjpieters `__. (`#871 `__, `#884 `__) +- Fixed the human representation of URLs with square brackets in usernames and passwords -- by `@mjpieters `__. (`#876 `__, `#882 `__) +- Updated type hints to include ``URL.missing_port()``, ``URL.__bytes__()`` + and the ``encoding`` argument to ``yarl.URL.joinpath()`` + -- by `@mjpieters `__. (`#891 `__) + + +Packaging updates and notes for downstreams +------------------------------------------- + +- Integrated Cython 3 to enable building *yarl* under Python 3.12 -- by `@mjpieters `__. (`#829 `__, `#881 `__) +- Declared modern ``setuptools.build_meta`` as the `PEP 517 `__ build + backend in ``pyproject.toml`` explicitly -- by `@webknjaz `__. (`#886 `__) +- Converted most of the packaging setup into a declarative ``setup.cfg`` + config -- by `@webknjaz `__. (`#890 `__) +- The packaging is replaced from an old-fashioned ``setup.py`` to an + in-tree `PEP 517 `__ build backend -- by `@webknjaz `__. + + Whenever the end-users or downstream packagers need to build ``yarl`` from + source (a Git checkout or an sdist), they may pass a ``config_settings`` + flag ``--pure-python``. If this flag is not set, a C-extension will be built + and included into the distribution. + + Here is how this can be done with ``pip``: + + .. code-block:: console + + $ python -m pip install . --config-settings=--pure-python=false + + This will also work with ``-e | --editable``. + + The same can be achieved via ``pypa/build``: + + .. code-block:: console + + $ python -m build --config-setting=--pure-python=false + + Adding ``-w | --wheel`` can force ``pypa/build`` produce a wheel from source + directly, as opposed to building an ``sdist`` and then building from it. (`#893 `__) + + .. attention:: + + v1.9.3 was the only version using the ``--pure-python`` setting name. + Later versions dropped the ``--`` prefix, making it just ``pure-python``. + +- Declared Python 3.12 supported officially in the distribution package metadata + -- by `@edgarrmondragon `__. (`#942 `__) + + +Contributor-facing changes +-------------------------- + +- A regression test for no-host URLs was added per `#821 `__ + and ``3986`` -- by `@kenballus `__. (`#821 `__, `#822 `__) +- Started testing *yarl* against Python 3.12 in CI -- by `@mjpieters `__. (`#881 `__) +- All Python 3.12 jobs are now marked as required to pass in CI + -- by `@edgarrmondragon `__. (`#942 `__) +- MyST is now integrated in Sphinx -- by `@webknjaz `__. + + This allows the contributors to author new documents in Markdown + when they have difficulties with going straight RST. (`#953 `__) + + +1.9.2 (2023-04-25) +================== + +Bugfixes +-------- + +- Fix regression with ``yarl.URL.__truediv__()`` and absolute URLs with empty paths causing the raw path to lack the leading ``/``. + (`#854 `_) + + +1.9.1 (2023-04-21) +================== + +Bugfixes +-------- + +- Marked tests that fail on older Python patch releases (< 3.7.10, < 3.8.8 and < 3.9.2) as expected to fail due to missing a security fix for CVE-2021-23336. (`#850 `_) + + +1.9.0 (2023-04-19) +================== + +This release was never published to PyPI, due to issues with the build process. + +Features +-------- + +- Added ``URL.joinpath(*elements)``, to create a new URL appending multiple path elements. (`#704 `_) +- Made ``URL.__truediv__()()`` return ``NotImplemented`` if called with an + unsupported type — by `@michaeljpeters `__. + (`#832 `_) + + +Bugfixes +-------- + +- Path normalization for absolute URLs no longer raises a ValueError exception + when ``..`` segments would otherwise go beyond the URL path root. + (`#536 `_) +- Fixed an issue with update_query() not getting rid of the query when argument is None. (`#792 `_) +- Added some input restrictions on with_port() function to prevent invalid boolean inputs or out of valid port inputs; handled incorrect 0 port representation. (`#793 `_) +- Made ``yarl.URL.build()`` raise a ``TypeError`` if the ``host`` argument is ``None`` — by `@paulpapacz `__. (`#808 `_) +- Fixed an issue with ``update_query()`` getting rid of the query when the argument + is empty but not ``None``. (`#845 `_) + + +Misc +---- + +- `#220 `_ + + +1.8.2 (2022-12-03) +================== + +This is the first release that started shipping wheels for Python 3.11. + + +1.8.1 (2022-08-01) +================== + +Misc +---- + +- `#694 `_, `#699 `_, `#700 `_, `#701 `_, `#702 `_, `#703 `_, `#739 `_ + + +1.8.0 (2022-08-01) +================== + +Features +-------- + +- Added ``URL.raw_suffix``, ``URL.suffix``, ``URL.raw_suffixes``, ``URL.suffixes``, ``URL.with_suffix``. (`#613 `_) + + +Improved Documentation +---------------------- + +- Fixed broken internal references to ``yarl.URL.human_repr()``. + (`#665 `_) +- Fixed broken external references to ``multidict:index`` docs. (`#665 `_) + + +Deprecations and Removals +------------------------- + +- Dropped Python 3.6 support. (`#672 `_) + + +Misc +---- + +- `#646 `_, `#699 `_, `#701 `_ + + +1.7.2 (2021-11-01) +================== + +Bugfixes +-------- + +- Changed call in ``with_port()`` to stop reencoding parts of the URL that were already encoded. (`#623 `_) + + +1.7.1 (2021-10-07) +================== + +Bugfixes +-------- + +- Fix 1.7.0 build error + +1.7.0 (2021-10-06) +================== + +Features +-------- + +- Add ``__bytes__()`` magic method so that ``bytes(url)`` will work and use optimal ASCII encoding. + (`#582 `_) +- Started shipping platform-specific arm64 wheels for Apple Silicon. (`#622 `_) +- Started shipping platform-specific wheels with the ``musl`` tag targeting typical Alpine Linux runtimes. (`#622 `_) +- Added support for Python 3.10. (`#622 `_) + + +1.6.3 (2020-11-14) +================== + +Bugfixes +-------- + +- No longer loose characters when decoding incorrect percent-sequences (like ``%e2%82%f8``). All non-decodable percent-sequences are now preserved. + `#517 `_ +- Provide x86 Windows wheels. + `#535 `_ + + +---- + + +1.6.2 (2020-10-12) +================== + + +Bugfixes +-------- + +- Provide generated ``.c`` files in TarBall distribution. + `#530 `_ + +1.6.1 (2020-10-12) +================== + +Features +-------- + +- Provide wheels for ``aarch64``, ``i686``, ``ppc64le``, ``s390x`` architectures on + Linux as well as ``x86_64``. + `#507 `_ +- Provide wheels for Python 3.9. + `#526 `_ + +Bugfixes +-------- + +- ``human_repr()`` now always produces valid representation equivalent to the original URL (if the original URL is valid). + `#511 `_ +- Fixed requoting a single percent followed by a percent-encoded character in the Cython implementation. + `#514 `_ +- Fix ValueError when decoding ``%`` which is not followed by two hexadecimal digits. + `#516 `_ +- Fix decoding ``%`` followed by a space and hexadecimal digit. + `#520 `_ +- Fix annotation of ``with_query()``/``update_query()`` methods for ``key=[val1, val2]`` case. + `#528 `_ + +Removal +------- + +- Drop Python 3.5 support; Python 3.6 is the minimal supported Python version. + + +---- + + +1.6.0 (2020-09-23) +================== + +Features +-------- + +- Allow for int and float subclasses in query, while still denying bool. + `#492 `_ + + +Bugfixes +-------- + +- Do not requote arguments in ``URL.build()``, ``with_xxx()`` and in ``/`` operator. + `#502 `_ +- Keep IPv6 brackets in ``origin()``. + `#504 `_ + + +---- + + +1.5.1 (2020-08-01) +================== + +Bugfixes +-------- + +- Fix including relocated internal ``yarl._quoting_c`` C-extension into published PyPI dists. + `#485 `_ + + +Misc +---- + +- `#484 `_ + + +---- + + +1.5.0 (2020-07-26) +================== + +Features +-------- + +- Convert host to lowercase on URL building. + `#386 `_ +- Allow using ``mod`` operator (``%``) for updating query string (an alias for ``update_query()`` method). + `#435 `_ +- Allow use of sequences such as ``list`` and ``tuple`` in the values + of a mapping such as ``dict`` to represent that a key has many values:: + + url = URL("http://example.com") + assert url.with_query({"a": [1, 2]}) == URL("http://example.com/?a=1&a=2") + + `#443 `_ +- Support ``URL.build()`` with scheme and path (creates a relative URL). + `#464 `_ +- Cache slow IDNA encode/decode calls. + `#476 `_ +- Add ``@final`` / ``Final`` type hints + `#477 `_ +- Support URL authority/raw_authority properties and authority argument of ``URL.build()`` method. + `#478 `_ +- Hide the library implementation details, make the exposed public list very clean. + `#483 `_ + + +Bugfixes +-------- + +- Fix tests with newer Python (3.7.6, 3.8.1 and 3.9.0+). + `#409 `_ +- Fix a bug where query component, passed in a form of mapping or sequence, is unquoted in unexpected way. + `#426 `_ +- Hide ``Query`` and ``QueryVariable`` type aliases in ``__init__.pyi``, now they are prefixed with underscore. + `#431 `_ +- Keep IPv6 brackets after updating port/user/password. + `#451 `_ + + +---- + + +1.4.2 (2019-12-05) +================== + +Features +-------- + +- Workaround for missing ``str.isascii()`` in Python 3.6 + `#389 `_ + + +---- + + +1.4.1 (2019-11-29) +================== + +* Fix regression, make the library work on Python 3.5 and 3.6 again. + +1.4.0 (2019-11-29) +================== + +* Distinguish an empty password in URL from a password not provided at all (#262) + +* Fixed annotations for optional parameters of ``URL.build`` (#309) + +* Use None as default value of ``user`` parameter of ``URL.build`` (#309) + +* Enforce building C Accelerated modules when installing from source tarball, use + ``YARL_NO_EXTENSIONS`` environment variable for falling back to (slower) Pure Python + implementation (#329) + +* Drop Python 3.5 support + +* Fix quoting of plus in path by pure python version (#339) + +* Don't create a new URL if fragment is unchanged (#292) + +* Included in error message the path that produces starting slash forbidden error (#376) + +* Skip slow IDNA encoding for ASCII-only strings (#387) + + +1.3.0 (2018-12-11) +================== + +* Fix annotations for ``query`` parameter (#207) + +* An incoming query sequence can have int variables (the same as for + Mapping type) (#208) + +* Add ``URL.explicit_port`` property (#218) + +* Give a friendlier error when port can't be converted to int (#168) + +* ``bool(URL())`` now returns ``False`` (#272) + +1.2.6 (2018-06-14) +================== + +* Drop Python 3.4 trove classifier (#205) + +1.2.5 (2018-05-23) +================== + +* Fix annotations for ``build`` (#199) + +1.2.4 (2018-05-08) +================== + +* Fix annotations for ``cached_property`` (#195) + +1.2.3 (2018-05-03) +================== + +* Accept ``str`` subclasses in ``URL`` constructor (#190) + +1.2.2 (2018-05-01) +================== + +* Fix build + +1.2.1 (2018-04-30) +================== + +* Pin minimal required Python to 3.5.3 (#189) + +1.2.0 (2018-04-30) +================== + +* Forbid inheritance, replace ``__init__`` with ``__new__`` (#171) + +* Support PEP-561 (provide type hinting marker) (#182) + +1.1.1 (2018-02-17) +================== + +* Fix performance regression: don't encode empty ``netloc`` (#170) + +1.1.0 (2018-01-21) +================== + +* Make pure Python quoter consistent with Cython version (#162) + +1.0.0 (2018-01-15) +================== + +* Use fast path if quoted string does not need requoting (#154) + +* Speed up quoting/unquoting by ``_Quoter`` and ``_Unquoter`` classes (#155) + +* Drop ``yarl.quote`` and ``yarl.unquote`` public functions (#155) + +* Add custom string writer, reuse static buffer if available (#157) + Code is 50-80 times faster than Pure Python version (was 4-5 times faster) + +* Don't recode IP zone (#144) + +* Support ``encoded=True`` in ``yarl.URL.build()`` (#158) + +* Fix updating query with multiple keys (#160) + +0.18.0 (2018-01-10) +=================== + +* Fallback to IDNA 2003 if domain name is not IDNA 2008 compatible (#152) + +0.17.0 (2017-12-30) +=================== + +* Use IDNA 2008 for domain name processing (#149) + +0.16.0 (2017-12-07) +=================== + +* Fix raising ``TypeError`` by ``url.query_string()`` after + ``url.with_query({})`` (empty mapping) (#141) + +0.15.0 (2017-11-23) +=================== + +* Add ``raw_path_qs`` attribute (#137) + +0.14.2 (2017-11-14) +=================== + +* Restore ``strict`` parameter as no-op in ``quote`` / ``unquote`` + +0.14.1 (2017-11-13) +=================== + +* Restore ``strict`` parameter as no-op for sake of compatibility with + aiohttp 2.2 + +0.14.0 (2017-11-11) +=================== + +* Drop strict mode (#123) + +* Fix ``"ValueError: Unallowed PCT %"`` when there's a ``"%"`` in the URL (#124) + +0.13.0 (2017-10-01) +=================== + +* Document ``encoded`` parameter (#102) + +* Support relative URLs like ``'?key=value'`` (#100) + +* Unsafe encoding for QS fixed. Encode ``;`` character in value parameter (#104) + +* Process passwords without user names (#95) + +0.12.0 (2017-06-26) +=================== + +* Properly support paths without leading slash in ``URL.with_path()`` (#90) + +* Enable type annotation checks + +0.11.0 (2017-06-26) +=================== + +* Normalize path (#86) + +* Clear query and fragment parts in ``.with_path()`` (#85) + +0.10.3 (2017-06-13) +=================== + +* Prevent double URL arguments unquoting (#83) + +0.10.2 (2017-05-05) +=================== + +* Unexpected hash behavior (#75) + + +0.10.1 (2017-05-03) +=================== + +* Unexpected compare behavior (#73) + +* Do not quote or unquote + if not a query string. (#74) + + +0.10.0 (2017-03-14) +=================== + +* Added ``URL.build`` class method (#58) + +* Added ``path_qs`` attribute (#42) + + +0.9.8 (2017-02-16) +================== + +* Do not quote ``:`` in path + + +0.9.7 (2017-02-16) +================== + +* Load from pickle without _cache (#56) + +* Percent-encoded pluses in path variables become spaces (#59) + + +0.9.6 (2017-02-15) +================== + +* Revert backward incompatible change (BaseURL) + + +0.9.5 (2017-02-14) +================== + +* Fix BaseURL rich comparison support + + +0.9.4 (2017-02-14) +================== + +* Use BaseURL + + +0.9.3 (2017-02-14) +================== + +* Added BaseURL + + +0.9.2 (2017-02-08) +================== + +* Remove debug print + + +0.9.1 (2017-02-07) +================== + +* Do not lose tail chars (#45) + + +0.9.0 (2017-02-07) +================== + +* Allow to quote ``%`` in non strict mode (#21) + +* Incorrect parsing of query parameters with %3B (;) inside (#34) + +* Fix core dumps (#41) + +* ``tmpbuf`` - compiling error (#43) + +* Added ``URL.update_path()`` method + +* Added ``URL.update_query()`` method (#47) + + +0.8.1 (2016-12-03) +================== + +* Fix broken aiohttp: revert back ``quote`` / ``unquote``. + + +0.8.0 (2016-12-03) +================== + +* Support more verbose error messages in ``.with_query()`` (#24) + +* Don't percent-encode ``@`` and ``:`` in path (#32) + +* Don't expose ``yarl.quote`` and ``yarl.unquote``, these functions are + part of private API + +0.7.1 (2016-11-18) +================== + +* Accept not only ``str`` but all classes inherited from ``str`` also (#25) + +0.7.0 (2016-11-07) +================== + +* Accept ``int`` as value for ``.with_query()`` + +0.6.0 (2016-11-07) +================== + +* Explicitly use UTF8 encoding in ``setup.py`` (#20) +* Properly unquote non-UTF8 strings (#19) + +0.5.3 (2016-11-02) +================== + +* Don't use ``typing.NamedTuple`` fields but indexes on URL construction + +0.5.2 (2016-11-02) +================== + +* Inline ``_encode`` class method + +0.5.1 (2016-11-02) +================== + +* Make URL construction faster by removing extra classmethod calls + +0.5.0 (2016-11-02) +================== + +* Add Cython optimization for quoting/unquoting +* Provide binary wheels + +0.4.3 (2016-09-29) +================== + +* Fix typing stubs + +0.4.2 (2016-09-29) +================== + +* Expose ``quote()`` and ``unquote()`` as public API + +0.4.1 (2016-09-28) +================== + +* Support empty values in query (``'/path?arg'``) + +0.4.0 (2016-09-27) +================== + +* Introduce ``relative()`` (#16) + +0.3.2 (2016-09-27) +================== + +* Typo fixes #15 + +0.3.1 (2016-09-26) +================== + +* Support sequence of pairs as ``with_query()`` parameter + +0.3.0 (2016-09-26) +================== + +* Introduce ``is_default_port()`` + +0.2.1 (2016-09-26) +================== + +* Raise ValueError for URLs like 'http://:8080/' + +0.2.0 (2016-09-18) +================== + +* Avoid doubling slashes when joining paths (#13) + +* Appending path starting from slash is forbidden (#12) + +0.1.4 (2016-09-09) +================== + +* Add ``kwargs`` support for ``with_query()`` (#10) + +0.1.3 (2016-09-07) +================== + +* Document ``with_query()``, ``with_fragment()`` and ``origin()`` + +* Allow ``None`` for ``with_query()`` and ``with_fragment()`` + +0.1.2 (2016-09-07) +================== + +* Fix links, tune docs theme. + +0.1.1 (2016-09-06) +================== + +* Update README, old version used obsolete API + +0.1.0 (2016-09-06) +================== + +* The library was deeply refactored, bytes are gone away but all + accepted strings are encoded if needed. + +0.0.1 (2016-08-30) +================== + +* The first release. diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/RECORD b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a37b4d9d6e179bd7c224e67cca29c5529a88197e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/RECORD @@ -0,0 +1,26 @@ +yarl-1.20.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +yarl-1.20.1.dist-info/METADATA,sha256=K0Ly6Viwwz6MHtOCAIKJqkwQuDjjt9IydAitWzRQYvU,73903 +yarl-1.20.1.dist-info/RECORD,, +yarl-1.20.1.dist-info/WHEEL,sha256=aSgG0F4rGPZtV0iTEIfy6dtHq6g67Lze3uLfk0vWn88,151 +yarl-1.20.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358 +yarl-1.20.1.dist-info/licenses/NOTICE,sha256=VtasbIEFwKUTBMIdsGDjYa-ajqCvmnXCOcKLXRNpODg,609 +yarl-1.20.1.dist-info/top_level.txt,sha256=vf3SJuQh-k7YtvsUrV_OPOrT9Kqn0COlk7IPYyhtGkQ,5 +yarl/__init__.py,sha256=FmDW8W3VgBfoaLs4K0k3YLdvtu6eTRG39PjdZ20COf0,281 +yarl/__pycache__/__init__.cpython-312.pyc,, +yarl/__pycache__/_parse.cpython-312.pyc,, +yarl/__pycache__/_path.cpython-312.pyc,, +yarl/__pycache__/_query.cpython-312.pyc,, +yarl/__pycache__/_quoters.cpython-312.pyc,, +yarl/__pycache__/_quoting.cpython-312.pyc,, +yarl/__pycache__/_quoting_py.cpython-312.pyc,, +yarl/__pycache__/_url.cpython-312.pyc,, +yarl/_parse.py,sha256=gNt8zxVFGr95ufUQpSMiiZ9vDrvg4zq6MEtT3f6_8J0,7185 +yarl/_path.py,sha256=A0FJUylZyzmlT0a3UDOBbK-EzZXCAYuQQBvG9eAC9hs,1291 +yarl/_query.py,sha256=2l76j4_2qQ6vnwKRyGwhI5AXUpdlKGmmC4yp3ZjjevI,3883 +yarl/_quoters.py,sha256=z-BzsXfLnJK-bd-HrGaoKGri9L3GpDv6vxFEtmu-uCM,1154 +yarl/_quoting.py,sha256=yKIqFTzFzWLVb08xy1DSxKNjFwo4f-oLlzxTuKwC57M,506 +yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so,sha256=kjAmisZBizo1YmiHrC6oO9iJKqBTkoYg56EztVsUmRU,1092184 +yarl/_quoting_c.pyx,sha256=Rk-98-kf1OwXTeU50UV8QjYks0wAQHpyPZk6McruIqk,14356 +yarl/_quoting_py.py,sha256=oVxVuDWMCjuvTViBiDzhYBFMI-YfDCNGGUbfnQpkOgQ,6830 +yarl/_url.py,sha256=7_9EhA9LbXjmK3zsAS4-WuMZgle7RovVK1pQGYVCL8k,55323 +yarl/py.typed,sha256=ay5OMO475PlcZ_Fbun9maHW7Y6MBTk0UXL4ztHx3Iug,14 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/WHEEL b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..e21e9f2f89caabbb0f5e84c1775fbe781dd45a63 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/WHEEL @@ -0,0 +1,6 @@ +Wheel-Version: 1.0 +Generator: setuptools (80.9.0) +Root-Is-Purelib: false +Tag: cp312-cp312-manylinux_2_17_x86_64 +Tag: cp312-cp312-manylinux2014_x86_64 + diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/top_level.txt b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..e93e8bddefb14a8a753f7ecab6b934fd899cd9e5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl-1.20.1.dist-info/top_level.txt @@ -0,0 +1 @@ +yarl diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8579787df900c6ebfb09bc0d7e891387f30b8763 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/__init__.py @@ -0,0 +1,14 @@ +from ._query import Query, QueryVariable, SimpleQuery +from ._url import URL, cache_clear, cache_configure, cache_info + +__version__ = "1.20.1" + +__all__ = ( + "URL", + "SimpleQuery", + "QueryVariable", + "Query", + "cache_clear", + "cache_configure", + "cache_info", +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_parse.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_parse.py new file mode 100644 index 0000000000000000000000000000000000000000..115d772360e61f4322eb72ced557d42a30930518 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_parse.py @@ -0,0 +1,203 @@ +"""URL parsing utilities.""" + +import re +import unicodedata +from functools import lru_cache +from typing import Union +from urllib.parse import scheme_chars, uses_netloc + +from ._quoters import QUOTER, UNQUOTER_PLUS + +# Leading and trailing C0 control and space to be stripped per WHATWG spec. +# == "".join([chr(i) for i in range(0, 0x20 + 1)]) +WHATWG_C0_CONTROL_OR_SPACE = ( + "\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10" + "\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f " +) + +# Unsafe bytes to be removed per WHATWG spec +UNSAFE_URL_BYTES_TO_REMOVE = ["\t", "\r", "\n"] +USES_AUTHORITY = frozenset(uses_netloc) + +SplitURLType = tuple[str, str, str, str, str] + + +def split_url(url: str) -> SplitURLType: + """Split URL into parts.""" + # Adapted from urllib.parse.urlsplit + # Only lstrip url as some applications rely on preserving trailing space. + # (https://url.spec.whatwg.org/#concept-basic-url-parser would strip both) + url = url.lstrip(WHATWG_C0_CONTROL_OR_SPACE) + for b in UNSAFE_URL_BYTES_TO_REMOVE: + if b in url: + url = url.replace(b, "") + + scheme = netloc = query = fragment = "" + i = url.find(":") + if i > 0 and url[0] in scheme_chars: + for c in url[1:i]: + if c not in scheme_chars: + break + else: + scheme, url = url[:i].lower(), url[i + 1 :] + has_hash = "#" in url + has_question_mark = "?" in url + if url[:2] == "//": + delim = len(url) # position of end of domain part of url, default is end + if has_hash and has_question_mark: + delim_chars = "/?#" + elif has_question_mark: + delim_chars = "/?" + elif has_hash: + delim_chars = "/#" + else: + delim_chars = "/" + for c in delim_chars: # look for delimiters; the order is NOT important + wdelim = url.find(c, 2) # find first of this delim + if wdelim >= 0 and wdelim < delim: # if found + delim = wdelim # use earliest delim position + netloc = url[2:delim] + url = url[delim:] + has_left_bracket = "[" in netloc + has_right_bracket = "]" in netloc + if (has_left_bracket and not has_right_bracket) or ( + has_right_bracket and not has_left_bracket + ): + raise ValueError("Invalid IPv6 URL") + if has_left_bracket: + bracketed_host = netloc.partition("[")[2].partition("]")[0] + # Valid bracketed hosts are defined in + # https://www.rfc-editor.org/rfc/rfc3986#page-49 + # https://url.spec.whatwg.org/ + if bracketed_host and bracketed_host[0] == "v": + if not re.match(r"\Av[a-fA-F0-9]+\..+\Z", bracketed_host): + raise ValueError("IPvFuture address is invalid") + elif ":" not in bracketed_host: + raise ValueError("The IPv6 content between brackets is not valid") + if has_hash: + url, _, fragment = url.partition("#") + if has_question_mark: + url, _, query = url.partition("?") + if netloc and not netloc.isascii(): + _check_netloc(netloc) + return scheme, netloc, url, query, fragment + + +def _check_netloc(netloc: str) -> None: + # Adapted from urllib.parse._checknetloc + # looking for characters like \u2100 that expand to 'a/c' + # IDNA uses NFKC equivalence, so normalize for this check + + # ignore characters already included + # but not the surrounding text + n = netloc.replace("@", "").replace(":", "").replace("#", "").replace("?", "") + normalized_netloc = unicodedata.normalize("NFKC", n) + if n == normalized_netloc: + return + # Note that there are no unicode decompositions for the character '@' so + # its currently impossible to have test coverage for this branch, however if the + # one should be added in the future we want to make sure its still checked. + for c in "/?#@:": # pragma: no branch + if c in normalized_netloc: + raise ValueError( + f"netloc '{netloc}' contains invalid " + "characters under NFKC normalization" + ) + + +@lru_cache # match the same size as urlsplit +def split_netloc( + netloc: str, +) -> tuple[Union[str, None], Union[str, None], Union[str, None], Union[int, None]]: + """Split netloc into username, password, host and port.""" + if "@" not in netloc: + username: Union[str, None] = None + password: Union[str, None] = None + hostinfo = netloc + else: + userinfo, _, hostinfo = netloc.rpartition("@") + username, have_password, password = userinfo.partition(":") + if not have_password: + password = None + + if "[" in hostinfo: + _, _, bracketed = hostinfo.partition("[") + hostname, _, port_str = bracketed.partition("]") + _, _, port_str = port_str.partition(":") + else: + hostname, _, port_str = hostinfo.partition(":") + + if not port_str: + return username or None, password, hostname or None, None + + try: + port = int(port_str) + except ValueError: + raise ValueError("Invalid URL: port can't be converted to integer") + if not (0 <= port <= 65535): + raise ValueError("Port out of range 0-65535") + return username or None, password, hostname or None, port + + +def unsplit_result( + scheme: str, netloc: str, url: str, query: str, fragment: str +) -> str: + """Unsplit a URL without any normalization.""" + if netloc or (scheme and scheme in USES_AUTHORITY) or url[:2] == "//": + if url and url[:1] != "/": + url = f"{scheme}://{netloc}/{url}" if scheme else f"{scheme}:{url}" + else: + url = f"{scheme}://{netloc}{url}" if scheme else f"//{netloc}{url}" + elif scheme: + url = f"{scheme}:{url}" + if query: + url = f"{url}?{query}" + return f"{url}#{fragment}" if fragment else url + + +@lru_cache # match the same size as urlsplit +def make_netloc( + user: Union[str, None], + password: Union[str, None], + host: Union[str, None], + port: Union[int, None], + encode: bool = False, +) -> str: + """Make netloc from parts. + + The user and password are encoded if encode is True. + + The host must already be encoded with _encode_host. + """ + if host is None: + return "" + ret = host + if port is not None: + ret = f"{ret}:{port}" + if user is None and password is None: + return ret + if password is not None: + if not user: + user = "" + elif encode: + user = QUOTER(user) + if encode: + password = QUOTER(password) + user = f"{user}:{password}" + elif user and encode: + user = QUOTER(user) + return f"{user}@{ret}" if user else ret + + +def query_to_pairs(query_string: str) -> list[tuple[str, str]]: + """Parse a query given as a string argument. + + Works like urllib.parse.parse_qsl with keep empty values. + """ + pairs: list[tuple[str, str]] = [] + if not query_string: + return pairs + for k_v in query_string.split("&"): + k, _, v = k_v.partition("=") + pairs.append((UNQUOTER_PLUS(k), UNQUOTER_PLUS(v))) + return pairs diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_path.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_path.py new file mode 100644 index 0000000000000000000000000000000000000000..c22f0b4b8cdd9280fd36789e2bc052b1c4938167 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_path.py @@ -0,0 +1,41 @@ +"""Utilities for working with paths.""" + +from collections.abc import Sequence +from contextlib import suppress + + +def normalize_path_segments(segments: Sequence[str]) -> list[str]: + """Drop '.' and '..' from a sequence of str segments""" + + resolved_path: list[str] = [] + + for seg in segments: + if seg == "..": + # ignore any .. segments that would otherwise cause an + # IndexError when popped from resolved_path if + # resolving for rfc3986 + with suppress(IndexError): + resolved_path.pop() + elif seg != ".": + resolved_path.append(seg) + + if segments and segments[-1] in (".", ".."): + # do some post-processing here. + # if the last segment was a relative dir, + # then we need to append the trailing '/' + resolved_path.append("") + + return resolved_path + + +def normalize_path(path: str) -> str: + # Drop '.' and '..' from str path + prefix = "" + if path and path[0] == "/": + # preserve the "/" root element of absolute paths, copying it to the + # normalised output as per sections 5.2.4 and 6.2.2.3 of rfc3986. + prefix = "/" + path = path[1:] + + segments = path.split("/") + return prefix + "/".join(normalize_path_segments(segments)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_query.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_query.py new file mode 100644 index 0000000000000000000000000000000000000000..910bc877c63254f56fe84cd0f8c7374a37511377 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_query.py @@ -0,0 +1,114 @@ +"""Query string handling.""" + +import math +from collections.abc import Iterable, Mapping, Sequence +from typing import Any, SupportsInt, Union + +from multidict import istr + +from ._quoters import QUERY_PART_QUOTER, QUERY_QUOTER + +SimpleQuery = Union[str, SupportsInt, float] +QueryVariable = Union[SimpleQuery, Sequence[SimpleQuery]] +Query = Union[ + None, str, Mapping[str, QueryVariable], Sequence[tuple[str, QueryVariable]] +] + + +def query_var(v: SimpleQuery) -> str: + """Convert a query variable to a string.""" + cls = type(v) + if cls is int: # Fast path for non-subclassed int + return str(v) + if isinstance(v, str): + return v + if isinstance(v, float): + if math.isinf(v): + raise ValueError("float('inf') is not supported") + if math.isnan(v): + raise ValueError("float('nan') is not supported") + return str(float(v)) + if cls is not bool and isinstance(v, SupportsInt): + return str(int(v)) + raise TypeError( + "Invalid variable type: value " + "should be str, int or float, got {!r} " + "of type {}".format(v, cls) + ) + + +def get_str_query_from_sequence_iterable( + items: Iterable[tuple[Union[str, istr], QueryVariable]], +) -> str: + """Return a query string from a sequence of (key, value) pairs. + + value is a single value or a sequence of values for the key + + The sequence of values must be a list or tuple. + """ + quoter = QUERY_PART_QUOTER + pairs = [ + f"{quoter(k)}={quoter(v if type(v) is str else query_var(v))}" + for k, val in items + for v in ( + val if type(val) is not str and isinstance(val, (list, tuple)) else (val,) + ) + ] + return "&".join(pairs) + + +def get_str_query_from_iterable( + items: Iterable[tuple[Union[str, istr], SimpleQuery]], +) -> str: + """Return a query string from an iterable. + + The iterable must contain (key, value) pairs. + + The values are not allowed to be sequences, only single values are + allowed. For sequences, use `_get_str_query_from_sequence_iterable`. + """ + quoter = QUERY_PART_QUOTER + # A listcomp is used since listcomps are inlined on CPython 3.12+ and + # they are a bit faster than a generator expression. + pairs = [ + f"{quoter(k)}={quoter(v if type(v) is str else query_var(v))}" for k, v in items + ] + return "&".join(pairs) + + +def get_str_query(*args: Any, **kwargs: Any) -> Union[str, None]: + """Return a query string from supported args.""" + query: Union[str, Mapping[str, QueryVariable], None] + if kwargs: + if args: + msg = "Either kwargs or single query parameter must be present" + raise ValueError(msg) + query = kwargs + elif len(args) == 1: + query = args[0] + else: + raise ValueError("Either kwargs or single query parameter must be present") + + if query is None: + return None + if not query: + return "" + if type(query) is dict: + return get_str_query_from_sequence_iterable(query.items()) + if type(query) is str or isinstance(query, str): + return QUERY_QUOTER(query) + if isinstance(query, Mapping): + return get_str_query_from_sequence_iterable(query.items()) + if isinstance(query, (bytes, bytearray, memoryview)): # type: ignore[unreachable] + msg = "Invalid query type: bytes, bytearray and memoryview are forbidden" + raise TypeError(msg) + if isinstance(query, Sequence): + # We don't expect sequence values if we're given a list of pairs + # already; only mappings like builtin `dict` which can't have the + # same key pointing to multiple values are allowed to use + # `_query_seq_pairs`. + return get_str_query_from_iterable(query) + raise TypeError( + "Invalid query type: only str, mapping or " + "sequence of (key, value) pairs is allowed" + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoters.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoters.py new file mode 100644 index 0000000000000000000000000000000000000000..0feb5b141131697a6dc87df19941ffe6714b20ff --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoters.py @@ -0,0 +1,33 @@ +"""Quoting and unquoting utilities for URL parts.""" + +from typing import Union +from urllib.parse import quote + +from ._quoting import _Quoter, _Unquoter + +QUOTER = _Quoter(requote=False) +REQUOTER = _Quoter() +PATH_QUOTER = _Quoter(safe="@:", protected="/+", requote=False) +PATH_REQUOTER = _Quoter(safe="@:", protected="/+") +QUERY_QUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True, requote=False) +QUERY_REQUOTER = _Quoter(safe="?/:@", protected="=+&;", qs=True) +QUERY_PART_QUOTER = _Quoter(safe="?/:@", qs=True, requote=False) +FRAGMENT_QUOTER = _Quoter(safe="?/:@", requote=False) +FRAGMENT_REQUOTER = _Quoter(safe="?/:@") + +UNQUOTER = _Unquoter() +PATH_UNQUOTER = _Unquoter(unsafe="+") +PATH_SAFE_UNQUOTER = _Unquoter(ignore="/%", unsafe="+") +QS_UNQUOTER = _Unquoter(qs=True) +UNQUOTER_PLUS = _Unquoter(plus=True) # to match urllib.parse.unquote_plus + + +def human_quote(s: Union[str, None], unsafe: str) -> Union[str, None]: + if not s: + return s + for c in "%" + unsafe: + if c in s: + s = s.replace(c, f"%{ord(c):02X}") + if s.isprintable(): + return s + return "".join(c if c.isprintable() else quote(c) for c in s) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting.py new file mode 100644 index 0000000000000000000000000000000000000000..25d76c885cacaa815bb7e0149aedbe76c20f2228 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting.py @@ -0,0 +1,19 @@ +import os +import sys +from typing import TYPE_CHECKING + +__all__ = ("_Quoter", "_Unquoter") + + +NO_EXTENSIONS = bool(os.environ.get("YARL_NO_EXTENSIONS")) # type: bool +if sys.implementation.name != "cpython": + NO_EXTENSIONS = True + + +if TYPE_CHECKING or NO_EXTENSIONS: + from ._quoting_py import _Quoter, _Unquoter +else: + try: + from ._quoting_c import _Quoter, _Unquoter + except ImportError: # pragma: no cover + from ._quoting_py import _Quoter, _Unquoter # type: ignore[assignment] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..29125cf735df1ef07703be27b6c27586eca4f35f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_c.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9230268ac6418b3a35626887ac2ea83bd8892aa053928620e7a133b55b149915 +size 1092184 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_c.pyx b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_c.pyx new file mode 100644 index 0000000000000000000000000000000000000000..91b0644f7fafb39eeaa79efa21635ffdcea12619 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_c.pyx @@ -0,0 +1,453 @@ +# cython: language_level=3, freethreading_compatible=True + +from cpython.exc cimport PyErr_NoMemory +from cpython.mem cimport PyMem_Free, PyMem_Malloc, PyMem_Realloc +from cpython.unicode cimport ( + PyUnicode_DATA, + PyUnicode_DecodeASCII, + PyUnicode_DecodeUTF8Stateful, + PyUnicode_GET_LENGTH, + PyUnicode_KIND, + PyUnicode_READ, +) +from libc.stdint cimport uint8_t, uint64_t +from libc.string cimport memcpy, memset + +from string import ascii_letters, digits + + +cdef str GEN_DELIMS = ":/?#[]@" +cdef str SUB_DELIMS_WITHOUT_QS = "!$'()*," +cdef str SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + '+?=;' +cdef str RESERVED = GEN_DELIMS + SUB_DELIMS +cdef str UNRESERVED = ascii_letters + digits + '-._~' +cdef str ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS +cdef str QS = '+&=;' + +DEF BUF_SIZE = 8 * 1024 # 8KiB + +cdef inline Py_UCS4 _to_hex(uint8_t v) noexcept: + if v < 10: + return (v+0x30) # ord('0') == 0x30 + else: + return (v+0x41-10) # ord('A') == 0x41 + + +cdef inline int _from_hex(Py_UCS4 v) noexcept: + if '0' <= v <= '9': + return (v) - 0x30 # ord('0') == 0x30 + elif 'A' <= v <= 'F': + return (v) - 0x41 + 10 # ord('A') == 0x41 + elif 'a' <= v <= 'f': + return (v) - 0x61 + 10 # ord('a') == 0x61 + else: + return -1 + + +cdef inline int _is_lower_hex(Py_UCS4 v) noexcept: + return 'a' <= v <= 'f' + + +cdef inline long _restore_ch(Py_UCS4 d1, Py_UCS4 d2): + cdef int digit1 = _from_hex(d1) + if digit1 < 0: + return -1 + cdef int digit2 = _from_hex(d2) + if digit2 < 0: + return -1 + return digit1 << 4 | digit2 + + +cdef uint8_t ALLOWED_TABLE[16] +cdef uint8_t ALLOWED_NOTQS_TABLE[16] + + +cdef inline bint bit_at(uint8_t array[], uint64_t ch) noexcept: + return array[ch >> 3] & (1 << (ch & 7)) + + +cdef inline void set_bit(uint8_t array[], uint64_t ch) noexcept: + array[ch >> 3] |= (1 << (ch & 7)) + + +memset(ALLOWED_TABLE, 0, sizeof(ALLOWED_TABLE)) +memset(ALLOWED_NOTQS_TABLE, 0, sizeof(ALLOWED_NOTQS_TABLE)) + +for i in range(128): + if chr(i) in ALLOWED: + set_bit(ALLOWED_TABLE, i) + set_bit(ALLOWED_NOTQS_TABLE, i) + if chr(i) in QS: + set_bit(ALLOWED_NOTQS_TABLE, i) + +# ----------------- writer --------------------------- + +cdef struct Writer: + char *buf + bint heap_allocated_buf + Py_ssize_t size + Py_ssize_t pos + bint changed + + +cdef inline void _init_writer(Writer* writer, char* buf): + writer.buf = buf + writer.heap_allocated_buf = False + writer.size = BUF_SIZE + writer.pos = 0 + writer.changed = 0 + + +cdef inline void _release_writer(Writer* writer): + if writer.heap_allocated_buf: + PyMem_Free(writer.buf) + + +cdef inline int _write_char(Writer* writer, Py_UCS4 ch, bint changed): + cdef char * buf + cdef Py_ssize_t size + + if writer.pos == writer.size: + # reallocate + size = writer.size + BUF_SIZE + if not writer.heap_allocated_buf: + buf = PyMem_Malloc(size) + if buf == NULL: + PyErr_NoMemory() + return -1 + memcpy(buf, writer.buf, writer.size) + writer.heap_allocated_buf = True + else: + buf = PyMem_Realloc(writer.buf, size) + if buf == NULL: + PyErr_NoMemory() + return -1 + writer.buf = buf + writer.size = size + writer.buf[writer.pos] = ch + writer.pos += 1 + writer.changed |= changed + return 0 + + +cdef inline int _write_pct(Writer* writer, uint8_t ch, bint changed): + if _write_char(writer, '%', changed) < 0: + return -1 + if _write_char(writer, _to_hex(ch >> 4), changed) < 0: + return -1 + return _write_char(writer, _to_hex(ch & 0x0f), changed) + + +cdef inline int _write_utf8(Writer* writer, Py_UCS4 symbol): + cdef uint64_t utf = symbol + + if utf < 0x80: + return _write_pct(writer, utf, True) + elif utf < 0x800: + if _write_pct(writer, (0xc0 | (utf >> 6)), True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif 0xD800 <= utf <= 0xDFFF: + # surogate pair, ignored + return 0 + elif utf < 0x10000: + if _write_pct(writer, (0xe0 | (utf >> 12)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + elif utf > 0x10FFFF: + # symbol is too large + return 0 + else: + if _write_pct(writer, (0xf0 | (utf >> 18)), True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 12) & 0x3f)), + True) < 0: + return -1 + if _write_pct(writer, (0x80 | ((utf >> 6) & 0x3f)), + True) < 0: + return -1 + return _write_pct(writer, (0x80 | (utf & 0x3f)), True) + + +# --------------------- end writer -------------------------- + + +cdef class _Quoter: + cdef bint _qs + cdef bint _requote + + cdef uint8_t _safe_table[16] + cdef uint8_t _protected_table[16] + + def __init__( + self, *, str safe='', str protected='', bint qs=False, bint requote=True, + ): + cdef Py_UCS4 ch + + self._qs = qs + self._requote = requote + + if not self._qs: + memcpy(self._safe_table, + ALLOWED_NOTQS_TABLE, + sizeof(self._safe_table)) + else: + memcpy(self._safe_table, + ALLOWED_TABLE, + sizeof(self._safe_table)) + for ch in safe: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + + memset(self._protected_table, 0, sizeof(self._protected_table)) + for ch in protected: + if ord(ch) > 127: + raise ValueError("Only safe symbols with ORD < 128 are allowed") + set_bit(self._safe_table, ch) + set_bit(self._protected_table, ch) + + def __call__(self, val): + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + return self._do_quote_or_skip(val) + + cdef str _do_quote_or_skip(self, str val): + cdef char[BUF_SIZE] buffer + cdef Py_UCS4 ch + cdef Py_ssize_t length = PyUnicode_GET_LENGTH(val) + cdef Py_ssize_t idx = length + cdef bint must_quote = 0 + cdef Writer writer + cdef int kind = PyUnicode_KIND(val) + cdef const void *data = PyUnicode_DATA(val) + + # If everything in the string is in the safe + # table and all ASCII, we can skip quoting + while idx: + idx -= 1 + ch = PyUnicode_READ(kind, data, idx) + if ch >= 128 or not bit_at(self._safe_table, ch): + must_quote = 1 + break + + if not must_quote: + return val + + _init_writer(&writer, &buffer[0]) + try: + return self._do_quote(val, length, kind, data, &writer) + finally: + _release_writer(&writer) + + cdef str _do_quote( + self, + str val, + Py_ssize_t length, + int kind, + const void *data, + Writer *writer + ): + cdef Py_UCS4 ch + cdef long chl + cdef int changed + cdef Py_ssize_t idx = 0 + + while idx < length: + ch = PyUnicode_READ(kind, data, idx) + idx += 1 + if ch == '%' and self._requote and idx <= length - 2: + chl = _restore_ch( + PyUnicode_READ(kind, data, idx), + PyUnicode_READ(kind, data, idx + 1) + ) + if chl != -1: + ch = chl + idx += 2 + if ch < 128: + if bit_at(self._protected_table, ch): + if _write_pct(writer, ch, True) < 0: + raise + continue + + if bit_at(self._safe_table, ch): + if _write_char(writer, ch, True) < 0: + raise + continue + + changed = (_is_lower_hex(PyUnicode_READ(kind, data, idx - 2)) or + _is_lower_hex(PyUnicode_READ(kind, data, idx - 1))) + if _write_pct(writer, ch, changed) < 0: + raise + continue + else: + ch = '%' + + if self._write(writer, ch) < 0: + raise + + if not writer.changed: + return val + else: + return PyUnicode_DecodeASCII(writer.buf, writer.pos, "strict") + + cdef inline int _write(self, Writer *writer, Py_UCS4 ch): + if self._qs: + if ch == ' ': + return _write_char(writer, '+', True) + + if ch < 128 and bit_at(self._safe_table, ch): + return _write_char(writer, ch, False) + + return _write_utf8(writer, ch) + + +cdef class _Unquoter: + cdef str _ignore + cdef bint _has_ignore + cdef str _unsafe + cdef bytes _unsafe_bytes + cdef Py_ssize_t _unsafe_bytes_len + cdef const unsigned char * _unsafe_bytes_char + cdef bint _qs + cdef bint _plus # to match urllib.parse.unquote_plus + cdef _Quoter _quoter + cdef _Quoter _qs_quoter + + def __init__(self, *, ignore="", unsafe="", qs=False, plus=False): + self._ignore = ignore + self._has_ignore = bool(self._ignore) + self._unsafe = unsafe + # unsafe may only be extended ascii characters (0-255) + self._unsafe_bytes = self._unsafe.encode('ascii') + self._unsafe_bytes_len = len(self._unsafe_bytes) + self._unsafe_bytes_char = self._unsafe_bytes + self._qs = qs + self._plus = plus + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + def __call__(self, val): + if val is None: + return None + if type(val) is not str: + if isinstance(val, str): + # derived from str + val = str(val) + else: + raise TypeError("Argument should be str") + return self._do_unquote(val) + + cdef str _do_unquote(self, str val): + cdef Py_ssize_t length = PyUnicode_GET_LENGTH(val) + if length == 0: + return val + + cdef list ret = [] + cdef char buffer[4] + cdef Py_ssize_t buflen = 0 + cdef Py_ssize_t consumed + cdef str unquoted + cdef Py_UCS4 ch = 0 + cdef long chl = 0 + cdef Py_ssize_t idx = 0 + cdef Py_ssize_t start_pct + cdef int kind = PyUnicode_KIND(val) + cdef const void *data = PyUnicode_DATA(val) + cdef bint changed = 0 + while idx < length: + ch = PyUnicode_READ(kind, data, idx) + idx += 1 + if ch == '%' and idx <= length - 2: + changed = 1 + chl = _restore_ch( + PyUnicode_READ(kind, data, idx), + PyUnicode_READ(kind, data, idx + 1) + ) + if chl != -1: + ch = chl + idx += 2 + assert buflen < 4 + buffer[buflen] = ch + buflen += 1 + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + start_pct = idx - buflen * 3 + buffer[0] = ch + buflen = 1 + ret.append(val[start_pct : idx - 3]) + try: + unquoted = PyUnicode_DecodeUTF8Stateful(buffer, buflen, + NULL, &consumed) + except UnicodeDecodeError: + buflen = 0 + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + assert consumed == 0 + continue + assert consumed == buflen + buflen = 0 + if self._qs and unquoted in '+=&;': + ret.append(self._qs_quoter(unquoted)) + elif ( + (self._unsafe_bytes_len and unquoted in self._unsafe) or + (self._has_ignore and unquoted in self._ignore) + ): + ret.append(self._quoter(unquoted)) + else: + ret.append(unquoted) + continue + else: + ch = '%' + + if buflen: + start_pct = idx - 1 - buflen * 3 + ret.append(val[start_pct : idx - 1]) + buflen = 0 + + if ch == '+': + if ( + (not self._qs and not self._plus) or + (self._unsafe_bytes_len and self._is_char_unsafe(ch)) + ): + ret.append('+') + else: + changed = 1 + ret.append(' ') + continue + + if self._unsafe_bytes_len and self._is_char_unsafe(ch): + changed = 1 + ret.append('%') + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if not changed: + return val + + if buflen: + ret.append(val[length - buflen * 3 : length]) + + return ''.join(ret) + + cdef inline bint _is_char_unsafe(self, Py_UCS4 ch): + for i in range(self._unsafe_bytes_len): + if ch == self._unsafe_bytes_char[i]: + return True + return False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_py.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_py.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc47bc675b0b34a2a11306d0bfc1cba1a04c8a8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_quoting_py.py @@ -0,0 +1,213 @@ +import codecs +import re +from string import ascii_letters, ascii_lowercase, digits +from typing import Union, cast, overload + +BASCII_LOWERCASE = ascii_lowercase.encode("ascii") +BPCT_ALLOWED = {f"%{i:02X}".encode("ascii") for i in range(256)} +GEN_DELIMS = ":/?#[]@" +SUB_DELIMS_WITHOUT_QS = "!$'()*," +SUB_DELIMS = SUB_DELIMS_WITHOUT_QS + "+&=;" +RESERVED = GEN_DELIMS + SUB_DELIMS +UNRESERVED = ascii_letters + digits + "-._~" +ALLOWED = UNRESERVED + SUB_DELIMS_WITHOUT_QS + + +_IS_HEX = re.compile(b"[A-Z0-9][A-Z0-9]") +_IS_HEX_STR = re.compile("[A-Fa-f0-9][A-Fa-f0-9]") + +utf8_decoder = codecs.getincrementaldecoder("utf-8") + + +class _Quoter: + def __init__( + self, + *, + safe: str = "", + protected: str = "", + qs: bool = False, + requote: bool = True, + ) -> None: + self._safe = safe + self._protected = protected + self._qs = qs + self._requote = requote + + @overload + def __call__(self, val: str) -> str: ... + @overload + def __call__(self, val: None) -> None: ... + def __call__(self, val: Union[str, None]) -> Union[str, None]: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + bval = val.encode("utf8", errors="ignore") + ret = bytearray() + pct = bytearray() + safe = self._safe + safe += ALLOWED + if not self._qs: + safe += "+&=;" + safe += self._protected + bsafe = safe.encode("ascii") + idx = 0 + while idx < len(bval): + ch = bval[idx] + idx += 1 + + if pct: + if ch in BASCII_LOWERCASE: + ch = ch - 32 # convert to uppercase + pct.append(ch) + if len(pct) == 3: # pragma: no branch # peephole optimizer + buf = pct[1:] + if not _IS_HEX.match(buf): + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + try: + unquoted = chr(int(pct[1:].decode("ascii"), base=16)) + except ValueError: + ret.extend(b"%25") + pct.clear() + idx -= 2 + continue + + if unquoted in self._protected: + ret.extend(pct) + elif unquoted in safe: + ret.append(ord(unquoted)) + else: + ret.extend(pct) + pct.clear() + + # special case, if we have only one char after "%" + elif len(pct) == 2 and idx == len(bval): + ret.extend(b"%25") + pct.clear() + idx -= 1 + + continue + + elif ch == ord("%") and self._requote: + pct.clear() + pct.append(ch) + + # special case if "%" is last char + if idx == len(bval): + ret.extend(b"%25") + + continue + + if self._qs and ch == ord(" "): + ret.append(ord("+")) + continue + if ch in bsafe: + ret.append(ch) + continue + + ret.extend((f"%{ch:02X}").encode("ascii")) + + ret2 = ret.decode("ascii") + if ret2 == val: + return val + return ret2 + + +class _Unquoter: + def __init__( + self, + *, + ignore: str = "", + unsafe: str = "", + qs: bool = False, + plus: bool = False, + ) -> None: + self._ignore = ignore + self._unsafe = unsafe + self._qs = qs + self._plus = plus # to match urllib.parse.unquote_plus + self._quoter = _Quoter() + self._qs_quoter = _Quoter(qs=True) + + @overload + def __call__(self, val: str) -> str: ... + @overload + def __call__(self, val: None) -> None: ... + def __call__(self, val: Union[str, None]) -> Union[str, None]: + if val is None: + return None + if not isinstance(val, str): + raise TypeError("Argument should be str") + if not val: + return "" + decoder = cast(codecs.BufferedIncrementalDecoder, utf8_decoder()) + ret = [] + idx = 0 + while idx < len(val): + ch = val[idx] + idx += 1 + if ch == "%" and idx <= len(val) - 2: + pct = val[idx : idx + 2] + if _IS_HEX_STR.fullmatch(pct): + b = bytes([int(pct, base=16)]) + idx += 2 + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + start_pct = idx - 3 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 3]) + decoder.reset() + try: + unquoted = decoder.decode(b) + except UnicodeDecodeError: + ret.append(val[idx - 3 : idx]) + continue + if not unquoted: + continue + if self._qs and unquoted in "+=&;": + to_add = self._qs_quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + elif unquoted in self._unsafe or unquoted in self._ignore: + to_add = self._quoter(unquoted) + if to_add is None: # pragma: no cover + raise RuntimeError("Cannot quote None") + ret.append(to_add) + else: + ret.append(unquoted) + continue + + if decoder.buffer: + start_pct = idx - 1 - len(decoder.buffer) * 3 + ret.append(val[start_pct : idx - 1]) + decoder.reset() + + if ch == "+": + if (not self._qs and not self._plus) or ch in self._unsafe: + ret.append("+") + else: + ret.append(" ") + continue + + if ch in self._unsafe: + ret.append("%") + h = hex(ord(ch)).upper()[2:] + for ch in h: + ret.append(ch) + continue + + ret.append(ch) + + if decoder.buffer: + ret.append(val[-len(decoder.buffer) * 3 :]) + + ret2 = "".join(ret) + if ret2 == val: + return val + return ret2 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_url.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_url.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa347f9c193e18da4f0ebd817b4589cda291da2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/_url.py @@ -0,0 +1,1604 @@ +import re +import sys +import warnings +from collections.abc import Mapping, Sequence +from enum import Enum +from functools import _CacheInfo, lru_cache +from ipaddress import ip_address +from typing import TYPE_CHECKING, Any, NoReturn, TypedDict, TypeVar, Union, overload +from urllib.parse import SplitResult, uses_relative + +import idna +from multidict import MultiDict, MultiDictProxy +from propcache.api import under_cached_property as cached_property + +from ._parse import ( + USES_AUTHORITY, + SplitURLType, + make_netloc, + query_to_pairs, + split_netloc, + split_url, + unsplit_result, +) +from ._path import normalize_path, normalize_path_segments +from ._query import ( + Query, + QueryVariable, + SimpleQuery, + get_str_query, + get_str_query_from_iterable, + get_str_query_from_sequence_iterable, +) +from ._quoters import ( + FRAGMENT_QUOTER, + FRAGMENT_REQUOTER, + PATH_QUOTER, + PATH_REQUOTER, + PATH_SAFE_UNQUOTER, + PATH_UNQUOTER, + QS_UNQUOTER, + QUERY_QUOTER, + QUERY_REQUOTER, + QUOTER, + REQUOTER, + UNQUOTER, + human_quote, +) + +DEFAULT_PORTS = {"http": 80, "https": 443, "ws": 80, "wss": 443, "ftp": 21} +USES_RELATIVE = frozenset(uses_relative) + +# Special schemes https://url.spec.whatwg.org/#special-scheme +# are not allowed to have an empty host https://url.spec.whatwg.org/#url-representation +SCHEME_REQUIRES_HOST = frozenset(("http", "https", "ws", "wss", "ftp")) + + +# reg-name: unreserved / pct-encoded / sub-delims +# this pattern matches anything that is *not* in those classes. and is only used +# on lower-cased ASCII values. +NOT_REG_NAME = re.compile( + r""" + # any character not in the unreserved or sub-delims sets, plus % + # (validated with the additional check for pct-encoded sequences below) + [^a-z0-9\-._~!$&'()*+,;=%] + | + # % only allowed if it is part of a pct-encoded + # sequence of 2 hex digits. + %(?![0-9a-f]{2}) + """, + re.VERBOSE, +) + +_T = TypeVar("_T") + +if sys.version_info >= (3, 11): + from typing import Self +else: + Self = Any + + +class UndefinedType(Enum): + """Singleton type for use with not set sentinel values.""" + + _singleton = 0 + + +UNDEFINED = UndefinedType._singleton + + +class CacheInfo(TypedDict): + """Host encoding cache.""" + + idna_encode: _CacheInfo + idna_decode: _CacheInfo + ip_address: _CacheInfo + host_validate: _CacheInfo + encode_host: _CacheInfo + + +class _InternalURLCache(TypedDict, total=False): + _val: SplitURLType + _origin: "URL" + absolute: bool + hash: int + scheme: str + raw_authority: str + authority: str + raw_user: Union[str, None] + user: Union[str, None] + raw_password: Union[str, None] + password: Union[str, None] + raw_host: Union[str, None] + host: Union[str, None] + host_subcomponent: Union[str, None] + host_port_subcomponent: Union[str, None] + port: Union[int, None] + explicit_port: Union[int, None] + raw_path: str + path: str + _parsed_query: list[tuple[str, str]] + query: "MultiDictProxy[str]" + raw_query_string: str + query_string: str + path_qs: str + raw_path_qs: str + raw_fragment: str + fragment: str + raw_parts: tuple[str, ...] + parts: tuple[str, ...] + parent: "URL" + raw_name: str + name: str + raw_suffix: str + suffix: str + raw_suffixes: tuple[str, ...] + suffixes: tuple[str, ...] + + +def rewrite_module(obj: _T) -> _T: + obj.__module__ = "yarl" + return obj + + +@lru_cache +def encode_url(url_str: str) -> "URL": + """Parse unencoded URL.""" + cache: _InternalURLCache = {} + host: Union[str, None] + scheme, netloc, path, query, fragment = split_url(url_str) + if not netloc: # netloc + host = "" + else: + if ":" in netloc or "@" in netloc or "[" in netloc: + # Complex netloc + username, password, host, port = split_netloc(netloc) + else: + username = password = port = None + host = netloc + if host is None: + if scheme in SCHEME_REQUIRES_HOST: + msg = ( + "Invalid URL: host is required for " + f"absolute urls with the {scheme} scheme" + ) + raise ValueError(msg) + else: + host = "" + host = _encode_host(host, validate_host=False) + # Remove brackets as host encoder adds back brackets for IPv6 addresses + cache["raw_host"] = host[1:-1] if "[" in host else host + cache["explicit_port"] = port + if password is None and username is None: + # Fast path for URLs without user, password + netloc = host if port is None else f"{host}:{port}" + cache["raw_user"] = None + cache["raw_password"] = None + else: + raw_user = REQUOTER(username) if username else username + raw_password = REQUOTER(password) if password else password + netloc = make_netloc(raw_user, raw_password, host, port) + cache["raw_user"] = raw_user + cache["raw_password"] = raw_password + + if path: + path = PATH_REQUOTER(path) + if netloc and "." in path: + path = normalize_path(path) + if query: + query = QUERY_REQUOTER(query) + if fragment: + fragment = FRAGMENT_REQUOTER(fragment) + + cache["scheme"] = scheme + cache["raw_path"] = "/" if not path and netloc else path + cache["raw_query_string"] = query + cache["raw_fragment"] = fragment + + self = object.__new__(URL) + self._scheme = scheme + self._netloc = netloc + self._path = path + self._query = query + self._fragment = fragment + self._cache = cache + return self + + +@lru_cache +def pre_encoded_url(url_str: str) -> "URL": + """Parse pre-encoded URL.""" + self = object.__new__(URL) + val = split_url(url_str) + self._scheme, self._netloc, self._path, self._query, self._fragment = val + self._cache = {} + return self + + +@lru_cache +def build_pre_encoded_url( + scheme: str, + authority: str, + user: Union[str, None], + password: Union[str, None], + host: str, + port: Union[int, None], + path: str, + query_string: str, + fragment: str, +) -> "URL": + """Build a pre-encoded URL from parts.""" + self = object.__new__(URL) + self._scheme = scheme + if authority: + self._netloc = authority + elif host: + if port is not None: + port = None if port == DEFAULT_PORTS.get(scheme) else port + if user is None and password is None: + self._netloc = host if port is None else f"{host}:{port}" + else: + self._netloc = make_netloc(user, password, host, port) + else: + self._netloc = "" + self._path = path + self._query = query_string + self._fragment = fragment + self._cache = {} + return self + + +def from_parts_uncached( + scheme: str, netloc: str, path: str, query: str, fragment: str +) -> "URL": + """Create a new URL from parts.""" + self = object.__new__(URL) + self._scheme = scheme + self._netloc = netloc + self._path = path + self._query = query + self._fragment = fragment + self._cache = {} + return self + + +from_parts = lru_cache(from_parts_uncached) + + +@rewrite_module +class URL: + # Don't derive from str + # follow pathlib.Path design + # probably URL will not suffer from pathlib problems: + # it's intended for libraries like aiohttp, + # not to be passed into standard library functions like os.open etc. + + # URL grammar (RFC 3986) + # pct-encoded = "%" HEXDIG HEXDIG + # reserved = gen-delims / sub-delims + # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" + # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" + # / "*" / "+" / "," / ";" / "=" + # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + # URI = scheme ":" hier-part [ "?" query ] [ "#" fragment ] + # hier-part = "//" authority path-abempty + # / path-absolute + # / path-rootless + # / path-empty + # scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) + # authority = [ userinfo "@" ] host [ ":" port ] + # userinfo = *( unreserved / pct-encoded / sub-delims / ":" ) + # host = IP-literal / IPv4address / reg-name + # IP-literal = "[" ( IPv6address / IPvFuture ) "]" + # IPvFuture = "v" 1*HEXDIG "." 1*( unreserved / sub-delims / ":" ) + # IPv6address = 6( h16 ":" ) ls32 + # / "::" 5( h16 ":" ) ls32 + # / [ h16 ] "::" 4( h16 ":" ) ls32 + # / [ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + # / [ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + # / [ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + # / [ *4( h16 ":" ) h16 ] "::" ls32 + # / [ *5( h16 ":" ) h16 ] "::" h16 + # / [ *6( h16 ":" ) h16 ] "::" + # ls32 = ( h16 ":" h16 ) / IPv4address + # ; least-significant 32 bits of address + # h16 = 1*4HEXDIG + # ; 16 bits of address represented in hexadecimal + # IPv4address = dec-octet "." dec-octet "." dec-octet "." dec-octet + # dec-octet = DIGIT ; 0-9 + # / %x31-39 DIGIT ; 10-99 + # / "1" 2DIGIT ; 100-199 + # / "2" %x30-34 DIGIT ; 200-249 + # / "25" %x30-35 ; 250-255 + # reg-name = *( unreserved / pct-encoded / sub-delims ) + # port = *DIGIT + # path = path-abempty ; begins with "/" or is empty + # / path-absolute ; begins with "/" but not "//" + # / path-noscheme ; begins with a non-colon segment + # / path-rootless ; begins with a segment + # / path-empty ; zero characters + # path-abempty = *( "/" segment ) + # path-absolute = "/" [ segment-nz *( "/" segment ) ] + # path-noscheme = segment-nz-nc *( "/" segment ) + # path-rootless = segment-nz *( "/" segment ) + # path-empty = 0 + # segment = *pchar + # segment-nz = 1*pchar + # segment-nz-nc = 1*( unreserved / pct-encoded / sub-delims / "@" ) + # ; non-zero-length segment without any colon ":" + # pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + # query = *( pchar / "/" / "?" ) + # fragment = *( pchar / "/" / "?" ) + # URI-reference = URI / relative-ref + # relative-ref = relative-part [ "?" query ] [ "#" fragment ] + # relative-part = "//" authority path-abempty + # / path-absolute + # / path-noscheme + # / path-empty + # absolute-URI = scheme ":" hier-part [ "?" query ] + __slots__ = ("_cache", "_scheme", "_netloc", "_path", "_query", "_fragment") + + _cache: _InternalURLCache + _scheme: str + _netloc: str + _path: str + _query: str + _fragment: str + + def __new__( + cls, + val: Union[str, SplitResult, "URL", UndefinedType] = UNDEFINED, + *, + encoded: bool = False, + strict: Union[bool, None] = None, + ) -> "URL": + if strict is not None: # pragma: no cover + warnings.warn("strict parameter is ignored") + if type(val) is str: + return pre_encoded_url(val) if encoded else encode_url(val) + if type(val) is cls: + return val + if type(val) is SplitResult: + if not encoded: + raise ValueError("Cannot apply decoding to SplitResult") + return from_parts(*val) + if isinstance(val, str): + return pre_encoded_url(str(val)) if encoded else encode_url(str(val)) + if val is UNDEFINED: + # Special case for UNDEFINED since it might be unpickling and we do + # not want to cache as the `__set_state__` call would mutate the URL + # object in the `pre_encoded_url` or `encoded_url` caches. + self = object.__new__(URL) + self._scheme = self._netloc = self._path = self._query = self._fragment = "" + self._cache = {} + return self + raise TypeError("Constructor parameter should be str") + + @classmethod + def build( + cls, + *, + scheme: str = "", + authority: str = "", + user: Union[str, None] = None, + password: Union[str, None] = None, + host: str = "", + port: Union[int, None] = None, + path: str = "", + query: Union[Query, None] = None, + query_string: str = "", + fragment: str = "", + encoded: bool = False, + ) -> "URL": + """Creates and returns a new URL""" + + if authority and (user or password or host or port): + raise ValueError( + 'Can\'t mix "authority" with "user", "password", "host" or "port".' + ) + if port is not None and not isinstance(port, int): + raise TypeError(f"The port is required to be int, got {type(port)!r}.") + if port and not host: + raise ValueError('Can\'t build URL with "port" but without "host".') + if query and query_string: + raise ValueError('Only one of "query" or "query_string" should be passed') + if ( + scheme is None # type: ignore[redundant-expr] + or authority is None # type: ignore[redundant-expr] + or host is None # type: ignore[redundant-expr] + or path is None # type: ignore[redundant-expr] + or query_string is None # type: ignore[redundant-expr] + or fragment is None + ): + raise TypeError( + 'NoneType is illegal for "scheme", "authority", "host", "path", ' + '"query_string", and "fragment" args, use empty string instead.' + ) + + if query: + query_string = get_str_query(query) or "" + + if encoded: + return build_pre_encoded_url( + scheme, + authority, + user, + password, + host, + port, + path, + query_string, + fragment, + ) + + self = object.__new__(URL) + self._scheme = scheme + _host: Union[str, None] = None + if authority: + user, password, _host, port = split_netloc(authority) + _host = _encode_host(_host, validate_host=False) if _host else "" + elif host: + _host = _encode_host(host, validate_host=True) + else: + self._netloc = "" + + if _host is not None: + if port is not None: + port = None if port == DEFAULT_PORTS.get(scheme) else port + if user is None and password is None: + self._netloc = _host if port is None else f"{_host}:{port}" + else: + self._netloc = make_netloc(user, password, _host, port, True) + + path = PATH_QUOTER(path) if path else path + if path and self._netloc: + if "." in path: + path = normalize_path(path) + if path[0] != "/": + msg = ( + "Path in a URL with authority should " + "start with a slash ('/') if set" + ) + raise ValueError(msg) + + self._path = path + if not query and query_string: + query_string = QUERY_QUOTER(query_string) + self._query = query_string + self._fragment = FRAGMENT_QUOTER(fragment) if fragment else fragment + self._cache = {} + return self + + def __init_subclass__(cls) -> NoReturn: + raise TypeError(f"Inheriting a class {cls!r} from URL is forbidden") + + def __str__(self) -> str: + if not self._path and self._netloc and (self._query or self._fragment): + path = "/" + else: + path = self._path + if (port := self.explicit_port) is not None and port == DEFAULT_PORTS.get( + self._scheme + ): + # port normalization - using None for default ports to remove from rendering + # https://datatracker.ietf.org/doc/html/rfc3986.html#section-6.2.3 + host = self.host_subcomponent + netloc = make_netloc(self.raw_user, self.raw_password, host, None) + else: + netloc = self._netloc + return unsplit_result(self._scheme, netloc, path, self._query, self._fragment) + + def __repr__(self) -> str: + return f"{self.__class__.__name__}('{str(self)}')" + + def __bytes__(self) -> bytes: + return str(self).encode("ascii") + + def __eq__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + + path1 = "/" if not self._path and self._netloc else self._path + path2 = "/" if not other._path and other._netloc else other._path + return ( + self._scheme == other._scheme + and self._netloc == other._netloc + and path1 == path2 + and self._query == other._query + and self._fragment == other._fragment + ) + + def __hash__(self) -> int: + if (ret := self._cache.get("hash")) is None: + path = "/" if not self._path and self._netloc else self._path + ret = self._cache["hash"] = hash( + (self._scheme, self._netloc, path, self._query, self._fragment) + ) + return ret + + def __le__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val <= other._val + + def __lt__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val < other._val + + def __ge__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val >= other._val + + def __gt__(self, other: object) -> bool: + if type(other) is not URL: + return NotImplemented + return self._val > other._val + + def __truediv__(self, name: str) -> "URL": + if not isinstance(name, str): + return NotImplemented # type: ignore[unreachable] + return self._make_child((str(name),)) + + def __mod__(self, query: Query) -> "URL": + return self.update_query(query) + + def __bool__(self) -> bool: + return bool(self._netloc or self._path or self._query or self._fragment) + + def __getstate__(self) -> tuple[SplitResult]: + return (tuple.__new__(SplitResult, self._val),) + + def __setstate__( + self, state: Union[tuple[SplitURLType], tuple[None, _InternalURLCache]] + ) -> None: + if state[0] is None and isinstance(state[1], dict): + # default style pickle + val = state[1]["_val"] + else: + unused: list[object] + val, *unused = state + self._scheme, self._netloc, self._path, self._query, self._fragment = val + self._cache = {} + + def _cache_netloc(self) -> None: + """Cache the netloc parts of the URL.""" + c = self._cache + split_loc = split_netloc(self._netloc) + c["raw_user"], c["raw_password"], c["raw_host"], c["explicit_port"] = split_loc + + def is_absolute(self) -> bool: + """A check for absolute URLs. + + Return True for absolute ones (having scheme or starting + with //), False otherwise. + + Is is preferred to call the .absolute property instead + as it is cached. + """ + return self.absolute + + def is_default_port(self) -> bool: + """A check for default port. + + Return True if port is default for specified scheme, + e.g. 'http://python.org' or 'http://python.org:80', False + otherwise. + + Return False for relative URLs. + + """ + if (explicit := self.explicit_port) is None: + # If the explicit port is None, then the URL must be + # using the default port unless its a relative URL + # which does not have an implicit port / default port + return self._netloc != "" + return explicit == DEFAULT_PORTS.get(self._scheme) + + def origin(self) -> "URL": + """Return an URL with scheme, host and port parts only. + + user, password, path, query and fragment are removed. + + """ + # TODO: add a keyword-only option for keeping user/pass maybe? + return self._origin + + @cached_property + def _val(self) -> SplitURLType: + return (self._scheme, self._netloc, self._path, self._query, self._fragment) + + @cached_property + def _origin(self) -> "URL": + """Return an URL with scheme, host and port parts only. + + user, password, path, query and fragment are removed. + """ + if not (netloc := self._netloc): + raise ValueError("URL should be absolute") + if not (scheme := self._scheme): + raise ValueError("URL should have scheme") + if "@" in netloc: + encoded_host = self.host_subcomponent + netloc = make_netloc(None, None, encoded_host, self.explicit_port) + elif not self._path and not self._query and not self._fragment: + return self + return from_parts(scheme, netloc, "", "", "") + + def relative(self) -> "URL": + """Return a relative part of the URL. + + scheme, user, password, host and port are removed. + + """ + if not self._netloc: + raise ValueError("URL should be absolute") + return from_parts("", "", self._path, self._query, self._fragment) + + @cached_property + def absolute(self) -> bool: + """A check for absolute URLs. + + Return True for absolute ones (having scheme or starting + with //), False otherwise. + + """ + # `netloc`` is an empty string for relative URLs + # Checking `netloc` is faster than checking `hostname` + # because `hostname` is a property that does some extra work + # to parse the host from the `netloc` + return self._netloc != "" + + @cached_property + def scheme(self) -> str: + """Scheme for absolute URLs. + + Empty string for relative URLs or URLs starting with // + + """ + return self._scheme + + @cached_property + def raw_authority(self) -> str: + """Encoded authority part of URL. + + Empty string for relative URLs. + + """ + return self._netloc + + @cached_property + def authority(self) -> str: + """Decoded authority part of URL. + + Empty string for relative URLs. + + """ + return make_netloc(self.user, self.password, self.host, self.port) + + @cached_property + def raw_user(self) -> Union[str, None]: + """Encoded user part of URL. + + None if user is missing. + + """ + # not .username + self._cache_netloc() + return self._cache["raw_user"] + + @cached_property + def user(self) -> Union[str, None]: + """Decoded user part of URL. + + None if user is missing. + + """ + if (raw_user := self.raw_user) is None: + return None + return UNQUOTER(raw_user) + + @cached_property + def raw_password(self) -> Union[str, None]: + """Encoded password part of URL. + + None if password is missing. + + """ + self._cache_netloc() + return self._cache["raw_password"] + + @cached_property + def password(self) -> Union[str, None]: + """Decoded password part of URL. + + None if password is missing. + + """ + if (raw_password := self.raw_password) is None: + return None + return UNQUOTER(raw_password) + + @cached_property + def raw_host(self) -> Union[str, None]: + """Encoded host part of URL. + + None for relative URLs. + + When working with IPv6 addresses, use the `host_subcomponent` property instead + as it will return the host subcomponent with brackets. + """ + # Use host instead of hostname for sake of shortness + # May add .hostname prop later + self._cache_netloc() + return self._cache["raw_host"] + + @cached_property + def host(self) -> Union[str, None]: + """Decoded host part of URL. + + None for relative URLs. + + """ + if (raw := self.raw_host) is None: + return None + if raw and raw[-1].isdigit() or ":" in raw: + # IP addresses are never IDNA encoded + return raw + return _idna_decode(raw) + + @cached_property + def host_subcomponent(self) -> Union[str, None]: + """Return the host subcomponent part of URL. + + None for relative URLs. + + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + + `IP-literal = "[" ( IPv6address / IPvFuture ) "]"` + + Examples: + - `http://example.com:8080` -> `example.com` + - `http://example.com:80` -> `example.com` + - `https://127.0.0.1:8443` -> `127.0.0.1` + - `https://[::1]:8443` -> `[::1]` + - `http://[::1]` -> `[::1]` + + """ + if (raw := self.raw_host) is None: + return None + return f"[{raw}]" if ":" in raw else raw + + @cached_property + def host_port_subcomponent(self) -> Union[str, None]: + """Return the host and port subcomponent part of URL. + + Trailing dots are removed from the host part. + + This value is suitable for use in the Host header of an HTTP request. + + None for relative URLs. + + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + `IP-literal = "[" ( IPv6address / IPvFuture ) "]"` + https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.3 + port = *DIGIT + + Examples: + - `http://example.com:8080` -> `example.com:8080` + - `http://example.com:80` -> `example.com` + - `http://example.com.:80` -> `example.com` + - `https://127.0.0.1:8443` -> `127.0.0.1:8443` + - `https://[::1]:8443` -> `[::1]:8443` + - `http://[::1]` -> `[::1]` + + """ + if (raw := self.raw_host) is None: + return None + if raw[-1] == ".": + # Remove all trailing dots from the netloc as while + # they are valid FQDNs in DNS, TLS validation fails. + # See https://github.com/aio-libs/aiohttp/issues/3636. + # To avoid string manipulation we only call rstrip if + # the last character is a dot. + raw = raw.rstrip(".") + port = self.explicit_port + if port is None or port == DEFAULT_PORTS.get(self._scheme): + return f"[{raw}]" if ":" in raw else raw + return f"[{raw}]:{port}" if ":" in raw else f"{raw}:{port}" + + @cached_property + def port(self) -> Union[int, None]: + """Port part of URL, with scheme-based fallback. + + None for relative URLs or URLs without explicit port and + scheme without default port substitution. + + """ + if (explicit_port := self.explicit_port) is not None: + return explicit_port + return DEFAULT_PORTS.get(self._scheme) + + @cached_property + def explicit_port(self) -> Union[int, None]: + """Port part of URL, without scheme-based fallback. + + None for relative URLs or URLs without explicit port. + + """ + self._cache_netloc() + return self._cache["explicit_port"] + + @cached_property + def raw_path(self) -> str: + """Encoded path of URL. + + / for absolute URLs without path part. + + """ + return self._path if self._path or not self._netloc else "/" + + @cached_property + def path(self) -> str: + """Decoded path of URL. + + / for absolute URLs without path part. + + """ + return PATH_UNQUOTER(self._path) if self._path else "/" if self._netloc else "" + + @cached_property + def path_safe(self) -> str: + """Decoded path of URL. + + / for absolute URLs without path part. + + / (%2F) and % (%25) are not decoded + + """ + if self._path: + return PATH_SAFE_UNQUOTER(self._path) + return "/" if self._netloc else "" + + @cached_property + def _parsed_query(self) -> list[tuple[str, str]]: + """Parse query part of URL.""" + return query_to_pairs(self._query) + + @cached_property + def query(self) -> "MultiDictProxy[str]": + """A MultiDictProxy representing parsed query parameters in decoded + representation. + + Empty value if URL has no query part. + + """ + return MultiDictProxy(MultiDict(self._parsed_query)) + + @cached_property + def raw_query_string(self) -> str: + """Encoded query part of URL. + + Empty string if query is missing. + + """ + return self._query + + @cached_property + def query_string(self) -> str: + """Decoded query part of URL. + + Empty string if query is missing. + + """ + return QS_UNQUOTER(self._query) if self._query else "" + + @cached_property + def path_qs(self) -> str: + """Decoded path of URL with query.""" + return self.path if not (q := self.query_string) else f"{self.path}?{q}" + + @cached_property + def raw_path_qs(self) -> str: + """Encoded path of URL with query.""" + if q := self._query: + return f"{self._path}?{q}" if self._path or not self._netloc else f"/?{q}" + return self._path if self._path or not self._netloc else "/" + + @cached_property + def raw_fragment(self) -> str: + """Encoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return self._fragment + + @cached_property + def fragment(self) -> str: + """Decoded fragment part of URL. + + Empty string if fragment is missing. + + """ + return UNQUOTER(self._fragment) if self._fragment else "" + + @cached_property + def raw_parts(self) -> tuple[str, ...]: + """A tuple containing encoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + path = self._path + if self._netloc: + return ("/", *path[1:].split("/")) if path else ("/",) + if path and path[0] == "/": + return ("/", *path[1:].split("/")) + return tuple(path.split("/")) + + @cached_property + def parts(self) -> tuple[str, ...]: + """A tuple containing decoded *path* parts. + + ('/',) for absolute URLs if *path* is missing. + + """ + return tuple(UNQUOTER(part) for part in self.raw_parts) + + @cached_property + def parent(self) -> "URL": + """A new URL with last part of path removed and cleaned up query and + fragment. + + """ + path = self._path + if not path or path == "/": + if self._fragment or self._query: + return from_parts(self._scheme, self._netloc, path, "", "") + return self + parts = path.split("/") + return from_parts(self._scheme, self._netloc, "/".join(parts[:-1]), "", "") + + @cached_property + def raw_name(self) -> str: + """The last part of raw_parts.""" + parts = self.raw_parts + if not self._netloc: + return parts[-1] + parts = parts[1:] + return parts[-1] if parts else "" + + @cached_property + def name(self) -> str: + """The last part of parts.""" + return UNQUOTER(self.raw_name) + + @cached_property + def raw_suffix(self) -> str: + name = self.raw_name + i = name.rfind(".") + return name[i:] if 0 < i < len(name) - 1 else "" + + @cached_property + def suffix(self) -> str: + return UNQUOTER(self.raw_suffix) + + @cached_property + def raw_suffixes(self) -> tuple[str, ...]: + name = self.raw_name + if name.endswith("."): + return () + name = name.lstrip(".") + return tuple("." + suffix for suffix in name.split(".")[1:]) + + @cached_property + def suffixes(self) -> tuple[str, ...]: + return tuple(UNQUOTER(suffix) for suffix in self.raw_suffixes) + + def _make_child(self, paths: "Sequence[str]", encoded: bool = False) -> "URL": + """ + add paths to self._path, accounting for absolute vs relative paths, + keep existing, but do not create new, empty segments + """ + parsed: list[str] = [] + needs_normalize: bool = False + for idx, path in enumerate(reversed(paths)): + # empty segment of last is not removed + last = idx == 0 + if path and path[0] == "/": + raise ValueError( + f"Appending path {path!r} starting from slash is forbidden" + ) + # We need to quote the path if it is not already encoded + # This cannot be done at the end because the existing + # path is already quoted and we do not want to double quote + # the existing path. + path = path if encoded else PATH_QUOTER(path) + needs_normalize |= "." in path + segments = path.split("/") + segments.reverse() + # remove trailing empty segment for all but the last path + parsed += segments[1:] if not last and segments[0] == "" else segments + + if (path := self._path) and (old_segments := path.split("/")): + # If the old path ends with a slash, the last segment is an empty string + # and should be removed before adding the new path segments. + old = old_segments[:-1] if old_segments[-1] == "" else old_segments + old.reverse() + parsed += old + + # If the netloc is present, inject a leading slash when adding a + # path to an absolute URL where there was none before. + if (netloc := self._netloc) and parsed and parsed[-1] != "": + parsed.append("") + + parsed.reverse() + if not netloc or not needs_normalize: + return from_parts(self._scheme, netloc, "/".join(parsed), "", "") + + path = "/".join(normalize_path_segments(parsed)) + # If normalizing the path segments removed the leading slash, add it back. + if path and path[0] != "/": + path = f"/{path}" + return from_parts(self._scheme, netloc, path, "", "") + + def with_scheme(self, scheme: str) -> "URL": + """Return a new URL with scheme replaced.""" + # N.B. doesn't cleanup query/fragment + if not isinstance(scheme, str): + raise TypeError("Invalid scheme type") + lower_scheme = scheme.lower() + netloc = self._netloc + if not netloc and lower_scheme in SCHEME_REQUIRES_HOST: + msg = ( + "scheme replacement is not allowed for " + f"relative URLs for the {lower_scheme} scheme" + ) + raise ValueError(msg) + return from_parts(lower_scheme, netloc, self._path, self._query, self._fragment) + + def with_user(self, user: Union[str, None]) -> "URL": + """Return a new URL with user replaced. + + Autoencode user if needed. + + Clear user/password if user is None. + + """ + # N.B. doesn't cleanup query/fragment + if user is None: + password = None + elif isinstance(user, str): + user = QUOTER(user) + password = self.raw_password + else: + raise TypeError("Invalid user type") + if not (netloc := self._netloc): + raise ValueError("user replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + netloc = make_netloc(user, password, encoded_host, self.explicit_port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_password(self, password: Union[str, None]) -> "URL": + """Return a new URL with password replaced. + + Autoencode password if needed. + + Clear password if argument is None. + + """ + # N.B. doesn't cleanup query/fragment + if password is None: + pass + elif isinstance(password, str): + password = QUOTER(password) + else: + raise TypeError("Invalid password type") + if not (netloc := self._netloc): + raise ValueError("password replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + port = self.explicit_port + netloc = make_netloc(self.raw_user, password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_host(self, host: str) -> "URL": + """Return a new URL with host replaced. + + Autoencode host if needed. + + Changing host for relative URLs is not allowed, use .join() + instead. + + """ + # N.B. doesn't cleanup query/fragment + if not isinstance(host, str): + raise TypeError("Invalid host type") + if not (netloc := self._netloc): + raise ValueError("host replacement is not allowed for relative URLs") + if not host: + raise ValueError("host removing is not allowed") + encoded_host = _encode_host(host, validate_host=True) if host else "" + port = self.explicit_port + netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_port(self, port: Union[int, None]) -> "URL": + """Return a new URL with port replaced. + + Clear port to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if port is not None: + if isinstance(port, bool) or not isinstance(port, int): + raise TypeError(f"port should be int or None, got {type(port)}") + if not (0 <= port <= 65535): + raise ValueError(f"port must be between 0 and 65535, got {port}") + if not (netloc := self._netloc): + raise ValueError("port replacement is not allowed for relative URLs") + encoded_host = self.host_subcomponent or "" + netloc = make_netloc(self.raw_user, self.raw_password, encoded_host, port) + return from_parts(self._scheme, netloc, self._path, self._query, self._fragment) + + def with_path( + self, + path: str, + *, + encoded: bool = False, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with path replaced.""" + netloc = self._netloc + if not encoded: + path = PATH_QUOTER(path) + if netloc: + path = normalize_path(path) if "." in path else path + if path and path[0] != "/": + path = f"/{path}" + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, path, query, fragment) + + @overload + def with_query(self, query: Query) -> "URL": ... + + @overload + def with_query(self, **kwargs: QueryVariable) -> "URL": ... + + def with_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part replaced. + + Accepts any Mapping (e.g. dict, multidict.MultiDict instances) + or str, autoencode the argument if needed. + + A sequence of (key, value) pairs is supported as well. + + It also can take an arbitrary number of keyword arguments. + + Clear query if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + query = get_str_query(*args, **kwargs) or "" + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + @overload + def extend_query(self, query: Query) -> "URL": ... + + @overload + def extend_query(self, **kwargs: QueryVariable) -> "URL": ... + + def extend_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part combined with the existing. + + This method will not remove existing query parameters. + + Example: + >>> url = URL('http://example.com/?a=1&b=2') + >>> url.extend_query(a=3, c=4) + URL('http://example.com/?a=1&b=2&a=3&c=4') + """ + if not (new_query := get_str_query(*args, **kwargs)): + return self + if query := self._query: + # both strings are already encoded so we can use a simple + # string join + query += new_query if query[-1] == "&" else f"&{new_query}" + else: + query = new_query + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + @overload + def update_query(self, query: Query) -> "URL": ... + + @overload + def update_query(self, **kwargs: QueryVariable) -> "URL": ... + + def update_query(self, *args: Any, **kwargs: Any) -> "URL": + """Return a new URL with query part updated. + + This method will overwrite existing query parameters. + + Example: + >>> url = URL('http://example.com/?a=1&b=2') + >>> url.update_query(a=3, c=4) + URL('http://example.com/?a=3&b=2&c=4') + """ + in_query: Union[str, Mapping[str, QueryVariable], None] + if kwargs: + if args: + msg = "Either kwargs or single query parameter must be present" + raise ValueError(msg) + in_query = kwargs + elif len(args) == 1: + in_query = args[0] + else: + raise ValueError("Either kwargs or single query parameter must be present") + + if in_query is None: + query = "" + elif not in_query: + query = self._query + elif isinstance(in_query, Mapping): + qm: MultiDict[QueryVariable] = MultiDict(self._parsed_query) + qm.update(in_query) + query = get_str_query_from_sequence_iterable(qm.items()) + elif isinstance(in_query, str): + qstr: MultiDict[str] = MultiDict(self._parsed_query) + qstr.update(query_to_pairs(in_query)) + query = get_str_query_from_iterable(qstr.items()) + elif isinstance(in_query, (bytes, bytearray, memoryview)): # type: ignore[unreachable] + msg = "Invalid query type: bytes, bytearray and memoryview are forbidden" + raise TypeError(msg) + elif isinstance(in_query, Sequence): + # We don't expect sequence values if we're given a list of pairs + # already; only mappings like builtin `dict` which can't have the + # same key pointing to multiple values are allowed to use + # `_query_seq_pairs`. + qs: MultiDict[SimpleQuery] = MultiDict(self._parsed_query) + qs.update(in_query) + query = get_str_query_from_iterable(qs.items()) + else: + raise TypeError( + "Invalid query type: only str, mapping or " + "sequence of (key, value) pairs is allowed" + ) + return from_parts_uncached( + self._scheme, self._netloc, self._path, query, self._fragment + ) + + def without_query_params(self, *query_params: str) -> "URL": + """Remove some keys from query part and return new URL.""" + params_to_remove = set(query_params) & self.query.keys() + if not params_to_remove: + return self + return self.with_query( + tuple( + (name, value) + for name, value in self.query.items() + if name not in params_to_remove + ) + ) + + def with_fragment(self, fragment: Union[str, None]) -> "URL": + """Return a new URL with fragment replaced. + + Autoencode fragment if needed. + + Clear fragment to default if None is passed. + + """ + # N.B. doesn't cleanup query/fragment + if fragment is None: + raw_fragment = "" + elif not isinstance(fragment, str): + raise TypeError("Invalid fragment type") + else: + raw_fragment = FRAGMENT_QUOTER(fragment) + if self._fragment == raw_fragment: + return self + return from_parts( + self._scheme, self._netloc, self._path, self._query, raw_fragment + ) + + def with_name( + self, + name: str, + *, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with name (last part of path) replaced. + + Query and fragment parts are cleaned up. + + Name is encoded if needed. + + """ + # N.B. DOES cleanup query/fragment + if not isinstance(name, str): + raise TypeError("Invalid name type") + if "/" in name: + raise ValueError("Slash in name is not allowed") + name = PATH_QUOTER(name) + if name in (".", ".."): + raise ValueError(". and .. values are forbidden") + parts = list(self.raw_parts) + if netloc := self._netloc: + if len(parts) == 1: + parts.append(name) + else: + parts[-1] = name + parts[0] = "" # replace leading '/' + else: + parts[-1] = name + if parts[0] == "/": + parts[0] = "" # replace leading '/' + + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, "/".join(parts), query, fragment) + + def with_suffix( + self, + suffix: str, + *, + keep_query: bool = False, + keep_fragment: bool = False, + ) -> "URL": + """Return a new URL with suffix (file extension of name) replaced. + + Query and fragment parts are cleaned up. + + suffix is encoded if needed. + """ + if not isinstance(suffix, str): + raise TypeError("Invalid suffix type") + if suffix and not suffix[0] == "." or suffix == "." or "/" in suffix: + raise ValueError(f"Invalid suffix {suffix!r}") + name = self.raw_name + if not name: + raise ValueError(f"{self!r} has an empty name") + old_suffix = self.raw_suffix + suffix = PATH_QUOTER(suffix) + name = name + suffix if not old_suffix else name[: -len(old_suffix)] + suffix + if name in (".", ".."): + raise ValueError(". and .. values are forbidden") + parts = list(self.raw_parts) + if netloc := self._netloc: + if len(parts) == 1: + parts.append(name) + else: + parts[-1] = name + parts[0] = "" # replace leading '/' + else: + parts[-1] = name + if parts[0] == "/": + parts[0] = "" # replace leading '/' + + query = self._query if keep_query else "" + fragment = self._fragment if keep_fragment else "" + return from_parts(self._scheme, netloc, "/".join(parts), query, fragment) + + def join(self, url: "URL") -> "URL": + """Join URLs + + Construct a full (“absolute”) URL by combining a “base URL” + (self) with another URL (url). + + Informally, this uses components of the base URL, in + particular the addressing scheme, the network location and + (part of) the path, to provide missing components in the + relative URL. + + """ + if type(url) is not URL: + raise TypeError("url should be URL") + + scheme = url._scheme or self._scheme + if scheme != self._scheme or scheme not in USES_RELATIVE: + return url + + # scheme is in uses_authority as uses_authority is a superset of uses_relative + if (join_netloc := url._netloc) and scheme in USES_AUTHORITY: + return from_parts(scheme, join_netloc, url._path, url._query, url._fragment) + + orig_path = self._path + if join_path := url._path: + if join_path[0] == "/": + path = join_path + elif not orig_path: + path = f"/{join_path}" + elif orig_path[-1] == "/": + path = f"{orig_path}{join_path}" + else: + # … + # and relativizing ".." + # parts[0] is / for absolute urls, + # this join will add a double slash there + path = "/".join([*self.parts[:-1], ""]) + join_path + # which has to be removed + if orig_path[0] == "/": + path = path[1:] + path = normalize_path(path) if "." in path else path + else: + path = orig_path + + return from_parts( + scheme, + self._netloc, + path, + url._query if join_path or url._query else self._query, + url._fragment if join_path or url._fragment else self._fragment, + ) + + def joinpath(self, *other: str, encoded: bool = False) -> "URL": + """Return a new URL with the elements in other appended to the path.""" + return self._make_child(other, encoded=encoded) + + def human_repr(self) -> str: + """Return decoded human readable string for URL representation.""" + user = human_quote(self.user, "#/:?@[]") + password = human_quote(self.password, "#/:?@[]") + if (host := self.host) and ":" in host: + host = f"[{host}]" + path = human_quote(self.path, "#?") + if TYPE_CHECKING: + assert path is not None + query_string = "&".join( + "{}={}".format(human_quote(k, "#&+;="), human_quote(v, "#&+;=")) + for k, v in self.query.items() + ) + fragment = human_quote(self.fragment, "") + if TYPE_CHECKING: + assert fragment is not None + netloc = make_netloc(user, password, host, self.explicit_port) + return unsplit_result(self._scheme, netloc, path, query_string, fragment) + + +_DEFAULT_IDNA_SIZE = 256 +_DEFAULT_ENCODE_SIZE = 512 + + +@lru_cache(_DEFAULT_IDNA_SIZE) +def _idna_decode(raw: str) -> str: + try: + return idna.decode(raw.encode("ascii")) + except UnicodeError: # e.g. '::1' + return raw.encode("ascii").decode("idna") + + +@lru_cache(_DEFAULT_IDNA_SIZE) +def _idna_encode(host: str) -> str: + try: + return idna.encode(host, uts46=True).decode("ascii") + except UnicodeError: + return host.encode("idna").decode("ascii") + + +@lru_cache(_DEFAULT_ENCODE_SIZE) +def _encode_host(host: str, validate_host: bool) -> str: + """Encode host part of URL.""" + # If the host ends with a digit or contains a colon, its likely + # an IP address. + if host and (host[-1].isdigit() or ":" in host): + raw_ip, sep, zone = host.partition("%") + # If it looks like an IP, we check with _ip_compressed_version + # and fall-through if its not an IP address. This is a performance + # optimization to avoid parsing IP addresses as much as possible + # because it is orders of magnitude slower than almost any other + # operation this library does. + # Might be an IP address, check it + # + # IP Addresses can look like: + # https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.2 + # - 127.0.0.1 (last character is a digit) + # - 2001:db8::ff00:42:8329 (contains a colon) + # - 2001:db8::ff00:42:8329%eth0 (contains a colon) + # - [2001:db8::ff00:42:8329] (contains a colon -- brackets should + # have been removed before it gets here) + # Rare IP Address formats are not supported per: + # https://datatracker.ietf.org/doc/html/rfc3986#section-7.4 + # + # IP parsing is slow, so its wrapped in an LRU + try: + ip = ip_address(raw_ip) + except ValueError: + pass + else: + # These checks should not happen in the + # LRU to keep the cache size small + host = ip.compressed + if ip.version == 6: + return f"[{host}%{zone}]" if sep else f"[{host}]" + return f"{host}%{zone}" if sep else host + + # IDNA encoding is slow, skip it for ASCII-only strings + if host.isascii(): + # Check for invalid characters explicitly; _idna_encode() does this + # for non-ascii host names. + host = host.lower() + if validate_host and (invalid := NOT_REG_NAME.search(host)): + value, pos, extra = invalid.group(), invalid.start(), "" + if value == "@" or (value == ":" and "@" in host[pos:]): + # this looks like an authority string + extra = ( + ", if the value includes a username or password, " + "use 'authority' instead of 'host'" + ) + raise ValueError( + f"Host {host!r} cannot contain {value!r} (at position {pos}){extra}" + ) from None + return host + + return _idna_encode(host) + + +@rewrite_module +def cache_clear() -> None: + """Clear all LRU caches.""" + _idna_encode.cache_clear() + _idna_decode.cache_clear() + _encode_host.cache_clear() + + +@rewrite_module +def cache_info() -> CacheInfo: + """Report cache statistics.""" + return { + "idna_encode": _idna_encode.cache_info(), + "idna_decode": _idna_decode.cache_info(), + "ip_address": _encode_host.cache_info(), + "host_validate": _encode_host.cache_info(), + "encode_host": _encode_host.cache_info(), + } + + +@rewrite_module +def cache_configure( + *, + idna_encode_size: Union[int, None] = _DEFAULT_IDNA_SIZE, + idna_decode_size: Union[int, None] = _DEFAULT_IDNA_SIZE, + ip_address_size: Union[int, None, UndefinedType] = UNDEFINED, + host_validate_size: Union[int, None, UndefinedType] = UNDEFINED, + encode_host_size: Union[int, None, UndefinedType] = UNDEFINED, +) -> None: + """Configure LRU cache sizes.""" + global _idna_decode, _idna_encode, _encode_host + # ip_address_size, host_validate_size are no longer + # used, but are kept for backwards compatibility. + if ip_address_size is not UNDEFINED or host_validate_size is not UNDEFINED: + warnings.warn( + "cache_configure() no longer accepts the " + "ip_address_size or host_validate_size arguments, " + "they are used to set the encode_host_size instead " + "and will be removed in the future", + DeprecationWarning, + stacklevel=2, + ) + + if encode_host_size is not None: + for size in (ip_address_size, host_validate_size): + if size is None: + encode_host_size = None + elif encode_host_size is UNDEFINED: + if size is not UNDEFINED: + encode_host_size = size + elif size is not UNDEFINED: + if TYPE_CHECKING: + assert isinstance(size, int) + assert isinstance(encode_host_size, int) + encode_host_size = max(size, encode_host_size) + if encode_host_size is UNDEFINED: + encode_host_size = _DEFAULT_ENCODE_SIZE + + _encode_host = lru_cache(encode_host_size)(_encode_host.__wrapped__) + _idna_decode = lru_cache(idna_decode_size)(_idna_decode.__wrapped__) + _idna_encode = lru_cache(idna_encode_size)(_idna_encode.__wrapped__) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/py.typed b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..dcf2c804da5e19d617a03a6c68aa128d1d1f89a0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/agent/thirdparty_files/yarl/py.typed @@ -0,0 +1 @@ +# Placeholder diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/conda.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/conda.py new file mode 100644 index 0000000000000000000000000000000000000000..9740b8de8ed8feae419c18213481c7a21f87d64e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/conda.py @@ -0,0 +1,409 @@ +import hashlib +import json +import logging +import os +import platform +import runpy +import shutil +import subprocess +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional + +import yaml +from filelock import FileLock + +import ray +from ray._common.utils import ( + get_or_create_event_loop, + try_to_create_directory, +) +from ray._private.runtime_env.conda_utils import ( + create_conda_env_if_needed, + delete_conda_env, + get_conda_activate_commands, + get_conda_envs, + get_conda_info_json, +) +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.packaging import Protocol, parse_uri +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray._private.runtime_env.validation import parse_and_validate_conda +from ray._private.utils import ( + get_directory_size_bytes, + get_master_wheel_url, + get_release_wheel_url, + get_wheel_filename, +) + +default_logger = logging.getLogger(__name__) + +_WIN32 = os.name == "nt" + + +def _resolve_current_ray_path() -> str: + # When ray is built from source with pip install -e, + # ray.__file__ returns .../python/ray/__init__.py and this function returns + # ".../python". + # When ray is installed from a prebuilt binary, ray.__file__ returns + # .../site-packages/ray/__init__.py and this function returns + # ".../site-packages". + return os.path.split(os.path.split(ray.__file__)[0])[0] + + +def _get_ray_setup_spec(): + """Find the Ray setup_spec from the currently running Ray. + + This function works even when Ray is built from source with pip install -e. + """ + ray_source_python_path = _resolve_current_ray_path() + setup_py_path = os.path.join(ray_source_python_path, "setup.py") + return runpy.run_path(setup_py_path)["setup_spec"] + + +def _resolve_install_from_source_ray_dependencies(): + """Find the Ray dependencies when Ray is installed from source.""" + deps = ( + _get_ray_setup_spec().install_requires + _get_ray_setup_spec().extras["default"] + ) + # Remove duplicates + return list(set(deps)) + + +def _inject_ray_to_conda_site( + conda_path, logger: Optional[logging.Logger] = default_logger +): + """Write the current Ray site package directory to a new site""" + if _WIN32: + python_binary = os.path.join(conda_path, "python") + else: + python_binary = os.path.join(conda_path, "bin/python") + site_packages_path = ( + subprocess.check_output( + [ + python_binary, + "-c", + "import sysconfig; print(sysconfig.get_paths()['purelib'])", + ] + ) + .decode() + .strip() + ) + + ray_path = _resolve_current_ray_path() + logger.warning( + f"Injecting {ray_path} to environment site-packages {site_packages_path} " + "because _inject_current_ray flag is on." + ) + + maybe_ray_dir = os.path.join(site_packages_path, "ray") + if os.path.isdir(maybe_ray_dir): + logger.warning(f"Replacing existing ray installation with {ray_path}") + shutil.rmtree(maybe_ray_dir) + + # See usage of *.pth file at + # https://docs.python.org/3/library/site.html + with open(os.path.join(site_packages_path, "ray_shared.pth"), "w") as f: + f.write(ray_path) + + +def _current_py_version(): + return ".".join(map(str, sys.version_info[:3])) # like 3.6.10 + + +def _is_m1_mac(): + return sys.platform == "darwin" and platform.machine() == "arm64" + + +def current_ray_pip_specifier( + logger: Optional[logging.Logger] = default_logger, +) -> Optional[str]: + """The pip requirement specifier for the running version of Ray. + + Returns: + A string which can be passed to `pip install` to install the + currently running Ray version, or None if running on a version + built from source locally (likely if you are developing Ray). + + Examples: + Returns "https://s3-us-west-2.amazonaws.com/ray-wheels/[..].whl" + if running a stable release, a nightly or a specific commit + """ + if os.environ.get("RAY_CI_POST_WHEEL_TESTS"): + # Running in Buildkite CI after the wheel has been built. + # Wheels are at in the ray/.whl directory, but use relative path to + # allow for testing locally if needed. + return os.path.join( + Path(ray.__file__).resolve().parents[2], ".whl", get_wheel_filename() + ) + elif ray.__commit__ == "{{RAY_COMMIT_SHA}}": + # Running on a version built from source locally. + if os.environ.get("RAY_RUNTIME_ENV_LOCAL_DEV_MODE") != "1": + logger.warning( + "Current Ray version could not be detected, most likely " + "because you have manually built Ray from source. To use " + "runtime_env in this case, set the environment variable " + "RAY_RUNTIME_ENV_LOCAL_DEV_MODE=1." + ) + return None + elif "dev" in ray.__version__: + # Running on a nightly wheel. + if _is_m1_mac(): + raise ValueError("Nightly wheels are not available for M1 Macs.") + return get_master_wheel_url() + else: + if _is_m1_mac(): + # M1 Mac release wheels are currently not uploaded to AWS S3; they + # are only available on PyPI. So unfortunately, this codepath is + # not end-to-end testable prior to the release going live on PyPI. + return f"ray=={ray.__version__}" + else: + return get_release_wheel_url() + + +def inject_dependencies( + conda_dict: Dict[Any, Any], + py_version: str, + pip_dependencies: Optional[List[str]] = None, +) -> Dict[Any, Any]: + """Add Ray, Python and (optionally) extra pip dependencies to a conda dict. + + Args: + conda_dict: A dict representing the JSON-serialized conda + environment YAML file. This dict will be modified and returned. + py_version: A string representing a Python version to inject + into the conda dependencies, e.g. "3.7.7" + pip_dependencies (List[str]): A list of pip dependencies that + will be prepended to the list of pip dependencies in + the conda dict. If the conda dict does not already have a "pip" + field, one will be created. + Returns: + The modified dict. (Note: the input argument conda_dict is modified + and returned.) + """ + if pip_dependencies is None: + pip_dependencies = [] + if conda_dict.get("dependencies") is None: + conda_dict["dependencies"] = [] + + # Inject Python dependency. + deps = conda_dict["dependencies"] + + # Add current python dependency. If the user has already included a + # python version dependency, conda will raise a readable error if the two + # are incompatible, e.g: + # ResolvePackageNotFound: - python[version='3.5.*,>=3.6'] + deps.append(f"python={py_version}") + + if "pip" not in deps: + deps.append("pip") + + # Insert pip dependencies. + found_pip_dict = False + for dep in deps: + if isinstance(dep, dict) and dep.get("pip") and isinstance(dep["pip"], list): + dep["pip"] = pip_dependencies + dep["pip"] + found_pip_dict = True + break + if not found_pip_dict: + deps.append({"pip": pip_dependencies}) + + return conda_dict + + +def _get_conda_env_hash(conda_dict: Dict) -> str: + # Set `sort_keys=True` so that different orderings yield the same hash. + serialized_conda_spec = json.dumps(conda_dict, sort_keys=True) + hash = hashlib.sha1(serialized_conda_spec.encode("utf-8")).hexdigest() + return hash + + +def get_uri(runtime_env: Dict) -> Optional[str]: + """Return `"conda://"`, or None if no GC required.""" + conda = runtime_env.get("conda") + if conda is not None: + if isinstance(conda, str): + # User-preinstalled conda env. We don't garbage collect these, so + # we don't track them with URIs. + uri = None + elif isinstance(conda, dict): + uri = f"conda://{_get_conda_env_hash(conda_dict=conda)}" + else: + raise TypeError( + "conda field received by RuntimeEnvAgent must be " + f"str or dict, not {type(conda).__name__}." + ) + else: + uri = None + return uri + + +def _get_conda_dict_with_ray_inserted( + runtime_env: "RuntimeEnv", # noqa: F821 + logger: Optional[logging.Logger] = default_logger, +) -> Dict[str, Any]: + """Returns the conda spec with the Ray and `python` dependency inserted.""" + conda_dict = json.loads(runtime_env.conda_config()) + assert conda_dict is not None + + ray_pip = current_ray_pip_specifier(logger=logger) + if ray_pip: + extra_pip_dependencies = [ray_pip, "ray[default]"] + elif runtime_env.get_extension("_inject_current_ray"): + extra_pip_dependencies = _resolve_install_from_source_ray_dependencies() + else: + extra_pip_dependencies = [] + conda_dict = inject_dependencies( + conda_dict, _current_py_version(), extra_pip_dependencies + ) + return conda_dict + + +class CondaPlugin(RuntimeEnvPlugin): + + name = "conda" + + def __init__(self, resources_dir: str): + self._resources_dir = os.path.join(resources_dir, "conda") + try_to_create_directory(self._resources_dir) + + # It is not safe for multiple processes to install conda envs + # concurrently, even if the envs are different, so use a global + # lock for all conda installs and deletions. + # See https://github.com/ray-project/ray/issues/17086 + self._installs_and_deletions_file_lock = os.path.join( + self._resources_dir, "ray-conda-installs-and-deletions.lock" + ) + # A set of named conda environments (instead of yaml or dict) + # that are validated to exist. + # NOTE: It has to be only used within the same thread, which + # is an event loop. + # Also, we don't need to GC this field because it is pretty small. + self._validated_named_conda_env = set() + + def _get_path_from_hash(self, hash: str) -> str: + """Generate a path from the hash of a conda or pip spec. + + The output path also functions as the name of the conda environment + when using the `--prefix` option to `conda create` and `conda remove`. + + Example output: + /tmp/ray/session_2021-11-03_16-33-59_356303_41018/runtime_resources + /conda/ray-9a7972c3a75f55e976e620484f58410c920db091 + """ + return os.path.join(self._resources_dir, hash) + + def get_uris(self, runtime_env: "RuntimeEnv") -> List[str]: # noqa: F821 + """Return the conda URI from the RuntimeEnv if it exists, else return [].""" + conda_uri = runtime_env.conda_uri() + if conda_uri: + return [conda_uri] + return [] + + def delete_uri( + self, uri: str, logger: Optional[logging.Logger] = default_logger + ) -> int: + """Delete URI and return the number of bytes deleted.""" + logger.info(f"Got request to delete URI {uri}") + protocol, hash = parse_uri(uri) + if protocol != Protocol.CONDA: + raise ValueError( + "CondaPlugin can only delete URIs with protocol " + f"conda. Received protocol {protocol}, URI {uri}" + ) + + conda_env_path = self._get_path_from_hash(hash) + local_dir_size = get_directory_size_bytes(conda_env_path) + + with FileLock(self._installs_and_deletions_file_lock): + successful = delete_conda_env(prefix=conda_env_path, logger=logger) + if not successful: + logger.warning(f"Error when deleting conda env {conda_env_path}. ") + return 0 + + return local_dir_size + + async def create( + self, + uri: Optional[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: logging.Logger = default_logger, + ) -> int: + if not runtime_env.has_conda(): + return 0 + + def _create(): + result = parse_and_validate_conda(runtime_env.get("conda")) + + if isinstance(result, str): + # The conda env name is given. + # In this case, we only verify if the given + # conda env exists. + + # If the env is already validated, do nothing. + if result in self._validated_named_conda_env: + return 0 + + conda_info = get_conda_info_json() + envs = get_conda_envs(conda_info) + + # We accept `result` as a conda name or full path. + if not any(result == env[0] or result == env[1] for env in envs): + raise ValueError( + f"The given conda environment '{result}' " + f"from the runtime env {runtime_env} doesn't " + "exist from the output of `conda info --json`. " + "You can only specify an env that already exists. " + f"Please make sure to create an env {result} " + ) + self._validated_named_conda_env.add(result) + return 0 + + logger.debug( + "Setting up conda for runtime_env: " f"{runtime_env.serialize()}" + ) + protocol, hash = parse_uri(uri) + conda_env_name = self._get_path_from_hash(hash) + + conda_dict = _get_conda_dict_with_ray_inserted(runtime_env, logger=logger) + + logger.info(f"Setting up conda environment with {runtime_env}") + with FileLock(self._installs_and_deletions_file_lock): + try: + conda_yaml_file = os.path.join( + self._resources_dir, "environment.yml" + ) + with open(conda_yaml_file, "w") as file: + yaml.dump(conda_dict, file) + create_conda_env_if_needed( + conda_yaml_file, prefix=conda_env_name, logger=logger + ) + finally: + os.remove(conda_yaml_file) + + if runtime_env.get_extension("_inject_current_ray"): + _inject_ray_to_conda_site(conda_path=conda_env_name, logger=logger) + logger.info(f"Finished creating conda environment at {conda_env_name}") + return get_directory_size_bytes(conda_env_name) + + loop = get_or_create_event_loop() + return await loop.run_in_executor(None, _create) + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + if not runtime_env.has_conda(): + return + + if runtime_env.conda_env_name(): + conda_env_name = runtime_env.conda_env_name() + else: + protocol, hash = parse_uri(runtime_env.conda_uri()) + conda_env_name = self._get_path_from_hash(hash) + context.py_executable = "python" + context.command_prefix += get_conda_activate_commands(conda_env_name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/conda_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/conda_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..eb2f67cabbe370b09d897a9303ac6cf719f28a37 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/conda_utils.py @@ -0,0 +1,279 @@ +import hashlib +import json +import logging +import os +import shutil +import subprocess +from typing import List, Optional, Tuple, Union + +"""Utilities for conda. Adapted from https://github.com/mlflow/mlflow.""" + +# Name of environment variable indicating a path to a conda installation. Ray +# will default to running "conda" if unset. +RAY_CONDA_HOME = "RAY_CONDA_HOME" + +_WIN32 = os.name == "nt" + + +def get_conda_activate_commands(conda_env_name: str) -> List[str]: + """ + Get a list of commands to run to silently activate the given conda env. + """ + # Checking for newer conda versions + if not _WIN32 and ("CONDA_EXE" in os.environ or RAY_CONDA_HOME in os.environ): + conda_path = get_conda_bin_executable("conda") + activate_conda_env = [ + ".", + f"{os.path.dirname(conda_path)}/../etc/profile.d/conda.sh", + "&&", + ] + activate_conda_env += ["conda", "activate", conda_env_name] + + else: + activate_path = get_conda_bin_executable("activate") + if not _WIN32: + # Use bash command syntax + activate_conda_env = ["source", activate_path, conda_env_name] + else: + conda_path = get_conda_bin_executable("conda") + activate_conda_env = [conda_path, "activate", conda_env_name] + return activate_conda_env + ["1>&2", "&&"] + + +def get_conda_bin_executable(executable_name: str) -> str: + """ + Return path to the specified executable, assumed to be discoverable within + a conda installation. + + The conda home directory (expected to contain a 'bin' subdirectory on + linux) is configurable via the ``RAY_CONDA_HOME`` environment variable. If + ``RAY_CONDA_HOME`` is unspecified, try the ``CONDA_EXE`` environment + variable set by activating conda. If neither is specified, this method + returns `executable_name`. + """ + conda_home = os.environ.get(RAY_CONDA_HOME) + if conda_home: + if _WIN32: + candidate = os.path.join(conda_home, "%s.exe" % executable_name) + if os.path.exists(candidate): + return candidate + candidate = os.path.join(conda_home, "%s.bat" % executable_name) + if os.path.exists(candidate): + return candidate + else: + return os.path.join(conda_home, "bin/%s" % executable_name) + else: + conda_home = "." + # Use CONDA_EXE as per https://github.com/conda/conda/issues/7126 + if "CONDA_EXE" in os.environ: + conda_bin_dir = os.path.dirname(os.environ["CONDA_EXE"]) + if _WIN32: + candidate = os.path.join(conda_home, "%s.exe" % executable_name) + if os.path.exists(candidate): + return candidate + candidate = os.path.join(conda_home, "%s.bat" % executable_name) + if os.path.exists(candidate): + return candidate + else: + return os.path.join(conda_bin_dir, executable_name) + if _WIN32: + return executable_name + ".bat" + return executable_name + + +def _get_conda_env_name(conda_env_path: str) -> str: + conda_env_contents = open(conda_env_path).read() + return "ray-%s" % hashlib.sha1(conda_env_contents.encode("utf-8")).hexdigest() + + +def create_conda_env_if_needed( + conda_yaml_file: str, prefix: str, logger: Optional[logging.Logger] = None +) -> None: + """ + Given a conda YAML, creates a conda environment containing the required + dependencies if such a conda environment doesn't already exist. + Args: + conda_yaml_file: The path to a conda `environment.yml` file. + prefix: Directory to install the environment into via + the `--prefix` option to conda create. This also becomes the name + of the conda env; i.e. it can be passed into `conda activate` and + `conda remove` + """ + if logger is None: + logger = logging.getLogger(__name__) + + conda_path = get_conda_bin_executable("conda") + try: + exec_cmd([conda_path, "--help"], throw_on_error=False) + except (EnvironmentError, FileNotFoundError): + raise ValueError( + f"Could not find Conda executable at '{conda_path}'. " + "Ensure Conda is installed as per the instructions at " + "https://conda.io/projects/conda/en/latest/" + "user-guide/install/index.html. " + "You can also configure Ray to look for a specific " + f"Conda executable by setting the {RAY_CONDA_HOME} " + "environment variable to the path of the Conda executable." + ) + + _, stdout, _ = exec_cmd([conda_path, "env", "list", "--json"]) + envs = json.loads(stdout[stdout.index("{") :])["envs"] + + if prefix in envs: + logger.info(f"Conda environment {prefix} already exists.") + return + + create_cmd = [ + conda_path, + "env", + "create", + "--file", + conda_yaml_file, + "--prefix", + prefix, + ] + + logger.info(f"Creating conda environment {prefix}") + exit_code, output = exec_cmd_stream_to_logger(create_cmd, logger) + if exit_code != 0: + if os.path.exists(prefix): + shutil.rmtree(prefix) + raise RuntimeError( + f"Failed to install conda environment {prefix}:\nOutput:\n{output}" + ) + + +def delete_conda_env(prefix: str, logger: Optional[logging.Logger] = None) -> bool: + if logger is None: + logger = logging.getLogger(__name__) + + logger.info(f"Deleting conda environment {prefix}") + + conda_path = get_conda_bin_executable("conda") + delete_cmd = [conda_path, "remove", "-p", prefix, "--all", "-y"] + exit_code, output = exec_cmd_stream_to_logger(delete_cmd, logger) + + if exit_code != 0: + logger.debug(f"Failed to delete conda environment {prefix}:\n{output}") + return False + + return True + + +def get_conda_env_list() -> list: + """ + Get conda env list in full paths. + """ + conda_path = get_conda_bin_executable("conda") + try: + exec_cmd([conda_path, "--help"], throw_on_error=False) + except EnvironmentError: + raise ValueError(f"Could not find Conda executable at {conda_path}.") + _, stdout, _ = exec_cmd([conda_path, "env", "list", "--json"]) + envs = json.loads(stdout)["envs"] + return envs + + +def get_conda_info_json() -> dict: + """ + Get `conda info --json` output. + + Returns dict of conda info. See [1] for more details. We mostly care about these + keys: + + - `conda_prefix`: str The path to the conda installation. + - `envs`: List[str] absolute paths to conda environments. + + [1] https://github.com/conda/conda/blob/main/conda/cli/main_info.py + """ + conda_path = get_conda_bin_executable("conda") + try: + exec_cmd([conda_path, "--help"], throw_on_error=False) + except EnvironmentError: + raise ValueError(f"Could not find Conda executable at {conda_path}.") + _, stdout, _ = exec_cmd([conda_path, "info", "--json"]) + return json.loads(stdout) + + +def get_conda_envs(conda_info: dict) -> List[Tuple[str, str]]: + """ + Gets the conda environments, as a list of (name, path) tuples. + """ + prefix = conda_info["conda_prefix"] + ret = [] + for env in conda_info["envs"]: + if env == prefix: + ret.append(("base", env)) + else: + ret.append((os.path.basename(env), env)) + return ret + + +class ShellCommandException(Exception): + pass + + +def exec_cmd( + cmd: List[str], throw_on_error: bool = True, logger: Optional[logging.Logger] = None +) -> Union[int, Tuple[int, str, str]]: + """ + Runs a command as a child process. + + A convenience wrapper for running a command from a Python script. + + Note on the return value: A tuple of the exit code, + standard output and standard error is returned. + + Args: + cmd: the command to run, as a list of strings + throw_on_error: if true, raises an Exception if the exit code of the + program is nonzero + """ + child = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stdin=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + ) + (stdout, stderr) = child.communicate() + exit_code = child.wait() + if throw_on_error and exit_code != 0: + raise ShellCommandException( + "Non-zero exit code: %s\n\nSTDOUT:\n%s\n\nSTDERR:%s" + % (exit_code, stdout, stderr) + ) + return exit_code, stdout, stderr + + +def exec_cmd_stream_to_logger( + cmd: List[str], logger: logging.Logger, n_lines: int = 50, **kwargs +) -> Tuple[int, str]: + """Runs a command as a child process, streaming output to the logger. + + The last n_lines lines of output are also returned (stdout and stderr). + """ + if "env" in kwargs and _WIN32 and "PATH" not in [x.upper() for x in kwargs.keys]: + raise ValueError("On windows, Popen requires 'PATH' in 'env'") + child = subprocess.Popen( + cmd, + universal_newlines=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + **kwargs, + ) + last_n_lines = [] + with child.stdout: + for line in iter(child.stdout.readline, b""): + exit_code = child.poll() + if exit_code is not None: + break + line = line.strip() + if not line: + continue + last_n_lines.append(line.strip()) + last_n_lines = last_n_lines[-n_lines:] + logger.info(line.strip()) + + exit_code = child.wait() + return exit_code, "\n".join(last_n_lines) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..3c6096b5993ef73836771ade7966947681bbab89 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/constants.py @@ -0,0 +1,28 @@ +# Env var set by job manager to pass runtime env and metadata to subprocess +RAY_JOB_CONFIG_JSON_ENV_VAR = "RAY_JOB_CONFIG_JSON_ENV_VAR" + +# The plugin config which should be loaded when ray cluster starts. +# It is a json formatted config, +# e.g. [{"class": "xxx.xxx.xxx_plugin", "priority": 10}]. +RAY_RUNTIME_ENV_PLUGINS_ENV_VAR = "RAY_RUNTIME_ENV_PLUGINS" + +# The field name of plugin class in the plugin config. +RAY_RUNTIME_ENV_CLASS_FIELD_NAME = "class" + +# The field name of priority in the plugin config. +RAY_RUNTIME_ENV_PRIORITY_FIELD_NAME = "priority" + +# The default priority of runtime env plugin. +RAY_RUNTIME_ENV_PLUGIN_DEFAULT_PRIORITY = 10 + +# The minimum priority of runtime env plugin. +RAY_RUNTIME_ENV_PLUGIN_MIN_PRIORITY = 0 + +# The maximum priority of runtime env plugin. +RAY_RUNTIME_ENV_PLUGIN_MAX_PRIORITY = 100 + +# The schema files or directories of plugins which should be loaded in workers. +RAY_RUNTIME_ENV_PLUGIN_SCHEMAS_ENV_VAR = "RAY_RUNTIME_ENV_PLUGIN_SCHEMAS" + +# The file suffix of runtime env plugin schemas. +RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX = ".json" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/context.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/context.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc58e28625d5a1e73bbbd62052e9fa92fbabecb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/context.py @@ -0,0 +1,108 @@ +import json +import logging +import os +import shlex +import subprocess +import sys +from typing import Dict, List, Optional + +from ray._private.services import get_ray_jars_dir +from ray._private.utils import update_envs +from ray.core.generated.common_pb2 import Language +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class RuntimeEnvContext: + """A context used to describe the created runtime env.""" + + def __init__( + self, + command_prefix: List[str] = None, + env_vars: Dict[str, str] = None, + py_executable: Optional[str] = None, + override_worker_entrypoint: Optional[str] = None, + java_jars: List[str] = None, + ): + self.command_prefix = command_prefix or [] + self.env_vars = env_vars or {} + self.py_executable = py_executable or sys.executable + self.override_worker_entrypoint: Optional[str] = override_worker_entrypoint + self.java_jars = java_jars or [] + + def serialize(self) -> str: + return json.dumps(self.__dict__) + + @staticmethod + def deserialize(json_string): + return RuntimeEnvContext(**json.loads(json_string)) + + def exec_worker(self, passthrough_args: List[str], language: Language): + update_envs(self.env_vars) + + if language == Language.PYTHON and sys.platform == "win32": + executable = [self.py_executable] + elif language == Language.PYTHON: + executable = ["exec", self.py_executable] + elif language == Language.JAVA: + executable = ["java"] + ray_jars = os.path.join(get_ray_jars_dir(), "*") + + local_java_jars = [] + for java_jar in self.java_jars: + local_java_jars.append(f"{java_jar}/*") + local_java_jars.append(java_jar) + + class_path_args = ["-cp", ray_jars + ":" + str(":".join(local_java_jars))] + passthrough_args = class_path_args + passthrough_args + elif sys.platform == "win32": + executable = [] + else: + executable = ["exec"] + + # By default, raylet uses the path to default_worker.py on host. + # However, the path to default_worker.py inside the container + # can be different. We need the user to specify the path to + # default_worker.py inside the container. + if self.override_worker_entrypoint: + logger.debug( + f"Changing the worker entrypoint from {passthrough_args[0]} to " + f"{self.override_worker_entrypoint}." + ) + passthrough_args[0] = self.override_worker_entrypoint + + if sys.platform == "win32": + + def quote(s): + s = s.replace("&", "%26") + return s + + passthrough_args = [quote(s) for s in passthrough_args] + + cmd = [*self.command_prefix, *executable, *passthrough_args] + logger.debug(f"Exec'ing worker with command: {cmd}") + subprocess.Popen(cmd, shell=True).wait() + else: + # We use shlex to do the necessary shell escape + # of special characters in passthrough_args. + passthrough_args = [shlex.quote(s) for s in passthrough_args] + cmd = [*self.command_prefix, *executable, *passthrough_args] + # TODO(SongGuyang): We add this env to command for macOS because it doesn't + # work for the C++ process of `os.execvp`. We should find a better way to + # fix it. + MACOS_LIBRARY_PATH_ENV_NAME = "DYLD_LIBRARY_PATH" + if MACOS_LIBRARY_PATH_ENV_NAME in os.environ: + cmd.insert( + 0, + f"{MACOS_LIBRARY_PATH_ENV_NAME}=" + f"{os.environ[MACOS_LIBRARY_PATH_ENV_NAME]}", + ) + logger.debug(f"Exec'ing worker with command: {cmd}") + # PyCharm will monkey patch the os.execvp at + # .pycharm_helpers/pydev/_pydev_bundle/pydev_monkey.py + # The monkey patched os.execvp function has a different + # signature. So, we use os.execvp("executable", args=[]) + # instead of os.execvp(file="executable", args=[]) + os.execvp("bash", args=["bash", "-c", " ".join(cmd)]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/default_impl.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/default_impl.py new file mode 100644 index 0000000000000000000000000000000000000000..331dc7fce01e2b096e4db2cf0d4cc32bd99301f4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/default_impl.py @@ -0,0 +1,11 @@ +from ray._private.runtime_env.image_uri import ImageURIPlugin + + +def get_image_uri_plugin_cls(): + return ImageURIPlugin + + +def get_protocols_provider(): + from ray._private.runtime_env.protocol import ProtocolsProvider + + return ProtocolsProvider diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/dependency_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/dependency_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..aff3dabb28f7d553ee4e7bc5087d13ce49ace453 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/dependency_utils.py @@ -0,0 +1,114 @@ +"""Util functions to manage dependency requirements.""" + +import logging +import os +import tempfile +from contextlib import asynccontextmanager +from typing import List, Optional, Tuple + +from ray._private.runtime_env import virtualenv_utils +from ray._private.runtime_env.utils import check_output_cmd + +INTERNAL_PIP_FILENAME = "ray_runtime_env_internal_pip_requirements.txt" +MAX_INTERNAL_PIP_FILENAME_TRIES = 100 + + +def gen_requirements_txt(requirements_file: str, pip_packages: List[str]): + """Dump [pip_packages] to the given [requirements_file] for later env setup.""" + with open(requirements_file, "w") as file: + for line in pip_packages: + file.write(line + "\n") + + +@asynccontextmanager +async def check_ray(python: str, cwd: str, logger: logging.Logger): + """A context manager to check ray is not overwritten. + + Currently, we only check ray version and path. It works for virtualenv, + - ray is in Python's site-packages. + - ray is overwritten during yield. + - ray is in virtualenv's site-packages. + """ + + async def _get_ray_version_and_path() -> Tuple[str, str]: + with tempfile.TemporaryDirectory( + prefix="check_ray_version_tempfile" + ) as tmp_dir: + ray_version_path = os.path.join(tmp_dir, "ray_version.txt") + check_ray_cmd = [ + python, + "-c", + """ +import ray +with open(r"{ray_version_path}", "wt") as f: + f.write(ray.__version__) + f.write(" ") + f.write(ray.__path__[0]) + """.format( + ray_version_path=ray_version_path + ), + ] + if virtualenv_utils._WIN32: + env = os.environ.copy() + else: + env = {} + output = await check_output_cmd( + check_ray_cmd, logger=logger, cwd=cwd, env=env + ) + logger.info(f"try to write ray version information in: {ray_version_path}") + with open(ray_version_path, "rt") as f: + output = f.read() + # print after import ray may have  endings, so we strip them by *_ + ray_version, ray_path, *_ = [s.strip() for s in output.split()] + return ray_version, ray_path + + version, path = await _get_ray_version_and_path() + yield + actual_version, actual_path = await _get_ray_version_and_path() + if actual_version != version or actual_path != path: + raise RuntimeError( + "Changing the ray version is not allowed: \n" + f" current version: {actual_version}, " + f"current path: {actual_path}\n" + f" expect version: {version}, " + f"expect path: {path}\n" + "Please ensure the dependencies in the runtime_env pip field " + "do not install a different version of Ray." + ) + + +def get_requirements_file(target_dir: str, pip_list: Optional[List[str]]) -> str: + """Returns the path to the requirements file to use for this runtime env. + + If pip_list is not None, we will check if the internal pip filename is in any of + the entries of pip_list. If so, we will append numbers to the end of the + filename until we find one that doesn't conflict. This prevents infinite + recursion if the user specifies the internal pip filename in their pip list. + + Args: + target_dir: The directory to store the requirements file in. + pip_list: A list of pip requirements specified by the user. + + Returns: + The path to the requirements file to use for this runtime env. + """ + + def filename_in_pip_list(filename: str) -> bool: + for pip_entry in pip_list: + if filename in pip_entry: + return True + return False + + filename = INTERNAL_PIP_FILENAME + if pip_list is not None: + i = 1 + while filename_in_pip_list(filename) and i < MAX_INTERNAL_PIP_FILENAME_TRIES: + filename = f"{INTERNAL_PIP_FILENAME}.{i}" + i += 1 + if i == MAX_INTERNAL_PIP_FILENAME_TRIES: + raise RuntimeError( + "Could not find a valid filename for the internal " + "pip requirements file. Please specify a different " + "pip list in your runtime env." + ) + return os.path.join(target_dir, filename) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/image_uri.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/image_uri.py new file mode 100644 index 0000000000000000000000000000000000000000..1d2b39907271df7143cc9fd95795add64a1318a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/image_uri.py @@ -0,0 +1,195 @@ +import logging +import os +from typing import List, Optional + +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray._private.runtime_env.utils import check_output_cmd + +default_logger = logging.getLogger(__name__) + + +async def _create_impl(image_uri: str, logger: logging.Logger): + # Pull image if it doesn't exist + # Also get path to `default_worker.py` inside the image. + pull_image_cmd = [ + "podman", + "run", + "--rm", + image_uri, + "python", + "-c", + ( + "import ray._private.workers.default_worker as default_worker; " + "print(default_worker.__file__)" + ), + ] + logger.info("Pulling image %s", image_uri) + worker_path = await check_output_cmd(pull_image_cmd, logger=logger) + return worker_path.strip() + + +def _modify_context_impl( + image_uri: str, + worker_path: str, + run_options: Optional[List[str]], + context: RuntimeEnvContext, + logger: logging.Logger, + ray_tmp_dir: str, +): + context.override_worker_entrypoint = worker_path + + container_driver = "podman" + container_command = [ + container_driver, + "run", + "-v", + ray_tmp_dir + ":" + ray_tmp_dir, + "--cgroup-manager=cgroupfs", + "--network=host", + "--pid=host", + "--ipc=host", + # NOTE(zcin): Mounted volumes in rootless containers are + # owned by the user `root`. The user on host (which will + # usually be `ray` if this is being run in a ray docker + # image) who started the container is mapped using user + # namespaces to the user `root` in a rootless container. In + # order for the Ray Python worker to access the mounted ray + # tmp dir, we need to use keep-id mode which maps the user + # as itself (instead of as `root`) into the container. + # https://www.redhat.com/sysadmin/rootless-podman-user-namespace-modes + "--userns=keep-id", + ] + + # Environment variables to set in container + env_vars = dict() + + # Propagate all host environment variables that have the prefix "RAY_" + # This should include RAY_RAYLET_PID + for env_var_name, env_var_value in os.environ.items(): + if env_var_name.startswith("RAY_"): + env_vars[env_var_name] = env_var_value + + # Support for runtime_env['env_vars'] + env_vars.update(context.env_vars) + + # Set environment variables + for env_var_name, env_var_value in env_vars.items(): + container_command.append("--env") + container_command.append(f"{env_var_name}='{env_var_value}'") + + # The RAY_JOB_ID environment variable is needed for the default worker. + # It won't be set at the time setup() is called, but it will be set + # when worker command is executed, so we use RAY_JOB_ID=$RAY_JOB_ID + # for the container start command + container_command.append("--env") + container_command.append("RAY_JOB_ID=$RAY_JOB_ID") + + if run_options: + container_command.extend(run_options) + # TODO(chenk008): add resource limit + container_command.append("--entrypoint") + container_command.append("python") + container_command.append(image_uri) + + # Example: + # podman run -v /tmp/ray:/tmp/ray + # --cgroup-manager=cgroupfs --network=host --pid=host --ipc=host + # --userns=keep-id --env RAY_RAYLET_PID=23478 --env RAY_JOB_ID=$RAY_JOB_ID + # --entrypoint python rayproject/ray:nightly-py39 + container_command_str = " ".join(container_command) + logger.info(f"Starting worker in container with prefix {container_command_str}") + + context.py_executable = container_command_str + + +class ImageURIPlugin(RuntimeEnvPlugin): + """Starts worker in a container of a custom image.""" + + name = "image_uri" + + @staticmethod + def get_compatible_keys(): + return {"image_uri", "config", "env_vars"} + + def __init__(self, ray_tmp_dir: str): + self._ray_tmp_dir = ray_tmp_dir + + async def create( + self, + uri: Optional[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: logging.Logger, + ) -> float: + if not runtime_env.image_uri(): + return + + self.worker_path = await _create_impl(runtime_env.image_uri(), logger) + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + if not runtime_env.image_uri(): + return + + _modify_context_impl( + runtime_env.image_uri(), + self.worker_path, + [], + context, + logger, + self._ray_tmp_dir, + ) + + +class ContainerPlugin(RuntimeEnvPlugin): + """Starts worker in container.""" + + name = "container" + + def __init__(self, ray_tmp_dir: str): + self._ray_tmp_dir = ray_tmp_dir + + async def create( + self, + uri: Optional[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: logging.Logger, + ) -> float: + if not runtime_env.has_py_container() or not runtime_env.py_container_image(): + return + + self.worker_path = await _create_impl(runtime_env.py_container_image(), logger) + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + if not runtime_env.has_py_container() or not runtime_env.py_container_image(): + return + + if runtime_env.py_container_worker_path(): + logger.warning( + "You are using `container.worker_path`, but the path to " + "`default_worker.py` is now automatically detected from the image. " + "`container.worker_path` is deprecated and will be removed in future " + "versions." + ) + + _modify_context_impl( + runtime_env.py_container_image(), + runtime_env.py_container_worker_path() or self.worker_path, + runtime_env.py_container_run_options(), + context, + logger, + self._ray_tmp_dir, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/java_jars.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/java_jars.py new file mode 100644 index 0000000000000000000000000000000000000000..83044ba7054b8a53643d8794a62ed2b2ecf97e17 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/java_jars.py @@ -0,0 +1,104 @@ +import logging +import os +from typing import Dict, List, Optional + +from ray._common.utils import try_to_create_directory +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.packaging import ( + delete_package, + download_and_unpack_package, + get_local_dir_from_uri, + is_jar_uri, +) +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray._private.utils import get_directory_size_bytes +from ray._raylet import GcsClient +from ray.exceptions import RuntimeEnvSetupError + +default_logger = logging.getLogger(__name__) + + +class JavaJarsPlugin(RuntimeEnvPlugin): + + name = "java_jars" + + def __init__(self, resources_dir: str, gcs_client: GcsClient): + self._resources_dir = os.path.join(resources_dir, "java_jars_files") + self._gcs_client = gcs_client + try_to_create_directory(self._resources_dir) + + def _get_local_dir_from_uri(self, uri: str): + return get_local_dir_from_uri(uri, self._resources_dir) + + def delete_uri( + self, uri: str, logger: Optional[logging.Logger] = default_logger + ) -> int: + """Delete URI and return the number of bytes deleted.""" + local_dir = get_local_dir_from_uri(uri, self._resources_dir) + local_dir_size = get_directory_size_bytes(local_dir) + + deleted = delete_package(uri, self._resources_dir) + if not deleted: + logger.warning(f"Tried to delete nonexistent URI: {uri}.") + return 0 + + return local_dir_size + + def get_uris(self, runtime_env: dict) -> List[str]: + return runtime_env.java_jars() + + async def _download_jars( + self, uri: str, logger: Optional[logging.Logger] = default_logger + ): + """Download a jar URI.""" + try: + jar_file = await download_and_unpack_package( + uri, self._resources_dir, self._gcs_client, logger=logger + ) + except Exception as e: + raise RuntimeEnvSetupError( + "Failed to download jar file: {}".format(e) + ) from e + module_dir = self._get_local_dir_from_uri(uri) + logger.debug(f"Succeeded to download jar file {jar_file} .") + return module_dir + + async def create( + self, + uri: str, + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ) -> int: + if not uri: + return 0 + if is_jar_uri(uri): + module_dir = await self._download_jars(uri=uri, logger=logger) + else: + try: + module_dir = await download_and_unpack_package( + uri, self._resources_dir, self._gcs_client, logger=logger + ) + except Exception as e: + raise RuntimeEnvSetupError( + "Failed to download jar file: {}".format(e) + ) from e + + return get_directory_size_bytes(module_dir) + + def modify_context( + self, + uris: List[str], + runtime_env_dict: Dict, + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + for uri in uris: + module_dir = self._get_local_dir_from_uri(uri) + if not module_dir.exists(): + raise ValueError( + f"Local directory {module_dir} for URI {uri} does " + "not exist on the cluster. Something may have gone wrong while " + "downloading, unpacking or installing the java jar files." + ) + context.java_jars.append(str(module_dir)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/mpi.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/mpi.py new file mode 100644 index 0000000000000000000000000000000000000000..28b5813ade44d35b31779018c33d0ef26cbf1fef --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/mpi.py @@ -0,0 +1,119 @@ +import logging +import os +import subprocess +from typing import List, Optional + +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.plugin import RuntimeEnvPlugin + +default_logger = logging.getLogger(__name__) + + +def mpi_init(): + """Initialize the MPI cluster. When using MPI cluster, this must be called first.""" + + if hasattr(mpi_init, "inited"): + assert mpi_init.inited is True + return + + from mpi4py import MPI + + comm = MPI.COMM_WORLD + rank = comm.Get_rank() + if rank == 0: + from ray._private.accelerators import get_all_accelerator_managers + + device_vars = [ + m.get_visible_accelerator_ids_env_var() + for m in get_all_accelerator_managers() + ] + visible_devices = { + n: os.environ.get(n) for n in device_vars if os.environ.get(n) + } + comm.bcast(visible_devices) + with open(f"/tmp/{os.getpid()}.{rank}", "w") as f: + f.write(str(visible_devices)) + else: + visible_devices = comm.bcast(None) + os.environ.update(visible_devices) + mpi_init.inited = True + + +class MPIPlugin(RuntimeEnvPlugin): + """Plugin for enabling MPI cluster functionality in runtime environments. + + This plugin enables an MPI cluster to run on top of Ray. It handles the setup + and configuration of MPI processes for distributed computing tasks. + + To use this plugin, add "mpi" to the runtime environment configuration: + + Example: + @ray.remote( + runtime_env={ + "mpi": { + "args": ["-n", "4"], + "worker_entry": worker_entry, + } + } + ) + def calc_pi(): + ... + + Here worker_entry should be function for the MPI worker to run. + For example, it should be `'py_module.worker_func'`. The module should be able to + be imported in the runtime. + + In the mpi worker with rank==0, it'll be the normal ray function or actor. + For the worker with rank > 0, it'll just run `worker_func`. + + ray.runtime_env.mpi_init must be called in the ray actors/tasks before any MPI + communication. + """ + + priority = 90 + name = "mpi" + + def modify_context( + self, + uris: List[str], # noqa: ARG002 + runtime_env: "RuntimeEnv", # noqa: F821 ARG002 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, # noqa: ARG002 + ) -> None: + mpi_config = runtime_env.mpi() + if mpi_config is None: + return + try: + proc = subprocess.run( + ["mpirun", "--version"], capture_output=True, check=True + ) + except subprocess.CalledProcessError: + logger.exception( + "Failed to run mpi run. Please make sure mpi has been installed" + ) + # The worker will fail to run and exception will be thrown in runtime + # env agent. + raise + + logger.info(f"Running MPI plugin\n {proc.stdout.decode()}") + + # worker_entry should be a file either in the working dir + # or visible inside the cluster. + worker_entry = mpi_config.get("worker_entry") + + assert ( + worker_entry is not None + ), "`worker_entry` must be setup in the runtime env." + + cmds = ( + ["mpirun"] + + mpi_config.get("args", []) + + [ + context.py_executable, + "-m", + "ray._private.runtime_env.mpi_runner", + worker_entry, + ] + ) + # Construct the start cmd + context.py_executable = " ".join(cmds) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/mpi_runner.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/mpi_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..fc30fed36a78c25ff087806f7b52b666cb4ba209 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/mpi_runner.py @@ -0,0 +1,32 @@ +import argparse +import importlib +import sys + +from mpi4py import MPI + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Setup MPI worker") + parser.add_argument("worker_entry") + parser.add_argument("main_entry") + + args, remaining_args = parser.parse_known_args() + + comm = MPI.COMM_WORLD + + rank = comm.Get_rank() + + if rank == 0: + entry_file = args.main_entry + + sys.argv[1:] = remaining_args + spec = importlib.util.spec_from_file_location("__main__", entry_file) + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + else: + from ray.runtime_env import mpi_init + + mpi_init() + module, func = args.worker_entry.rsplit(".", 1) + m = importlib.import_module(module) + f = getattr(m, func) + f() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/nsight.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/nsight.py new file mode 100644 index 0000000000000000000000000000000000000000..bd1c44beabd7bf7383baeb3abdf80e79b2ef3df3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/nsight.py @@ -0,0 +1,149 @@ +import asyncio +import copy +import logging +import os +import subprocess +import sys +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +from ray._common.utils import ( + try_to_create_directory, +) +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray.exceptions import RuntimeEnvSetupError + +default_logger = logging.getLogger(__name__) + +# Nsight options used when runtime_env={"_nsight": "default"} +NSIGHT_DEFAULT_CONFIG = { + "t": "cuda,cudnn,cublas,nvtx", + "o": "'worker_process_%p'", + "stop-on-exit": "true", +} + + +def parse_nsight_config(nsight_config: Dict[str, str]) -> List[str]: + """ + Function to convert dictionary of nsight options into + nsight command line + + The function returns: + - List[str]: nsys profile cmd line split into list of str + """ + nsight_cmd = ["nsys", "profile"] + for option, option_val in nsight_config.items(): + # option standard based on + # https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + if len(option) > 1: + nsight_cmd.append(f"--{option}={option_val}") + else: + nsight_cmd += [f"-{option}", option_val] + return nsight_cmd + + +class NsightPlugin(RuntimeEnvPlugin): + name = "_nsight" + + def __init__(self, resources_dir: str): + self.nsight_cmd = [] + + # replace this with better way to get logs dir + session_dir, runtime_dir = os.path.split(resources_dir) + self._nsight_dir = Path(session_dir) / "logs" / "nsight" + try_to_create_directory(self._nsight_dir) + + async def _check_nsight_script( + self, nsight_config: Dict[str, str] + ) -> Tuple[bool, str]: + """ + Function to validate if nsight_config is a valid nsight profile options + Args: + nsight_config: dictionary mapping nsight option to it's value + Returns: + a tuple consists of a boolean indicating if the nsight_config + is valid option and an error message if the nsight_config is invalid + """ + + # use empty as nsight report test filename + nsight_config_copy = copy.deepcopy(nsight_config) + nsight_config_copy["o"] = str(Path(self._nsight_dir) / "empty") + nsight_cmd = parse_nsight_config(nsight_config_copy) + try: + nsight_cmd = nsight_cmd + [sys.executable, "-c", '""'] + process = await asyncio.create_subprocess_exec( + *nsight_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + error_msg = stderr.strip() if stderr.strip() != "" else stdout.strip() + + # cleanup test.nsys-rep file + clean_up_cmd = ["rm", f"{nsight_config_copy['o']}.nsys-rep"] + cleanup_process = await asyncio.create_subprocess_exec( + *clean_up_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + _, _ = await cleanup_process.communicate() + if process.returncode == 0: + return True, None + else: + return False, error_msg + except FileNotFoundError: + return False, ("nsight is not installed") + + async def create( + self, + uri: Optional[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: logging.Logger = default_logger, + ) -> int: + nsight_config = runtime_env.nsight() + if not nsight_config: + return 0 + + if nsight_config and sys.platform != "linux": + raise RuntimeEnvSetupError( + "Nsight CLI is only available in Linux.\n" + "More information can be found in " + "https://docs.nvidia.com/nsight-compute/NsightComputeCli/index.html" + ) + + if isinstance(nsight_config, str): + if nsight_config == "default": + nsight_config = NSIGHT_DEFAULT_CONFIG + else: + raise RuntimeEnvSetupError( + f"Unsupported nsight config: {nsight_config}. " + "The supported config is 'default' or " + "Dictionary of nsight options" + ) + + is_valid_nsight_cmd, error_msg = await self._check_nsight_script(nsight_config) + if not is_valid_nsight_cmd: + logger.warning(error_msg) + raise RuntimeEnvSetupError( + "nsight profile failed to run with the following " + f"error message:\n {error_msg}" + ) + # add set output path to logs dir + nsight_config["o"] = str( + Path(self._nsight_dir) / nsight_config.get("o", NSIGHT_DEFAULT_CONFIG["o"]) + ) + + self.nsight_cmd = parse_nsight_config(nsight_config) + return 0 + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + logger.info("Running nsight profiler") + context.py_executable = " ".join(self.nsight_cmd) + " python" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/packaging.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/packaging.py new file mode 100644 index 0000000000000000000000000000000000000000..d2366da4389e5c8c870c9edf2ecac3fad123c237 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/packaging.py @@ -0,0 +1,970 @@ +import asyncio +import hashlib +import logging +import os +import shutil +import time +from pathlib import Path +from tempfile import TemporaryDirectory +from typing import Callable, List, Optional, Tuple +from urllib.parse import urlparse +from zipfile import ZipFile + +from filelock import FileLock + +from ray._private.path_utils import is_path +from ray._private.ray_constants import ( + GRPC_CPP_MAX_MESSAGE_SIZE, + RAY_RUNTIME_ENV_IGNORE_GITIGNORE, + RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_DEFAULT, + RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_ENV_VAR, +) +from ray._private.runtime_env.conda_utils import exec_cmd_stream_to_logger +from ray._private.runtime_env.protocol import Protocol +from ray._private.thirdparty.pathspec import PathSpec +from ray._raylet import GcsClient +from ray.experimental.internal_kv import ( + _internal_kv_exists, + _internal_kv_put, + _pin_runtime_env_uri, +) +from ray.util.annotations import DeveloperAPI + +default_logger = logging.getLogger(__name__) + +# If an individual file is beyond this size, print a warning. +FILE_SIZE_WARNING = 10 * 1024 * 1024 # 10MiB +# The size is bounded by the max gRPC message size. +# Keep in sync with max_grpc_message_size in ray_config_def.h. +GCS_STORAGE_MAX_SIZE = int( + os.environ.get("RAY_max_grpc_message_size", GRPC_CPP_MAX_MESSAGE_SIZE) +) +RAY_PKG_PREFIX = "_ray_pkg_" + +RAY_RUNTIME_ENV_FAIL_UPLOAD_FOR_TESTING_ENV_VAR = ( + "RAY_RUNTIME_ENV_FAIL_UPLOAD_FOR_TESTING" +) +RAY_RUNTIME_ENV_FAIL_DOWNLOAD_FOR_TESTING_ENV_VAR = ( + "RAY_RUNTIME_ENV_FAIL_DOWNLOAD_FOR_TESTING" +) + +# The name of the hidden top-level directory that appears when files are +# zipped on MacOS. +MAC_OS_ZIP_HIDDEN_DIR_NAME = "__MACOSX" + + +def _mib_string(num_bytes: float) -> str: + size_mib = float(num_bytes / 1024**2) + return f"{size_mib:.2f}MiB" + + +class _AsyncFileLock: + """Asyncio version used to prevent blocking event loop.""" + + def __init__(self, lock_file: str): + self.file = FileLock(lock_file) + + async def __aenter__(self): + while True: + try: + self.file.acquire(timeout=0) + return + except TimeoutError: + await asyncio.sleep(0.1) + + async def __aexit__(self, exc_type, exc, tb): + self.file.release() + + +def _xor_bytes(left: bytes, right: bytes) -> bytes: + if left and right: + return bytes(a ^ b for (a, b) in zip(left, right)) + return left or right + + +def _dir_travel( + path: Path, + excludes: List[Callable], + handler: Callable, + logger: Optional[logging.Logger] = default_logger, +): + """Travels the path recursively, calling the handler on each subpath. + + Respects excludes, which will be called to check if this path is skipped. + """ + e = _get_gitignore(path) + + if e is not None: + excludes.append(e) + + skip = any(e(path) for e in excludes) + if not skip: + try: + handler(path) + except Exception as e: + logger.error(f"Issue with path: {path}") + raise e + if path.is_dir(): + for sub_path in path.iterdir(): + _dir_travel(sub_path, excludes, handler, logger=logger) + + if e is not None: + excludes.pop() + + +def _hash_file_content_or_directory_name( + filepath: Path, + relative_path: Path, + logger: Optional[logging.Logger] = default_logger, +) -> bytes: + """Helper function to create hash of a single file or directory. + + This function hashes the path of the file or directory, + and if it's a file, then it hashes its content too. + """ + + BUF_SIZE = 4096 * 1024 + + sha1 = hashlib.sha1() + sha1.update(str(filepath.relative_to(relative_path)).encode()) + if not filepath.is_dir(): + try: + f = filepath.open("rb") + except Exception as e: + logger.debug( + f"Skipping contents of file {filepath} when calculating package hash " + f"because the file couldn't be opened: {e}" + ) + else: + try: + data = f.read(BUF_SIZE) + while len(data) != 0: + sha1.update(data) + data = f.read(BUF_SIZE) + finally: + f.close() + + return sha1.digest() + + +def _hash_file( + filepath: Path, + relative_path: Path, + logger: Optional[logging.Logger] = default_logger, +) -> bytes: + """Helper function to create hash of a single file. + + It hashes the path of the file and its content to create a hash value. + """ + file_hash = _hash_file_content_or_directory_name( + filepath, relative_path, logger=logger + ) + return _xor_bytes(file_hash, b"0" * 8) + + +def _hash_directory( + root: Path, + relative_path: Path, + excludes: Optional[Callable], + logger: Optional[logging.Logger] = default_logger, +) -> bytes: + """Helper function to create hash of a directory. + + It'll go through all the files in the directory and xor + hash(file_name, file_content) to create a hash value. + """ + hash_val = b"0" * 8 + + def handler(path: Path): + file_hash = _hash_file_content_or_directory_name( + path, relative_path, logger=logger + ) + nonlocal hash_val + hash_val = _xor_bytes(hash_val, file_hash) + + excludes = [] if excludes is None else [excludes] + _dir_travel(root, excludes, handler, logger=logger) + return hash_val + + +def parse_path(pkg_path: str) -> None: + """Parse the path to check it is well-formed and exists.""" + path = Path(pkg_path) + try: + path.resolve(strict=True) + except OSError: + raise ValueError(f"{path} is not a valid path.") + + +def parse_uri(pkg_uri: str) -> Tuple[Protocol, str]: + """ + Parse package uri into protocol and package name based on its format. + Note that the output of this function is not for handling actual IO, it's + only for setting up local directory folders by using package name as path. + + >>> parse_uri("https://test.com/file.zip") + (, 'https_test_com_file.zip') + + >>> parse_uri("https://test.com/file.whl") + (, 'file.whl') + + """ + if is_path(pkg_uri): + raise ValueError(f"Expected URI but received path {pkg_uri}") + + uri = urlparse(pkg_uri) + try: + protocol = Protocol(uri.scheme) + except ValueError as e: + raise ValueError( + f'Invalid protocol for runtime_env URI "{pkg_uri}". ' + f"Supported protocols: {Protocol._member_names_}. Original error: {e}" + ) + + if protocol in Protocol.remote_protocols(): + if uri.path.endswith(".whl"): + # Don't modify the .whl filename. See + # https://peps.python.org/pep-0427/#file-name-convention + # for more information. + package_name = uri.path.split("/")[-1] + else: + package_name = f"{protocol.value}_{uri.netloc}{uri.path}" + + disallowed_chars = ["/", ":", "@", "+", " ", "(", ")"] + for disallowed_char in disallowed_chars: + package_name = package_name.replace(disallowed_char, "_") + + # Remove all periods except the last, which is part of the + # file extension + package_name = package_name.replace(".", "_", package_name.count(".") - 1) + else: + package_name = uri.netloc + return (protocol, package_name) + + +def is_zip_uri(uri: str) -> bool: + try: + protocol, path = parse_uri(uri) + except ValueError: + return False + + return Path(path).suffix == ".zip" + + +def is_whl_uri(uri: str) -> bool: + try: + _, path = parse_uri(uri) + except ValueError: + return False + + return Path(path).suffix == ".whl" + + +def is_jar_uri(uri: str) -> bool: + try: + _, path = parse_uri(uri) + except ValueError: + return False + + return Path(path).suffix == ".jar" + + +def _get_excludes(path: Path, excludes: List[str]) -> Callable: + path = path.absolute() + pathspec = PathSpec.from_lines("gitwildmatch", excludes) + + def match(p: Path): + path_str = str(p.absolute().relative_to(path)) + return pathspec.match_file(path_str) + + return match + + +def _get_gitignore(path: Path) -> Optional[Callable]: + """Returns a function that returns True if the path should be excluded. + + Returns None if there is no .gitignore file in the path, or if the + RAY_RUNTIME_ENV_IGNORE_GITIGNORE environment variable is set to 1. + + Args: + path: The path to the directory to check for a .gitignore file. + + Returns: + A function that returns True if the path should be excluded. + """ + ignore_gitignore = os.environ.get(RAY_RUNTIME_ENV_IGNORE_GITIGNORE, "0") == "1" + if ignore_gitignore: + return None + + path = path.absolute() + ignore_file = path / ".gitignore" + if ignore_file.is_file(): + with ignore_file.open("r") as f: + pathspec = PathSpec.from_lines("gitwildmatch", f.readlines()) + + def match(p: Path): + path_str = str(p.absolute().relative_to(path)) + return pathspec.match_file(path_str) + + return match + else: + return None + + +def pin_runtime_env_uri(uri: str, *, expiration_s: Optional[int] = None) -> None: + """Pin a reference to a runtime_env URI in the GCS on a timeout. + + This is used to avoid premature eviction in edge conditions for job + reference counting. See https://github.com/ray-project/ray/pull/24719. + + Packages are uploaded to GCS in order to be downloaded by a runtime env plugin + (e.g. working_dir, py_modules) after the job starts. + + This function adds a temporary reference to the package in the GCS to prevent + it from being deleted before the job starts. (See #23423 for the bug where + this happened.) + + If this reference didn't have an expiration, then if the script exited + (e.g. via Ctrl-C) before the job started, the reference would never be + removed, so the package would never be deleted. + """ + + if expiration_s is None: + expiration_s = int( + os.environ.get( + RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_ENV_VAR, + RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_DEFAULT, + ) + ) + elif not isinstance(expiration_s, int): + raise ValueError(f"expiration_s must be an int, got {type(expiration_s)}.") + + if expiration_s < 0: + raise ValueError(f"expiration_s must be >= 0, got {expiration_s}.") + elif expiration_s > 0: + _pin_runtime_env_uri(uri, expiration_s=expiration_s) + + +def _store_package_in_gcs( + pkg_uri: str, + data: bytes, + logger: Optional[logging.Logger] = default_logger, +) -> int: + """Stores package data in the Global Control Store (GCS). + + Args: + pkg_uri: The GCS key to store the data in. + data: The serialized package's bytes to store in the GCS. + logger (Optional[logging.Logger]): The logger used by this function. + + Return: + int: Size of data + + Raises: + RuntimeError: If the upload to the GCS fails. + ValueError: If the data's size exceeds GCS_STORAGE_MAX_SIZE. + """ + + file_size = len(data) + size_str = _mib_string(file_size) + if len(data) >= GCS_STORAGE_MAX_SIZE: + raise ValueError( + f"Package size ({size_str}) exceeds the maximum size of " + f"{_mib_string(GCS_STORAGE_MAX_SIZE)}. You can exclude large " + "files using the 'excludes' option to the runtime_env or provide " + "a remote URI of a zip file using protocols such as 's3://', " + "'https://' and so on, refer to " + "https://docs.ray.io/en/latest/ray-core/handling-dependencies.html#api-reference." # noqa + ) + + logger.info(f"Pushing file package '{pkg_uri}' ({size_str}) to Ray cluster...") + try: + if os.environ.get(RAY_RUNTIME_ENV_FAIL_UPLOAD_FOR_TESTING_ENV_VAR): + raise RuntimeError( + "Simulating failure to upload package for testing purposes." + ) + _internal_kv_put(pkg_uri, data) + except Exception as e: + raise RuntimeError( + "Failed to store package in the GCS.\n" + f" - GCS URI: {pkg_uri}\n" + f" - Package data ({size_str}): {data[:15]}...\n" + ) from e + logger.info(f"Successfully pushed file package '{pkg_uri}'.") + return len(data) + + +def _get_local_path(base_directory: str, pkg_uri: str) -> str: + _, pkg_name = parse_uri(pkg_uri) + return os.path.join(base_directory, pkg_name) + + +def _zip_files( + path_str: str, + excludes: List[str], + output_path: str, + include_parent_dir: bool = False, + logger: Optional[logging.Logger] = default_logger, +) -> None: + """Zip the target file or directory and write it to the output_path. + + path_str: The file or directory to zip. + excludes (List(str)): The directories or file to be excluded. + output_path: The output path for the zip file. + include_parent_dir: If true, includes the top-level directory as a + directory inside the zip file. + """ + pkg_file = Path(output_path).absolute() + with ZipFile(pkg_file, "w", strict_timestamps=False) as zip_handler: + # Put all files in the directory into the zip file. + file_path = Path(path_str).absolute() + dir_path = file_path + if file_path.is_file(): + dir_path = file_path.parent + + def handler(path: Path): + # Pack this path if it's an empty directory or it's a file. + if path.is_dir() and next(path.iterdir(), None) is None or path.is_file(): + file_size = path.stat().st_size + if file_size >= FILE_SIZE_WARNING: + logger.warning( + f"File {path} is very large " + f"({_mib_string(file_size)}). Consider adding this " + "file to the 'excludes' list to skip uploading it: " + "`ray.init(..., " + f"runtime_env={{'excludes': ['{path}']}})`" + ) + to_path = path.relative_to(dir_path) + if include_parent_dir: + to_path = dir_path.name / to_path + zip_handler.write(path, to_path) + + excludes = [_get_excludes(file_path, excludes)] + _dir_travel(file_path, excludes, handler, logger=logger) + + +def package_exists(pkg_uri: str) -> bool: + """Check whether the package with given URI exists or not. + + Args: + pkg_uri: The uri of the package + + Return: + True for package existing and False for not. + """ + protocol, pkg_name = parse_uri(pkg_uri) + if protocol == Protocol.GCS: + return _internal_kv_exists(pkg_uri) + else: + raise NotImplementedError(f"Protocol {protocol} is not supported") + + +def get_uri_for_package(package: Path) -> str: + """Get a content-addressable URI from a package's contents.""" + + if package.suffix == ".whl": + # Wheel file names include the Python package name, version + # and tags, so it is already effectively content-addressed. + return "{protocol}://{whl_filename}".format( + protocol=Protocol.GCS.value, whl_filename=package.name + ) + else: + hash_val = hashlib.sha1(package.read_bytes()).hexdigest() + return "{protocol}://{pkg_name}.zip".format( + protocol=Protocol.GCS.value, pkg_name=RAY_PKG_PREFIX + hash_val + ) + + +def get_uri_for_file(file: str) -> str: + """Get a content-addressable URI from a file's content. + + This function generates the name of the package by the file. + The final package name is _ray_pkg_.zip of this package, + where HASH_VAL is the hash value of the file. + For example: _ray_pkg_029f88d5ecc55e1e4d64fc6e388fd103.zip + + Examples: + + >>> get_uri_for_file("/my_file.py") # doctest: +SKIP + _ray_pkg_af2734982a741.zip + + Args: + file: The file. + + Returns: + URI (str) + + Raises: + ValueError: If the file doesn't exist. + """ + filepath = Path(file).absolute() + if not filepath.exists() or not filepath.is_file(): + raise ValueError(f"File {filepath} must be an existing file") + + hash_val = _hash_file(filepath, filepath.parent) + + return "{protocol}://{pkg_name}.zip".format( + protocol=Protocol.GCS.value, pkg_name=RAY_PKG_PREFIX + hash_val.hex() + ) + + +def get_uri_for_directory(directory: str, excludes: Optional[List[str]] = None) -> str: + """Get a content-addressable URI from a directory's contents. + + This function generates the name of the package by the directory. + It'll go through all the files in the directory and hash the contents + of the files to get the hash value of the package. + The final package name is _ray_pkg_.zip of this package. + For example: _ray_pkg_029f88d5ecc55e1e4d64fc6e388fd103.zip + + Examples: + + >>> get_uri_for_directory("/my_directory") # doctest: +SKIP + _ray_pkg_af2734982a741.zip + + Args: + directory: The directory. + excludes (list[str]): The dir or files that should be excluded. + + Returns: + URI (str) + + Raises: + ValueError: If the directory doesn't exist. + """ + if excludes is None: + excludes = [] + + directory = Path(directory).absolute() + if not directory.exists() or not directory.is_dir(): + raise ValueError(f"directory {directory} must be an existing directory") + + hash_val = _hash_directory(directory, directory, _get_excludes(directory, excludes)) + + return "{protocol}://{pkg_name}.zip".format( + protocol=Protocol.GCS.value, pkg_name=RAY_PKG_PREFIX + hash_val.hex() + ) + + +def upload_package_to_gcs(pkg_uri: str, pkg_bytes: bytes) -> None: + """Upload a local package to GCS. + + Args: + pkg_uri: The URI of the package, e.g. gcs://my_package.zip + pkg_bytes: The data to be uploaded. + + Raises: + RuntimeError: If the upload fails. + ValueError: If the pkg_uri is a remote path or if the data's + size exceeds GCS_STORAGE_MAX_SIZE. + NotImplementedError: If the protocol of the URI is not supported. + + """ + protocol, pkg_name = parse_uri(pkg_uri) + if protocol == Protocol.GCS: + _store_package_in_gcs(pkg_uri, pkg_bytes) + elif protocol in Protocol.remote_protocols(): + raise ValueError( + "upload_package_to_gcs should not be called with a remote path." + ) + else: + raise NotImplementedError(f"Protocol {protocol} is not supported") + + +def create_package( + module_path: str, + target_path: Path, + include_parent_dir: bool = False, + excludes: Optional[List[str]] = None, + logger: Optional[logging.Logger] = default_logger, +): + if excludes is None: + excludes = [] + + if logger is None: + logger = default_logger + + if not target_path.exists(): + logger.info(f"Creating a file package for local module '{module_path}'.") + _zip_files( + module_path, + excludes, + str(target_path), + include_parent_dir=include_parent_dir, + logger=logger, + ) + + +def upload_package_if_needed( + pkg_uri: str, + base_directory: str, + module_path: str, + include_parent_dir: bool = False, + excludes: Optional[List[str]] = None, + logger: Optional[logging.Logger] = default_logger, +) -> bool: + """Upload the contents of the directory under the given URI. + + This will first create a temporary zip file under the passed + base_directory. + + If the package already exists in storage, this is a no-op. + + Args: + pkg_uri: URI of the package to upload. + base_directory: Directory where package files are stored. + module_path: The module to be uploaded, either a single .py file or a directory. + include_parent_dir: If true, includes the top-level directory as a + directory inside the zip file. + excludes: List specifying files to exclude. + + Raises: + RuntimeError: If the upload fails. + ValueError: If the pkg_uri is a remote path or if the data's + size exceeds GCS_STORAGE_MAX_SIZE. + NotImplementedError: If the protocol of the URI is not supported. + """ + if excludes is None: + excludes = [] + + if logger is None: + logger = default_logger + + pin_runtime_env_uri(pkg_uri) + + if package_exists(pkg_uri): + return False + + package_file = Path(_get_local_path(base_directory, pkg_uri)) + # Make the temporary zip file name unique so that it doesn't conflict with + # concurrent upload_package_if_needed calls with the same pkg_uri. + # See https://github.com/ray-project/ray/issues/47471. + package_file = package_file.with_name( + f"{time.time_ns()}_{os.getpid()}_{package_file.name}" + ) + + create_package( + module_path, + package_file, + include_parent_dir=include_parent_dir, + excludes=excludes, + ) + package_file_bytes = package_file.read_bytes() + # Remove the local file to avoid accumulating temporary zip files. + package_file.unlink() + + upload_package_to_gcs(pkg_uri, package_file_bytes) + + return True + + +def get_local_dir_from_uri(uri: str, base_directory: str) -> Path: + """Return the local directory corresponding to this URI.""" + pkg_file = Path(_get_local_path(base_directory, uri)) + local_dir = pkg_file.with_suffix("") + return local_dir + + +@DeveloperAPI +async def download_and_unpack_package( + pkg_uri: str, + base_directory: str, + gcs_client: Optional[GcsClient] = None, + logger: Optional[logging.Logger] = default_logger, + overwrite: bool = False, +) -> str: + """Download the package corresponding to this URI and unpack it if zipped. + + Will be written to a file or directory named {base_directory}/{uri}. + Returns the path to this file or directory. + + Args: + pkg_uri: URI of the package to download. + base_directory: Directory to use as the parent directory of the target + directory for the unpacked files. + gcs_client: Client to use for downloading from the GCS. + logger: The logger to use. + overwrite: If True, overwrite the existing package. + + Returns: + Path to the local directory containing the unpacked package files. + + Raises: + IOError: If the download fails. + ImportError: If smart_open is not installed and a remote URI is used. + NotImplementedError: If the protocol of the URI is not supported. + ValueError: If the GCS client is not provided when downloading from GCS, + or if package URI is invalid. + + """ + pkg_file = Path(_get_local_path(base_directory, pkg_uri)) + if pkg_file.suffix == "": + raise ValueError( + f"Invalid package URI: {pkg_uri}." + "URI must have a file extension and the URI must be valid." + ) + + async with _AsyncFileLock(str(pkg_file) + ".lock"): + if logger is None: + logger = default_logger + + logger.debug(f"Fetching package for URI: {pkg_uri}") + + local_dir = get_local_dir_from_uri(pkg_uri, base_directory) + assert local_dir != pkg_file, "Invalid pkg_file!" + + download_package: bool = True + if local_dir.exists() and not overwrite: + download_package = False + assert local_dir.is_dir(), f"{local_dir} is not a directory" + elif local_dir.exists(): + logger.info(f"Removing {local_dir} with pkg_file {pkg_file}") + shutil.rmtree(local_dir) + + if download_package: + protocol, _ = parse_uri(pkg_uri) + logger.info( + f"Downloading package from {pkg_uri} to {pkg_file} " + f"with protocol {protocol}" + ) + if protocol == Protocol.GCS: + if gcs_client is None: + raise ValueError( + "GCS client must be provided to download from GCS." + ) + + # Download package from the GCS. + code = await gcs_client.async_internal_kv_get( + pkg_uri.encode(), namespace=None, timeout=None + ) + if os.environ.get(RAY_RUNTIME_ENV_FAIL_DOWNLOAD_FOR_TESTING_ENV_VAR): + code = None + if code is None: + raise IOError( + f"Failed to download runtime_env file package {pkg_uri} " + "from the GCS to the Ray worker node. The package may " + "have prematurely been deleted from the GCS due to a " + "long upload time or a problem with Ray. Try setting the " + "environment variable " + f"{RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_ENV_VAR} " + " to a value larger than the upload time in seconds " + "(the default is " + f"{RAY_RUNTIME_ENV_URI_PIN_EXPIRATION_S_DEFAULT}). " + "If this fails, try re-running " + "after making any change to a file in the file package." + ) + code = code or b"" + pkg_file.write_bytes(code) + + if is_zip_uri(pkg_uri): + unzip_package( + package_path=pkg_file, + target_dir=local_dir, + remove_top_level_directory=False, + unlink_zip=True, + logger=logger, + ) + else: + return str(pkg_file) + elif protocol in Protocol.remote_protocols(): + protocol.download_remote_uri(source_uri=pkg_uri, dest_file=pkg_file) + + if pkg_file.suffix in [".zip", ".jar"]: + unzip_package( + package_path=pkg_file, + target_dir=local_dir, + remove_top_level_directory=True, + unlink_zip=True, + logger=logger, + ) + elif pkg_file.suffix == ".whl": + return str(pkg_file) + else: + raise NotImplementedError( + f"Package format {pkg_file.suffix} is ", + "not supported for remote protocols", + ) + else: + raise NotImplementedError(f"Protocol {protocol} is not supported") + + return str(local_dir) + + +def get_top_level_dir_from_compressed_package(package_path: str): + """ + If compressed package at package_path contains a single top-level + directory, returns the name of the top-level directory. Otherwise, + returns None. + + Ignores a second top-level directory if it is named __MACOSX. + """ + + package_zip = ZipFile(package_path, "r") + top_level_directory = None + + def is_top_level_file(file_name): + return "/" not in file_name + + def base_dir_name(file_name): + return file_name.split("/")[0] + + for file_name in package_zip.namelist(): + if top_level_directory is None: + # Cache the top_level_directory name when checking + # the first file in the zipped package + if is_top_level_file(file_name): + return None + else: + # Top-level directory, or non-top-level file or directory + dir_name = base_dir_name(file_name) + if dir_name == MAC_OS_ZIP_HIDDEN_DIR_NAME: + continue + top_level_directory = dir_name + else: + # Confirm that all other files + # belong to the same top_level_directory + if is_top_level_file(file_name) or base_dir_name(file_name) not in [ + top_level_directory, + MAC_OS_ZIP_HIDDEN_DIR_NAME, + ]: + return None + + return top_level_directory + + +def remove_dir_from_filepaths(base_dir: str, rdir: str): + """ + base_dir: String path of the directory containing rdir + rdir: String path of directory relative to base_dir whose contents should + be moved to its base_dir, its parent directory + + Removes rdir from the filepaths of all files and directories inside it. + In other words, moves all the files inside rdir to the directory that + contains rdir. Assumes base_dir's contents and rdir's contents have no + name conflicts. + """ + + # Move rdir to a temporary directory, so its contents can be moved to + # base_dir without any name conflicts + with TemporaryDirectory() as tmp_dir: + # shutil.move() is used instead of os.rename() in case rdir and tmp_dir + # are located on separate file systems + shutil.move(os.path.join(base_dir, rdir), os.path.join(tmp_dir, rdir)) + + # Shift children out of rdir and into base_dir + rdir_children = os.listdir(os.path.join(tmp_dir, rdir)) + for child in rdir_children: + shutil.move( + os.path.join(tmp_dir, rdir, child), os.path.join(base_dir, child) + ) + + +def unzip_package( + package_path: str, + target_dir: str, + remove_top_level_directory: bool, + unlink_zip: bool, + logger: Optional[logging.Logger] = default_logger, +) -> None: + """ + Unzip the compressed package contained at package_path to target_dir. + + If remove_top_level_directory is True and the top level consists of a + a single directory (or possibly also a second hidden directory named + __MACOSX at the top level arising from macOS's zip command), the function + will automatically remove the top-level directory and store the contents + directly in target_dir. + + Otherwise, if remove_top_level_directory is False or if the top level + consists of multiple files or directories (not counting __MACOS), + the zip contents will be stored in target_dir. + + Args: + package_path: String path of the compressed package to unzip. + target_dir: String path of the directory to store the unzipped contents. + remove_top_level_directory: Whether to remove the top-level directory + from the zip contents. + unlink_zip: Whether to unlink the zip file stored at package_path. + logger: Optional logger to use for logging. + + """ + try: + os.mkdir(target_dir) + except FileExistsError: + logger.info(f"Directory at {target_dir} already exists") + + logger.debug(f"Unpacking {package_path} to {target_dir}") + + with ZipFile(str(package_path), "r") as zip_ref: + zip_ref.extractall(target_dir) + if remove_top_level_directory: + top_level_directory = get_top_level_dir_from_compressed_package(package_path) + if top_level_directory is not None: + # Remove __MACOSX directory if it exists + macos_dir = os.path.join(target_dir, MAC_OS_ZIP_HIDDEN_DIR_NAME) + if os.path.isdir(macos_dir): + shutil.rmtree(macos_dir) + + remove_dir_from_filepaths(target_dir, top_level_directory) + + if unlink_zip: + Path(package_path).unlink() + + +def delete_package(pkg_uri: str, base_directory: str) -> Tuple[bool, int]: + """Deletes a specific URI from the local filesystem. + + Args: + pkg_uri: URI to delete. + + Returns: + bool: True if the URI was successfully deleted, else False. + """ + + deleted = False + path = Path(_get_local_path(base_directory, pkg_uri)) + with FileLock(str(path) + ".lock"): + path = path.with_suffix("") + if path.exists(): + if path.is_dir() and not path.is_symlink(): + shutil.rmtree(str(path)) + else: + path.unlink() + deleted = True + + return deleted + + +async def install_wheel_package( + wheel_uri: str, + target_dir: str, + logger: Optional[logging.Logger] = default_logger, +) -> None: + """Install packages in the wheel URI, and then delete the local wheel file.""" + + pip_install_cmd = [ + "pip", + "install", + wheel_uri, + f"--target={target_dir}", + ] + + logger.info("Running py_modules wheel install command: %s", str(pip_install_cmd)) + try: + # TODO(architkulkarni): Use `await check_output_cmd` or similar. + exit_code, output = exec_cmd_stream_to_logger(pip_install_cmd, logger) + finally: + wheel_uri_path = Path(wheel_uri) + if wheel_uri_path.exists(): + if wheel_uri_path.is_dir(): + shutil.rmtree(wheel_uri) + else: + Path(wheel_uri).unlink() + + if exit_code != 0: + if Path(target_dir).exists(): + shutil.rmtree(target_dir) + raise RuntimeError( + f"Failed to install py_modules wheel {wheel_uri}" + f"to {target_dir}:\n{output}" + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/pip.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/pip.py new file mode 100644 index 0000000000000000000000000000000000000000..0af8a63914e0dddeabc1c6bc5c20e498ec0714bd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/pip.py @@ -0,0 +1,338 @@ +import asyncio +import hashlib +import json +import logging +import os +import shutil +import sys +from asyncio import create_task, get_running_loop +from typing import Dict, List, Optional + +from ray._common.utils import try_to_create_directory +from ray._private.runtime_env import dependency_utils, virtualenv_utils +from ray._private.runtime_env.packaging import Protocol, parse_uri +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray._private.runtime_env.utils import check_output_cmd +from ray._private.utils import get_directory_size_bytes + +default_logger = logging.getLogger(__name__) + + +def _get_pip_hash(pip_dict: Dict) -> str: + serialized_pip_spec = json.dumps(pip_dict, sort_keys=True) + hash_val = hashlib.sha1(serialized_pip_spec.encode("utf-8")).hexdigest() + return hash_val + + +def get_uri(runtime_env: Dict) -> Optional[str]: + """Return `"pip://"`, or None if no GC required.""" + pip = runtime_env.get("pip") + if pip is not None: + if isinstance(pip, dict): + uri = "pip://" + _get_pip_hash(pip_dict=pip) + elif isinstance(pip, list): + uri = "pip://" + _get_pip_hash(pip_dict=dict(packages=pip)) + else: + raise TypeError( + "pip field received by RuntimeEnvAgent must be " + f"list or dict, not {type(pip).__name__}." + ) + else: + uri = None + return uri + + +class PipProcessor: + def __init__( + self, + target_dir: str, + runtime_env: "RuntimeEnv", # noqa: F821 + logger: Optional[logging.Logger] = default_logger, + ): + try: + import virtualenv # noqa: F401 ensure virtualenv exists. + except ImportError: + raise RuntimeError( + f"Please install virtualenv " + f"`{sys.executable} -m pip install virtualenv`" + f"to enable pip runtime env." + ) + logger.debug("Setting up pip for runtime_env: %s", runtime_env) + self._target_dir = target_dir + self._runtime_env = runtime_env + self._logger = logger + + self._pip_config = self._runtime_env.pip_config() + self._pip_env = os.environ.copy() + self._pip_env.update(self._runtime_env.env_vars()) + + @classmethod + async def _ensure_pip_version( + cls, + path: str, + pip_version: Optional[str], + cwd: str, + pip_env: Dict, + logger: logging.Logger, + ): + """Run the pip command to reinstall pip to the specified version.""" + if not pip_version: + return + + python = virtualenv_utils.get_virtualenv_python(path) + # Ensure pip version. + pip_reinstall_cmd = [ + python, + "-m", + "pip", + "install", + "--disable-pip-version-check", + f"pip{pip_version}", + ] + logger.info("Installing pip with version %s", pip_version) + + await check_output_cmd(pip_reinstall_cmd, logger=logger, cwd=cwd, env=pip_env) + + async def _pip_check( + self, + path: str, + pip_check: bool, + cwd: str, + pip_env: Dict, + logger: logging.Logger, + ): + """Run the pip check command to check python dependency conflicts. + If exists conflicts, the exit code of pip check command will be non-zero. + """ + if not pip_check: + logger.info("Skip pip check.") + return + python = virtualenv_utils.get_virtualenv_python(path) + + await check_output_cmd( + [python, "-m", "pip", "check", "--disable-pip-version-check"], + logger=logger, + cwd=cwd, + env=pip_env, + ) + + logger.info("Pip check on %s successfully.", path) + + @classmethod + async def _install_pip_packages( + cls, + path: str, + pip_packages: List[str], + cwd: str, + pip_env: Dict, + logger: logging.Logger, + ): + virtualenv_path = virtualenv_utils.get_virtualenv_path(path) + python = virtualenv_utils.get_virtualenv_python(path) + # TODO(fyrestone): Support -i, --no-deps, --no-cache-dir, ... + pip_requirements_file = dependency_utils.get_requirements_file( + path, pip_packages + ) + + # Avoid blocking the event loop. + loop = get_running_loop() + await loop.run_in_executor( + None, + dependency_utils.gen_requirements_txt, + pip_requirements_file, + pip_packages, + ) + + # pip options + # + # --disable-pip-version-check + # Don't periodically check PyPI to determine whether a new version + # of pip is available for download. + # + # --no-cache-dir + # Disable the cache, the pip runtime env is a one-time installation, + # and we don't need to handle the pip cache broken. + pip_install_cmd = [ + python, + "-m", + "pip", + "install", + "--disable-pip-version-check", + "--no-cache-dir", + "-r", + pip_requirements_file, + ] + logger.info("Installing python requirements to %s", virtualenv_path) + + await check_output_cmd(pip_install_cmd, logger=logger, cwd=cwd, env=pip_env) + + async def _run(self): + path = self._target_dir + logger = self._logger + pip_packages = self._pip_config["packages"] + # We create an empty directory for exec cmd so that the cmd will + # run more stable. e.g. if cwd has ray, then checking ray will + # look up ray in cwd instead of site packages. + exec_cwd = os.path.join(path, "exec_cwd") + os.makedirs(exec_cwd, exist_ok=True) + try: + await virtualenv_utils.create_or_get_virtualenv(path, exec_cwd, logger) + python = virtualenv_utils.get_virtualenv_python(path) + async with dependency_utils.check_ray(python, exec_cwd, logger): + # Ensure pip version. + await self._ensure_pip_version( + path, + self._pip_config.get("pip_version", None), + exec_cwd, + self._pip_env, + logger, + ) + # Install pip packages. + await self._install_pip_packages( + path, + pip_packages, + exec_cwd, + self._pip_env, + logger, + ) + # Check python environment for conflicts. + await self._pip_check( + path, + self._pip_config.get("pip_check", False), + exec_cwd, + self._pip_env, + logger, + ) + except Exception: + logger.info("Delete incomplete virtualenv: %s", path) + shutil.rmtree(path, ignore_errors=True) + logger.exception("Failed to install pip packages.") + raise + + def __await__(self): + return self._run().__await__() + + +class PipPlugin(RuntimeEnvPlugin): + name = "pip" + + def __init__(self, resources_dir: str): + self._pip_resources_dir = os.path.join(resources_dir, "pip") + self._creating_task = {} + # Maps a URI to a lock that is used to prevent multiple concurrent + # installs of the same virtualenv, see #24513 + self._create_locks: Dict[str, asyncio.Lock] = {} + # Key: created hashes. Value: size of the pip dir. + self._created_hash_bytes: Dict[str, int] = {} + try_to_create_directory(self._pip_resources_dir) + + def _get_path_from_hash(self, hash_val: str) -> str: + """Generate a path from the hash of a pip spec. + + Example output: + /tmp/ray/session_2021-11-03_16-33-59_356303_41018/runtime_resources + /pip/ray-9a7972c3a75f55e976e620484f58410c920db091 + """ + return os.path.join(self._pip_resources_dir, hash_val) + + def get_uris(self, runtime_env: "RuntimeEnv") -> List[str]: # noqa: F821 + """Return the pip URI from the RuntimeEnv if it exists, else return [].""" + pip_uri = runtime_env.pip_uri() + if pip_uri: + return [pip_uri] + return [] + + def delete_uri( + self, uri: str, logger: Optional[logging.Logger] = default_logger + ) -> int: + """Delete URI and return the number of bytes deleted.""" + logger.info("Got request to delete pip URI %s", uri) + protocol, hash_val = parse_uri(uri) + if protocol != Protocol.PIP: + raise ValueError( + "PipPlugin can only delete URIs with protocol " + f"pip. Received protocol {protocol}, URI {uri}" + ) + + # Cancel running create task. + task = self._creating_task.pop(hash_val, None) + if task is not None: + task.cancel() + + del self._created_hash_bytes[hash_val] + + pip_env_path = self._get_path_from_hash(hash_val) + local_dir_size = get_directory_size_bytes(pip_env_path) + del self._create_locks[uri] + try: + shutil.rmtree(pip_env_path) + except OSError as e: + logger.warning(f"Error when deleting pip env {pip_env_path}: {str(e)}") + return 0 + + return local_dir_size + + async def create( + self, + uri: str, + runtime_env: "RuntimeEnv", # noqa: F821 + context: "RuntimeEnvContext", # noqa: F821 + logger: Optional[logging.Logger] = default_logger, + ) -> int: + if not runtime_env.has_pip(): + return 0 + + protocol, hash_val = parse_uri(uri) + target_dir = self._get_path_from_hash(hash_val) + + async def _create_for_hash(): + await PipProcessor( + target_dir, + runtime_env, + logger, + ) + + loop = get_running_loop() + return await loop.run_in_executor( + None, get_directory_size_bytes, target_dir + ) + + if uri not in self._create_locks: + # async lock to prevent the same virtualenv being concurrently installed + self._create_locks[uri] = asyncio.Lock() + + async with self._create_locks[uri]: + if hash_val in self._created_hash_bytes: + return self._created_hash_bytes[hash_val] + self._creating_task[hash_val] = task = create_task(_create_for_hash()) + task.add_done_callback(lambda _: self._creating_task.pop(hash_val, None)) + pip_dir_bytes = await task + self._created_hash_bytes[hash_val] = pip_dir_bytes + return pip_dir_bytes + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: "RuntimeEnvContext", # noqa: F821 + logger: logging.Logger = default_logger, + ): + if not runtime_env.has_pip(): + return + # PipPlugin only uses a single URI. + uri = uris[0] + # Update py_executable. + protocol, hash_val = parse_uri(uri) + target_dir = self._get_path_from_hash(hash_val) + virtualenv_python = virtualenv_utils.get_virtualenv_python(target_dir) + + if not os.path.exists(virtualenv_python): + raise ValueError( + f"Local directory {target_dir} for URI {uri} does " + "not exist on the cluster. Something may have gone wrong while " + "installing the runtime_env `pip` packages." + ) + context.py_executable = virtualenv_python + context.command_prefix += virtualenv_utils.get_virtualenv_activate_command( + target_dir + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/plugin.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..e5da3ecbeb6c285f0d3ec296f31598fcc58b5d5a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/plugin.py @@ -0,0 +1,265 @@ +import json +import logging +import os +from abc import ABC +from typing import Any, Dict, List, Optional, Type + +from ray._common.utils import import_attr +from ray._private.runtime_env.constants import ( + RAY_RUNTIME_ENV_CLASS_FIELD_NAME, + RAY_RUNTIME_ENV_PLUGIN_DEFAULT_PRIORITY, + RAY_RUNTIME_ENV_PLUGIN_MAX_PRIORITY, + RAY_RUNTIME_ENV_PLUGIN_MIN_PRIORITY, + RAY_RUNTIME_ENV_PLUGINS_ENV_VAR, + RAY_RUNTIME_ENV_PRIORITY_FIELD_NAME, +) +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.uri_cache import URICache +from ray.util.annotations import DeveloperAPI + +default_logger = logging.getLogger(__name__) + + +@DeveloperAPI +class RuntimeEnvPlugin(ABC): + """Abstract base class for runtime environment plugins.""" + + name: str = None + priority: int = RAY_RUNTIME_ENV_PLUGIN_DEFAULT_PRIORITY + + @staticmethod + def validate(runtime_env_dict: dict) -> None: + """Validate user entry for this plugin. + + The method is invoked upon installation of runtime env. + + Args: + runtime_env_dict: The user-supplied runtime environment dict. + + Raises: + ValueError: If the validation fails. + """ + pass + + def get_uris(self, runtime_env: "RuntimeEnv") -> List[str]: # noqa: F821 + return [] + + async def create( + self, + uri: Optional[str], + runtime_env, + context: RuntimeEnvContext, + logger: logging.Logger, + ) -> float: + """Create and install the runtime environment. + + Gets called in the runtime env agent at install time. The URI can be + used as a caching mechanism. + + Args: + uri: A URI uniquely describing this resource. + runtime_env: The RuntimeEnv object. + context: Auxiliary information supplied by Ray. + logger: A logger to log messages during the context modification. + + Returns: + float: The disk space taken up by this plugin installation for this + environment. e.g. for working_dir, this downloads the files to the + local node. + """ + return 0 + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: logging.Logger, + ) -> None: + """Modify context to change worker startup behavior. + + For example, you can use this to prepend "cd " command to worker + startup, or add new environment variables. + + Args: + uris: The URIs used by this resource. + runtime_env: The RuntimeEnv object. + context: Auxiliary information supplied by Ray. + logger: A logger to log messages during the context modification. + """ + return + + def delete_uri(self, uri: str, logger: logging.Logger) -> float: + """Delete the runtime environment given uri. + + Args: + uri: A URI uniquely describing this resource. + logger: The logger used to log messages during the deletion. + + Returns: + float: The amount of space reclaimed by the deletion. + """ + return 0 + + +class PluginSetupContext: + def __init__( + self, + name: str, + class_instance: RuntimeEnvPlugin, + priority: int, + uri_cache: URICache, + ): + self.name = name + self.class_instance = class_instance + self.priority = priority + self.uri_cache = uri_cache + + +class RuntimeEnvPluginManager: + """This manager is used to load plugins in runtime env agent.""" + + def __init__(self): + self.plugins: Dict[str, PluginSetupContext] = {} + plugin_config_str = os.environ.get(RAY_RUNTIME_ENV_PLUGINS_ENV_VAR) + if plugin_config_str: + plugin_configs = json.loads(plugin_config_str) + self.load_plugins(plugin_configs) + + def validate_plugin_class(self, plugin_class: Type[RuntimeEnvPlugin]) -> None: + if not issubclass(plugin_class, RuntimeEnvPlugin): + raise RuntimeError( + f"Invalid runtime env plugin class {plugin_class}. " + "The plugin class must inherit " + "ray._private.runtime_env.plugin.RuntimeEnvPlugin." + ) + if not plugin_class.name: + raise RuntimeError(f"No valid name in runtime env plugin {plugin_class}.") + if plugin_class.name in self.plugins: + raise RuntimeError( + f"The name of runtime env plugin {plugin_class} conflicts " + f"with {self.plugins[plugin_class.name]}.", + ) + + def validate_priority(self, priority: Any) -> None: + if ( + not isinstance(priority, int) + or priority < RAY_RUNTIME_ENV_PLUGIN_MIN_PRIORITY + or priority > RAY_RUNTIME_ENV_PLUGIN_MAX_PRIORITY + ): + raise RuntimeError( + f"Invalid runtime env priority {priority}, " + "it should be an integer between " + f"{RAY_RUNTIME_ENV_PLUGIN_MIN_PRIORITY} " + f"and {RAY_RUNTIME_ENV_PLUGIN_MAX_PRIORITY}." + ) + + def load_plugins(self, plugin_configs: List[Dict]) -> None: + """Load runtime env plugins and create URI caches for them.""" + for plugin_config in plugin_configs: + if ( + not isinstance(plugin_config, dict) + or RAY_RUNTIME_ENV_CLASS_FIELD_NAME not in plugin_config + ): + raise RuntimeError( + f"Invalid runtime env plugin config {plugin_config}, " + "it should be a object which contains the " + f"{RAY_RUNTIME_ENV_CLASS_FIELD_NAME} field." + ) + plugin_class = import_attr(plugin_config[RAY_RUNTIME_ENV_CLASS_FIELD_NAME]) + self.validate_plugin_class(plugin_class) + + # The priority should be an integer between 0 and 100. + # The default priority is 10. A smaller number indicates a + # higher priority and the plugin will be set up first. + if RAY_RUNTIME_ENV_PRIORITY_FIELD_NAME in plugin_config: + priority = plugin_config[RAY_RUNTIME_ENV_PRIORITY_FIELD_NAME] + else: + priority = plugin_class.priority + self.validate_priority(priority) + + class_instance = plugin_class() + self.plugins[plugin_class.name] = PluginSetupContext( + plugin_class.name, + class_instance, + priority, + self.create_uri_cache_for_plugin(class_instance), + ) + + def add_plugin(self, plugin: RuntimeEnvPlugin) -> None: + """Add a plugin to the manager and create a URI cache for it. + + Args: + plugin: The class instance of the plugin. + """ + plugin_class = type(plugin) + self.validate_plugin_class(plugin_class) + self.validate_priority(plugin_class.priority) + self.plugins[plugin_class.name] = PluginSetupContext( + plugin_class.name, + plugin, + plugin_class.priority, + self.create_uri_cache_for_plugin(plugin), + ) + + def create_uri_cache_for_plugin(self, plugin: RuntimeEnvPlugin) -> URICache: + """Create a URI cache for a plugin. + + Args: + plugin_name: The name of the plugin. + + Returns: + The created URI cache for the plugin. + """ + # Set the max size for the cache. Defaults to 10 GB. + cache_size_env_var = f"RAY_RUNTIME_ENV_{plugin.name}_CACHE_SIZE_GB".upper() + cache_size_bytes = int( + (1024**3) * float(os.environ.get(cache_size_env_var, 10)) + ) + return URICache(plugin.delete_uri, cache_size_bytes) + + def sorted_plugin_setup_contexts(self) -> List[PluginSetupContext]: + """Get the sorted plugin setup contexts, sorted by increasing priority. + + Returns: + The sorted plugin setup contexts. + """ + return sorted(self.plugins.values(), key=lambda x: x.priority) + + +async def create_for_plugin_if_needed( + runtime_env: "RuntimeEnv", # noqa: F821 + plugin: RuntimeEnvPlugin, + uri_cache: URICache, + context: RuntimeEnvContext, + logger: logging.Logger = default_logger, +): + """Set up the environment using the plugin if not already set up and cached.""" + if plugin.name not in runtime_env or runtime_env[plugin.name] is None: + return + + plugin.validate(runtime_env) + + uris = plugin.get_uris(runtime_env) + + if not uris: + logger.debug( + f"No URIs for runtime env plugin {plugin.name}; " + "create always without checking the cache." + ) + await plugin.create(None, runtime_env, context, logger=logger) + + for uri in uris: + if uri not in uri_cache: + logger.debug(f"Cache miss for URI {uri}.") + size_bytes = await plugin.create(uri, runtime_env, context, logger=logger) + uri_cache.add(uri, size_bytes, logger=logger) + else: + logger.info( + f"Runtime env {plugin.name} {uri} is already installed " + "and will be reused. Search " + "all runtime_env_setup-*.log to find the corresponding setup log." + ) + uri_cache.mark_used(uri, logger=logger) + + plugin.modify_context(uris, runtime_env, context, logger) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/plugin_schema_manager.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/plugin_schema_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..5de24113b26fa73247eb47b7be31ffb191c3ac20 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/plugin_schema_manager.py @@ -0,0 +1,97 @@ +import json +import logging +import os +from typing import List + +import jsonschema + +from ray._private.runtime_env.constants import ( + RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX, + RAY_RUNTIME_ENV_PLUGIN_SCHEMAS_ENV_VAR, +) + +logger = logging.getLogger(__name__) + + +class RuntimeEnvPluginSchemaManager: + """This manager is used to load plugin json schemas.""" + + default_schema_path = os.path.join( + os.path.dirname(__file__), "../../runtime_env/schemas" + ) + schemas = {} + loaded = False + + @classmethod + def _load_schemas(cls, schema_paths: List[str]): + for schema_path in schema_paths: + try: + with open(schema_path) as f: + schema = json.load(f) + except json.decoder.JSONDecodeError: + logger.error("Invalid runtime env schema %s, skip it.", schema_path) + continue + except OSError: + logger.error("Cannot open runtime env schema %s, skip it.", schema_path) + continue + if "title" not in schema: + logger.error( + "No valid title in runtime env schema %s, skip it.", schema_path + ) + continue + if schema["title"] in cls.schemas: + logger.error( + "The 'title' of runtime env schema %s conflicts with %s, skip it.", + schema_path, + cls.schemas[schema["title"]], + ) + continue + cls.schemas[schema["title"]] = schema + + @classmethod + def _load_default_schemas(cls): + schema_json_files = list() + for root, _, files in os.walk(cls.default_schema_path): + for f in files: + if f.endswith(RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX): + schema_json_files.append(os.path.join(root, f)) + logger.debug( + f"Loading the default runtime env schemas: {schema_json_files}." + ) + cls._load_schemas(schema_json_files) + + @classmethod + def _load_schemas_from_env_var(cls): + # The format of env var: + # "/path/to/env_1_schema.json,/path/to/env_2_schema.json,/path/to/schemas_dir/" + schema_paths = os.environ.get(RAY_RUNTIME_ENV_PLUGIN_SCHEMAS_ENV_VAR) + if schema_paths: + schema_json_files = list() + for path in schema_paths.split(","): + if path.endswith(RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX): + schema_json_files.append(path) + elif os.path.isdir(path): + for root, _, files in os.walk(path): + for f in files: + if f.endswith(RAY_RUNTIME_ENV_PLUGIN_SCHEMA_SUFFIX): + schema_json_files.append(os.path.join(root, f)) + logger.info( + f"Loading the runtime env schemas from env var: {schema_json_files}." + ) + cls._load_schemas(schema_json_files) + + @classmethod + def validate(cls, name, instance): + if not cls.loaded: + # Load the schemas lazily. + cls._load_default_schemas() + cls._load_schemas_from_env_var() + cls.loaded = True + # if no schema matches, skip the validation. + if name in cls.schemas: + jsonschema.validate(instance=instance, schema=cls.schemas[name]) + + @classmethod + def clear(cls): + cls.schemas.clear() + cls.loaded = False diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/protocol.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..b61dea8f71fa7817a6cda88253d4c4ed2b3321de --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/protocol.py @@ -0,0 +1,193 @@ +import enum +import os + +from ray._private.runtime_env.default_impl import get_protocols_provider + + +class ProtocolsProvider: + _MISSING_DEPENDENCIES_WARNING = ( + "Note that these must be preinstalled " + "on all nodes in the Ray cluster; it is not " + "sufficient to install them in the runtime_env." + ) + + @classmethod + def get_protocols(cls): + return { + # For packages dynamically uploaded and managed by the GCS. + "gcs", + # For conda environments installed locally on each node. + "conda", + # For pip environments installed locally on each node. + "pip", + # For uv environments install locally on each node. + "uv", + # Remote https path, assumes everything packed in one zip file. + "https", + # Remote s3 path, assumes everything packed in one zip file. + "s3", + # Remote google storage path, assumes everything packed in one zip file. + "gs", + # Remote azure blob storage path, assumes everything packed in one zip file. + "azure", + # File storage path, assumes everything packed in one zip file. + "file", + } + + @classmethod + def get_remote_protocols(cls): + return {"https", "s3", "gs", "azure", "file"} + + @classmethod + def _handle_s3_protocol(cls): + """Set up S3 protocol handling. + + Returns: + tuple: (open_file function, transport_params) + + Raises: + ImportError: If required dependencies are not installed. + """ + try: + import boto3 + from smart_open import open as open_file + except ImportError: + raise ImportError( + "You must `pip install smart_open[s3]` " + "to fetch URIs in s3 bucket. " + cls._MISSING_DEPENDENCIES_WARNING + ) + + transport_params = {"client": boto3.client("s3")} + return open_file, transport_params + + @classmethod + def _handle_gs_protocol(cls): + """Set up Google Cloud Storage protocol handling. + + Returns: + tuple: (open_file function, transport_params) + + Raises: + ImportError: If required dependencies are not installed. + """ + try: + from google.cloud import storage # noqa: F401 + from smart_open import open as open_file + except ImportError: + raise ImportError( + "You must `pip install smart_open[gcs]` " + "to fetch URIs in Google Cloud Storage bucket." + + cls._MISSING_DEPENDENCIES_WARNING + ) + + return open_file, None + + @classmethod + def _handle_azure_protocol(cls): + """Set up Azure blob storage protocol handling. + + Returns: + tuple: (open_file function, transport_params) + + Raises: + ImportError: If required dependencies are not installed. + ValueError: If required environment variables are not set. + """ + try: + from azure.identity import DefaultAzureCredential + from azure.storage.blob import BlobServiceClient # noqa: F401 + from smart_open import open as open_file + except ImportError: + raise ImportError( + "You must `pip install azure-storage-blob azure-identity smart_open[azure]` " + "to fetch URIs in Azure Blob Storage. " + + cls._MISSING_DEPENDENCIES_WARNING + ) + + # Define authentication variable + azure_storage_account_name = os.getenv("AZURE_STORAGE_ACCOUNT") + + if not azure_storage_account_name: + raise ValueError( + "Azure Blob Storage authentication requires " + "AZURE_STORAGE_ACCOUNT environment variable to be set." + ) + + account_url = f"https://{azure_storage_account_name}.blob.core.windows.net/" + transport_params = { + "client": BlobServiceClient( + account_url=account_url, credential=DefaultAzureCredential() + ) + } + + return open_file, transport_params + + @classmethod + def download_remote_uri(cls, protocol: str, source_uri: str, dest_file: str): + """Download file from remote URI to destination file. + + Args: + protocol: The protocol to use for downloading (e.g., 's3', 'https'). + source_uri: The source URI to download from. + dest_file: The destination file path to save to. + + Raises: + ImportError: If required dependencies for the protocol are not installed. + """ + assert protocol in cls.get_remote_protocols() + + tp = None + open_file = None + + if protocol == "file": + source_uri = source_uri[len("file://") :] + + def open_file(uri, mode, *, transport_params=None): + return open(uri, mode) + + elif protocol == "s3": + open_file, tp = cls._handle_s3_protocol() + elif protocol == "gs": + open_file, tp = cls._handle_gs_protocol() + elif protocol == "azure": + open_file, tp = cls._handle_azure_protocol() + else: + try: + from smart_open import open as open_file + except ImportError: + raise ImportError( + "You must `pip install smart_open` " + f"to fetch {protocol.upper()} URIs. " + + cls._MISSING_DEPENDENCIES_WARNING + ) + + with open_file(source_uri, "rb", transport_params=tp) as fin: + with open_file(dest_file, "wb") as fout: + fout.write(fin.read()) + + +_protocols_provider = get_protocols_provider() + +Protocol = enum.Enum( + "Protocol", + {protocol.upper(): protocol for protocol in _protocols_provider.get_protocols()}, +) + + +@classmethod +def _remote_protocols(cls): + # Returns a list of protocols that support remote storage + # These protocols should only be used with paths that end in ".zip" or ".whl" + return [ + cls[protocol.upper()] for protocol in _protocols_provider.get_remote_protocols() + ] + + +Protocol.remote_protocols = _remote_protocols + + +def _download_remote_uri(self, source_uri, dest_file): + return _protocols_provider.download_remote_uri(self.value, source_uri, dest_file) + + +Protocol.download_remote_uri = _download_remote_uri diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/py_executable.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/py_executable.py new file mode 100644 index 0000000000000000000000000000000000000000..0a57344909042a6237cd6ac0f1f4c760809db1f2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/py_executable.py @@ -0,0 +1,45 @@ +import logging +from typing import List, Optional + +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.plugin import RuntimeEnvPlugin + +default_logger = logging.getLogger(__name__) + + +class PyExecutablePlugin(RuntimeEnvPlugin): + """This plugin allows running Ray workers with a custom Python executable. + + You can use it with + `ray.init(runtime_env={"py_executable": " "})`. If you specify + a `working_dir` in the runtime environment, the executable will have access + to the working directory, for example, to a requirements.txt for a package manager, + a script for a debugger, or the executable could be a shell script in the + working directory. You can also use this plugin to run worker processes + in a custom profiler or use a custom Python interpreter or `python` with + custom arguments. + """ + + name = "py_executable" + + def __init__(self): + pass + + async def create( + self, + uri: Optional[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: logging.Logger = default_logger, + ) -> int: + return 0 + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + logger.info("Running py_executable plugin") + context.py_executable = runtime_env.py_executable() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/py_modules.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/py_modules.py new file mode 100644 index 0000000000000000000000000000000000000000..fc6e03693e02b5fcca564eb7f2280ffd3f44fe81 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/py_modules.py @@ -0,0 +1,233 @@ +import logging +import os +from pathlib import Path +from types import ModuleType +from typing import Any, Dict, List, Optional + +from ray._common.utils import try_to_create_directory +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.packaging import ( + Protocol, + delete_package, + download_and_unpack_package, + get_local_dir_from_uri, + get_uri_for_directory, + get_uri_for_file, + get_uri_for_package, + install_wheel_package, + is_whl_uri, + package_exists, + parse_uri, + upload_package_if_needed, + upload_package_to_gcs, +) +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray._private.runtime_env.working_dir import set_pythonpath_in_context +from ray._private.utils import get_directory_size_bytes +from ray._raylet import GcsClient +from ray.exceptions import RuntimeEnvSetupError + +default_logger = logging.getLogger(__name__) + + +def _check_is_uri(s: str) -> bool: + try: + protocol, path = parse_uri(s) + except ValueError: + protocol, path = None, None + + if ( + protocol in Protocol.remote_protocols() + and not path.endswith(".zip") + and not path.endswith(".whl") + ): + raise ValueError("Only .zip or .whl files supported for remote URIs.") + + return protocol is not None + + +def upload_py_modules_if_needed( + runtime_env: Dict[str, Any], + scratch_dir: Optional[str] = os.getcwd(), + logger: Optional[logging.Logger] = default_logger, + upload_fn=None, +) -> Dict[str, Any]: + """Uploads the entries in py_modules and replaces them with a list of URIs. + + For each entry that is already a URI, this is a no-op. + """ + py_modules = runtime_env.get("py_modules") + if py_modules is None: + return runtime_env + + if not isinstance(py_modules, list): + raise TypeError( + "py_modules must be a List of local paths, imported modules, or " + f"URIs, got {type(py_modules)}." + ) + + py_modules_uris = [] + for module in py_modules: + if isinstance(module, str): + # module_path is a local path or a URI. + module_path = module + elif isinstance(module, Path): + module_path = str(module) + elif isinstance(module, ModuleType): + if not hasattr(module, "__path__"): + # This is a single-file module. + module_path = module.__file__ + else: + # NOTE(edoakes): Python allows some installed Python packages to + # be split into multiple directories. We could probably handle + # this, but it seems tricky & uncommon. If it's a problem for + # users, we can add this support on demand. + if len(module.__path__) > 1: + raise ValueError( + "py_modules only supports modules whose __path__" + " has length 1 or those who are single-file." + ) + [module_path] = module.__path__ + else: + raise TypeError( + "py_modules must be a list of file paths, URIs, " + f"or imported modules, got {type(module)}." + ) + + if _check_is_uri(module_path): + module_uri = module_path + else: + # module_path is a local path. + if Path(module_path).is_dir() or Path(module_path).suffix == ".py": + is_dir = Path(module_path).is_dir() + excludes = runtime_env.get("excludes", None) + if is_dir: + module_uri = get_uri_for_directory(module_path, excludes=excludes) + else: + module_uri = get_uri_for_file(module_path) + if upload_fn is None: + try: + upload_package_if_needed( + module_uri, + scratch_dir, + module_path, + excludes=excludes, + include_parent_dir=is_dir, + logger=logger, + ) + except Exception as e: + from ray.util.spark.utils import is_in_databricks_runtime + + if is_in_databricks_runtime(): + raise RuntimeEnvSetupError( + f"Failed to upload module {module_path} to the Ray " + f"cluster, please ensure there are only files under " + f"the module path, notebooks under the path are " + f"not allowed, original exception: {e}" + ) from e + raise RuntimeEnvSetupError( + f"Failed to upload module {module_path} to the Ray " + f"cluster: {e}" + ) from e + else: + upload_fn(module_path, excludes=excludes) + elif Path(module_path).suffix == ".whl": + module_uri = get_uri_for_package(Path(module_path)) + if upload_fn is None: + if not package_exists(module_uri): + try: + upload_package_to_gcs( + module_uri, Path(module_path).read_bytes() + ) + except Exception as e: + raise RuntimeEnvSetupError( + f"Failed to upload {module_path} to the Ray " + f"cluster: {e}" + ) from e + else: + upload_fn(module_path, excludes=None, is_file=True) + else: + raise ValueError( + "py_modules entry must be a .py file, " + "a directory, or a .whl file; " + f"got {module_path}" + ) + + py_modules_uris.append(module_uri) + + # TODO(architkulkarni): Expose a single URI for py_modules. This plugin + # should internally handle the "sub-URIs", the individual modules. + + runtime_env["py_modules"] = py_modules_uris + return runtime_env + + +class PyModulesPlugin(RuntimeEnvPlugin): + + name = "py_modules" + + def __init__(self, resources_dir: str, gcs_client: GcsClient): + self._resources_dir = os.path.join(resources_dir, "py_modules_files") + self._gcs_client = gcs_client + try_to_create_directory(self._resources_dir) + + def _get_local_dir_from_uri(self, uri: str): + return get_local_dir_from_uri(uri, self._resources_dir) + + def delete_uri( + self, uri: str, logger: Optional[logging.Logger] = default_logger + ) -> int: + """Delete URI and return the number of bytes deleted.""" + logger.info("Got request to delete pymodule URI %s", uri) + local_dir = get_local_dir_from_uri(uri, self._resources_dir) + local_dir_size = get_directory_size_bytes(local_dir) + + deleted = delete_package(uri, self._resources_dir) + if not deleted: + logger.warning(f"Tried to delete nonexistent URI: {uri}.") + return 0 + + return local_dir_size + + def get_uris(self, runtime_env) -> List[str]: + return runtime_env.py_modules() + + async def create( + self, + uri: str, + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ) -> int: + + module_dir = await download_and_unpack_package( + uri, self._resources_dir, self._gcs_client, logger=logger + ) + + if is_whl_uri(uri): + wheel_uri = module_dir + module_dir = self._get_local_dir_from_uri(uri) + await install_wheel_package( + wheel_uri=wheel_uri, target_dir=module_dir, logger=logger + ) + + return get_directory_size_bytes(module_dir) + + def modify_context( + self, + uris: List[str], + runtime_env_dict: Dict, + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + module_dirs = [] + for uri in uris: + module_dir = self._get_local_dir_from_uri(uri) + if not module_dir.exists(): + raise ValueError( + f"Local directory {module_dir} for URI {uri} does " + "not exist on the cluster. Something may have gone wrong while " + "downloading, unpacking or installing the py_modules files." + ) + module_dirs.append(str(module_dir)) + set_pythonpath_in_context(os.pathsep.join(module_dirs), context) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/rocprof_sys.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/rocprof_sys.py new file mode 100644 index 0000000000000000000000000000000000000000..a05626de1a0e336561cf1c5c6768899dc8c82ca7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/rocprof_sys.py @@ -0,0 +1,173 @@ +import asyncio +import copy +import logging +import os +import subprocess +import sys +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +from ray._common.utils import try_to_create_directory +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray.exceptions import RuntimeEnvSetupError + +default_logger = logging.getLogger(__name__) + +# rocprof-sys config used when runtime_env={"_rocprof_sys": "default"} +# Refer to the following link for more information on rocprof-sys options +# https://rocm.docs.amd.com/projects/rocprofiler-systems/en/docs-6.4.0/how-to/understanding-rocprof-sys-output.html +ROCPROFSYS_DEFAULT_CONFIG = { + "env": { + "ROCPROFSYS_TIME_OUTPUT": "false", + "ROCPROFSYS_OUTPUT_PREFIX": "worker_process_%p", + }, + "args": { + "F": "true", + }, +} + + +def parse_rocprof_sys_config( + rocprof_sys_config: Dict[str, str] +) -> Tuple[List[str], List[str]]: + """ + Function to convert dictionary of rocprof-sys options into + rocprof-sys-python command line + + The function returns: + - List[str]: rocprof-sys-python cmd line split into list of str + """ + rocprof_sys_cmd = ["rocprof-sys-python"] + rocprof_sys_env = {} + if "args" in rocprof_sys_config: + # Parse rocprof-sys arg options + for option, option_val in rocprof_sys_config["args"].items(): + # option standard based on + # https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html + if len(option) > 1: + rocprof_sys_cmd.append(f"--{option}={option_val}") + else: + rocprof_sys_cmd += [f"-{option}", option_val] + if "env" in rocprof_sys_config: + rocprof_sys_env = rocprof_sys_config["env"] + rocprof_sys_cmd.append("--") + return rocprof_sys_cmd, rocprof_sys_env + + +class RocProfSysPlugin(RuntimeEnvPlugin): + name = "_rocprof_sys" + + def __init__(self, resources_dir: str): + self.rocprof_sys_cmd = [] + self.rocprof_sys_env = {} + + # replace this with better way to get logs dir + session_dir, runtime_dir = os.path.split(resources_dir) + self._rocprof_sys_dir = Path(session_dir) / "logs" / "rocprof_sys" + try_to_create_directory(self._rocprof_sys_dir) + + async def _check_rocprof_sys_script( + self, rocprof_sys_config: Dict[str, str] + ) -> Tuple[bool, str]: + """ + Function to validate if rocprof_sys_config is a valid rocprof_sys profile options + Args: + rocprof_sys_config: dictionary mapping rocprof_sys option to it's value + Returns: + a tuple consists of a boolean indicating if the rocprof_sys_config + is valid option and an error message if the rocprof_sys_config is invalid + """ + + # use empty as rocprof_sys report test filename + test_folder = str(Path(self._rocprof_sys_dir) / "test") + rocprof_sys_cmd, rocprof_sys_env = parse_rocprof_sys_config(rocprof_sys_config) + rocprof_sys_env_copy = copy.deepcopy(rocprof_sys_env) + rocprof_sys_env_copy["ROCPROFSYS_OUTPUT_PATH"] = test_folder + rocprof_sys_env_copy.update(os.environ) + try_to_create_directory(test_folder) + + # Create a test python file to run rocprof_sys + with open(f"{test_folder}/test.py", "w") as f: + f.write("import time\n") + try: + rocprof_sys_cmd = rocprof_sys_cmd + [f"{test_folder}/test.py"] + process = await asyncio.create_subprocess_exec( + *rocprof_sys_cmd, + env=rocprof_sys_env_copy, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + stdout, stderr = await process.communicate() + error_msg = stderr.strip() if stderr.strip() != "" else stdout.strip() + + # cleanup temp file + clean_up_cmd = ["rm", "-r", test_folder] + cleanup_process = await asyncio.create_subprocess_exec( + *clean_up_cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + _, _ = await cleanup_process.communicate() + if process.returncode == 0: + return True, None + else: + return False, error_msg + except FileNotFoundError: + return False, ("rocprof_sys is not installed") + + async def create( + self, + uri: Optional[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: logging.Logger = default_logger, + ) -> int: + rocprof_sys_config = runtime_env.rocprof_sys() + if not rocprof_sys_config: + return 0 + + if rocprof_sys_config and sys.platform != "linux": + raise RuntimeEnvSetupError("rocprof-sys CLI is only available in Linux.\n") + + if isinstance(rocprof_sys_config, str): + if rocprof_sys_config == "default": + rocprof_sys_config = ROCPROFSYS_DEFAULT_CONFIG + else: + raise RuntimeEnvSetupError( + f"Unsupported rocprof_sys config: {rocprof_sys_config}. " + "The supported config is 'default' or " + "Dictionary of rocprof_sys options" + ) + + is_valid_rocprof_sys_config, error_msg = await self._check_rocprof_sys_script( + rocprof_sys_config + ) + if not is_valid_rocprof_sys_config: + logger.warning(error_msg) + raise RuntimeEnvSetupError( + "rocprof-sys profile failed to run with the following " + f"error message:\n {error_msg}" + ) + # add set output path to logs dir + if "env" not in rocprof_sys_config: + rocprof_sys_config["env"] = {} + rocprof_sys_config["env"]["ROCPROFSYS_OUTPUT_PATH"] = str( + Path(self._rocprof_sys_dir) + ) + + self.rocprof_sys_cmd, self.rocprof_sys_env = parse_rocprof_sys_config( + rocprof_sys_config + ) + return 0 + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + logger.info("Running rocprof-sys profiler") + context.py_executable = " ".join(self.rocprof_sys_cmd) + context.env_vars.update(self.rocprof_sys_env) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/setup_hook.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/setup_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..e6c1283df274cb4e3937abaffdd64a1dc6b1e2f5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/setup_hook.py @@ -0,0 +1,193 @@ +import base64 +import logging +import os +import traceback +from typing import Any, Callable, Dict, Optional, Union + +import ray +import ray._private.ray_constants as ray_constants +import ray.cloudpickle as pickle +from ray._common.utils import load_class +from ray.runtime_env import RuntimeEnv + +logger = logging.getLogger(__name__) + +RUNTIME_ENV_FUNC_IDENTIFIER = "ray_runtime_env_func::" + + +def get_import_export_timeout(): + return int( + os.environ.get( + ray_constants.RAY_WORKER_PROCESS_SETUP_HOOK_LOAD_TIMEOUT_ENV_VAR, "60" + ) + ) + + +def _decode_function_key(key: bytes) -> str: + # b64encode only includes A-Z, a-z, 0-9, + and / characters + return RUNTIME_ENV_FUNC_IDENTIFIER + base64.b64encode(key).decode() + + +def _encode_function_key(key: str) -> bytes: + assert key.startswith(RUNTIME_ENV_FUNC_IDENTIFIER) + return base64.b64decode(key[len(RUNTIME_ENV_FUNC_IDENTIFIER) :]) + + +def export_setup_func_callable( + runtime_env: Union[Dict[str, Any], RuntimeEnv], + setup_func: Callable, + worker: "ray.Worker", +) -> Union[Dict[str, Any], RuntimeEnv]: + assert isinstance(setup_func, Callable) + try: + key = worker.function_actor_manager.export_setup_func( + setup_func, timeout=get_import_export_timeout() + ) + except Exception as e: + raise ray.exceptions.RuntimeEnvSetupError( + "Failed to export the setup function." + ) from e + env_vars = runtime_env.get("env_vars", {}) + assert ray_constants.WORKER_PROCESS_SETUP_HOOK_ENV_VAR not in env_vars, ( + f"The env var, {ray_constants.WORKER_PROCESS_SETUP_HOOK_ENV_VAR}, " + "is not permitted because it is reserved for the internal use." + ) + env_vars[ray_constants.WORKER_PROCESS_SETUP_HOOK_ENV_VAR] = _decode_function_key( + key + ) + runtime_env["env_vars"] = env_vars + # Note: This field is no-op. We don't have a plugin for the setup hook + # because we can implement it simply using an env var. + # This field is just for the observability purpose, so we store + # the name of the method. + runtime_env["worker_process_setup_hook"] = setup_func.__name__ + return runtime_env + + +def export_setup_func_module( + runtime_env: Union[Dict[str, Any], RuntimeEnv], + setup_func_module: str, +) -> Union[Dict[str, Any], RuntimeEnv]: + assert isinstance(setup_func_module, str) + env_vars = runtime_env.get("env_vars", {}) + assert ray_constants.WORKER_PROCESS_SETUP_HOOK_ENV_VAR not in env_vars, ( + f"The env var, {ray_constants.WORKER_PROCESS_SETUP_HOOK_ENV_VAR}, " + "is not permitted because it is reserved for the internal use." + ) + env_vars[ray_constants.WORKER_PROCESS_SETUP_HOOK_ENV_VAR] = setup_func_module + runtime_env["env_vars"] = env_vars + return runtime_env + + +def upload_worker_process_setup_hook_if_needed( + runtime_env: Union[Dict[str, Any], RuntimeEnv], + worker: "ray.Worker", +) -> Union[Dict[str, Any], RuntimeEnv]: + """Uploads the worker_process_setup_hook to GCS with a key. + + runtime_env["worker_process_setup_hook"] is converted to a decoded key + that can load the worker setup hook function from GCS. + i.e., you can use internalKV.Get(runtime_env["worker_process_setup_hook]) + to access the worker setup hook from GCS. + + Args: + runtime_env: The runtime_env. The value will be modified + when returned. + worker: ray.worker instance. + decoder: GCS requires the function key to be bytes. However, + we cannot json serialize (which is required to serialize + runtime env) the bytes. So the key should be decoded to + a string. The given decoder is used to decode the function + key. + """ + setup_func = runtime_env.get("worker_process_setup_hook") + + if setup_func is None: + return runtime_env + + if isinstance(setup_func, Callable): + return export_setup_func_callable(runtime_env, setup_func, worker) + elif isinstance(setup_func, str): + return export_setup_func_module(runtime_env, setup_func) + else: + raise TypeError( + "worker_process_setup_hook must be a function, " f"got {type(setup_func)}." + ) + + +def load_and_execute_setup_hook( + worker_process_setup_hook_key: str, +) -> Optional[str]: + """Load the setup hook from a given key and execute. + + Args: + worker_process_setup_hook_key: The key to import the setup hook + from GCS. + Returns: + An error message if it fails. None if it succeeds. + """ + assert worker_process_setup_hook_key is not None + if not worker_process_setup_hook_key.startswith(RUNTIME_ENV_FUNC_IDENTIFIER): + return load_and_execute_setup_hook_module(worker_process_setup_hook_key) + else: + return load_and_execute_setup_hook_func(worker_process_setup_hook_key) + + +def load_and_execute_setup_hook_module( + worker_process_setup_hook_key: str, +) -> Optional[str]: + try: + setup_func = load_class(worker_process_setup_hook_key) + setup_func() + return None + except Exception: + error_message = ( + "Failed to execute the setup hook method, " + f"{worker_process_setup_hook_key} " + "from ``ray.init(runtime_env=" + f"{{'worker_process_setup_hook': {worker_process_setup_hook_key}}})``. " + "Please make sure the given module exists and is available " + "from ray workers. For more details, see the error trace below.\n" + f"{traceback.format_exc()}" + ) + return error_message + + +def load_and_execute_setup_hook_func( + worker_process_setup_hook_key: str, +) -> Optional[str]: + worker = ray._private.worker.global_worker + assert worker.connected + func_manager = worker.function_actor_manager + try: + worker_setup_func_info = func_manager.fetch_registered_method( + _encode_function_key(worker_process_setup_hook_key), + timeout=get_import_export_timeout(), + ) + except Exception: + error_message = ( + "Failed to import setup hook within " + f"{get_import_export_timeout()} seconds.\n" + f"{traceback.format_exc()}" + ) + return error_message + + try: + setup_func = pickle.loads(worker_setup_func_info.function) + except Exception: + error_message = ( + "Failed to deserialize the setup hook method.\n" f"{traceback.format_exc()}" + ) + return error_message + + try: + setup_func() + except Exception: + error_message = ( + f"Failed to execute the setup hook method. Function name:" + f"{worker_setup_func_info.function_name}\n" + f"{traceback.format_exc()}" + ) + return error_message + + return None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uri_cache.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uri_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..430bcf6d7e4e1ffb62e55c7a6d49cf6d0cae0492 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uri_cache.py @@ -0,0 +1,115 @@ +import logging +from typing import Callable, Optional, Set + +default_logger = logging.getLogger(__name__) + +DEFAULT_MAX_URI_CACHE_SIZE_BYTES = (1024**3) * 10 # 10 GB + + +class URICache: + """Caches URIs up to a specified total size limit. + + URIs are represented by strings. Each URI has an associated size on disk. + When a URI is added to the URICache, it is marked as "in use". + When a URI is no longer in use, the user of this class should call + `mark_unused` to signal that the URI is safe for deletion. + + URIs in the cache can be marked as "in use" by calling `mark_used`. + + Deletion of URIs on disk does not occur until the size limit is exceeded. + When this happens, URIs that are not in use are deleted randomly until the + size limit is satisfied, or there are no more URIs that are not in use. + + It is possible for the total size on disk to exceed the size limit if all + the URIs are in use. + + """ + + def __init__( + self, + delete_fn: Optional[Callable[[str, logging.Logger], int]] = None, + max_total_size_bytes: int = DEFAULT_MAX_URI_CACHE_SIZE_BYTES, + debug_mode: bool = False, + ): + # Maps URIs to the size in bytes of their corresponding disk contents. + self._used_uris: Set[str] = set() + self._unused_uris: Set[str] = set() + + if delete_fn is None: + self._delete_fn = lambda uri, logger: 0 + else: + self._delete_fn = delete_fn + + # Total size of both used and unused URIs in the cache. + self._total_size_bytes = 0 + self.max_total_size_bytes = max_total_size_bytes + + # Used in `self._check_valid()` for testing. + self._debug_mode = debug_mode + + def mark_unused(self, uri: str, logger: logging.Logger = default_logger): + """Mark a URI as unused and okay to be deleted.""" + if uri not in self._used_uris: + logger.info(f"URI {uri} is already unused.") + else: + self._unused_uris.add(uri) + self._used_uris.remove(uri) + logger.info(f"Marked URI {uri} unused.") + self._evict_if_needed(logger) + self._check_valid() + + def mark_used(self, uri: str, logger: logging.Logger = default_logger): + """Mark a URI as in use. URIs in use will not be deleted.""" + if uri in self._used_uris: + return + elif uri in self._unused_uris: + self._used_uris.add(uri) + self._unused_uris.remove(uri) + else: + raise ValueError( + f"Got request to mark URI {uri} used, but this " + "URI is not present in the cache." + ) + logger.info(f"Marked URI {uri} used.") + self._check_valid() + + def add(self, uri: str, size_bytes: int, logger: logging.Logger = default_logger): + """Add a URI to the cache and mark it as in use.""" + if uri in self._unused_uris: + self._unused_uris.remove(uri) + + self._used_uris.add(uri) + self._total_size_bytes += size_bytes + + self._evict_if_needed(logger) + self._check_valid() + logger.info(f"Added URI {uri} with size {size_bytes}") + + def get_total_size_bytes(self) -> int: + return self._total_size_bytes + + def _evict_if_needed(self, logger: logging.Logger = default_logger): + """Evict unused URIs (if they exist) until total size <= max size.""" + while ( + self._unused_uris + and self.get_total_size_bytes() > self.max_total_size_bytes + ): + # TODO(architkulkarni): Evict least recently used URI instead + arbitrary_unused_uri = next(iter(self._unused_uris)) + self._unused_uris.remove(arbitrary_unused_uri) + num_bytes_deleted = self._delete_fn(arbitrary_unused_uri, logger) + self._total_size_bytes -= num_bytes_deleted + logger.info( + f"Deleted URI {arbitrary_unused_uri} with size " f"{num_bytes_deleted}." + ) + + def _check_valid(self): + """(Debug mode only) Check "used" and "unused" sets are disjoint.""" + if self._debug_mode: + assert self._used_uris & self._unused_uris == set() + + def __contains__(self, uri): + return uri in self._used_uris or uri in self._unused_uris + + def __repr__(self): + return str(self.__dict__) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a4387ff27b697d4918fdd6c4228a7dfcd7a59cc6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/utils.py @@ -0,0 +1,117 @@ +import asyncio +import itertools +import logging +import subprocess +import textwrap +import types +from typing import List + + +class SubprocessCalledProcessError(subprocess.CalledProcessError): + """The subprocess.CalledProcessError with stripped stdout.""" + + LAST_N_LINES = 50 + + def __init__(self, *args, cmd_index=None, **kwargs): + self.cmd_index = cmd_index + super().__init__(*args, **kwargs) + + @staticmethod + def _get_last_n_line(str_data: str, last_n_lines: int) -> str: + if last_n_lines < 0: + return str_data + lines = str_data.strip().split("\n") + return "\n".join(lines[-last_n_lines:]) + + def __str__(self): + str_list = ( + [] + if self.cmd_index is None + else [f"Run cmd[{self.cmd_index}] failed with the following details."] + ) + str_list.append(super().__str__()) + out = { + "stdout": self.stdout, + "stderr": self.stderr, + } + for name, s in out.items(): + if s: + subtitle = f"Last {self.LAST_N_LINES} lines of {name}:" + last_n_line_str = self._get_last_n_line(s, self.LAST_N_LINES).strip() + str_list.append( + f"{subtitle}\n{textwrap.indent(last_n_line_str, ' ' * 4)}" + ) + return "\n".join(str_list) + + +async def check_output_cmd( + cmd: List[str], + *, + logger: logging.Logger, + cmd_index_gen: types.GeneratorType = itertools.count(1), + **kwargs, +) -> str: + """Run command with arguments and return its output. + + If the return code was non-zero it raises a CalledProcessError. The + CalledProcessError object will have the return code in the returncode + attribute and any output in the output attribute. + + Args: + cmd: The cmdline should be a sequence of program arguments or else + a single string or path-like object. The program to execute is + the first item in cmd. + logger: The logger instance. + cmd_index_gen: The cmd index generator, default is itertools.count(1). + kwargs: All arguments are passed to the create_subprocess_exec. + + Returns: + The stdout of cmd. + + Raises: + CalledProcessError: If the return code of cmd is not 0. + """ + + cmd_index = next(cmd_index_gen) + logger.info("Run cmd[%s] %s", cmd_index, repr(cmd)) + + proc = None + try: + proc = await asyncio.create_subprocess_exec( + *cmd, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.STDOUT, + **kwargs, + ) + # Use communicate instead of polling stdout: + # * Avoid deadlocks due to streams pausing reading or writing and blocking the + # child process. Please refer to: + # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.stderr + # * Avoid mixing multiple outputs of concurrent cmds. + stdout, _ = await proc.communicate() + except asyncio.exceptions.CancelledError as e: + # since Python 3.9, when cancelled, the inner process needs to throw as it is + # for asyncio to timeout properly https://bugs.python.org/issue40607 + raise e + except BaseException as e: + raise RuntimeError(f"Run cmd[{cmd_index}] got exception.") from e + else: + stdout = stdout.decode("utf-8") + if stdout: + logger.info("Output of cmd[%s]: %s", cmd_index, stdout) + else: + logger.info("No output for cmd[%s]", cmd_index) + if proc.returncode != 0: + raise SubprocessCalledProcessError( + proc.returncode, cmd, output=stdout, cmd_index=cmd_index + ) + return stdout + finally: + if proc is not None: + # Kill process. + try: + proc.kill() + except ProcessLookupError: + pass + # Wait process exit. + await proc.wait() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uv.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uv.py new file mode 100644 index 0000000000000000000000000000000000000000..196e0e43bd867ede32a44bb3837fec9adb515324 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uv.py @@ -0,0 +1,346 @@ +"""Util class to install packages via uv. +""" + +import asyncio +import hashlib +import json +import logging +import os +import shutil +import sys +from asyncio import create_task, get_running_loop +from typing import Dict, List, Optional + +from ray._common.utils import try_to_create_directory +from ray._private.runtime_env import dependency_utils, virtualenv_utils +from ray._private.runtime_env.packaging import Protocol, parse_uri +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray._private.runtime_env.utils import check_output_cmd +from ray._private.utils import get_directory_size_bytes + +default_logger = logging.getLogger(__name__) + + +def _get_uv_hash(uv_dict: Dict) -> str: + """Get a deterministic hash value for `uv` related runtime envs.""" + serialized_uv_spec = json.dumps(uv_dict, sort_keys=True) + hash_val = hashlib.sha1(serialized_uv_spec.encode("utf-8")).hexdigest() + return hash_val + + +def get_uri(runtime_env: Dict) -> Optional[str]: + """Return `"uv://"`, or None if no GC required.""" + uv = runtime_env.get("uv") + if uv is not None: + if isinstance(uv, dict): + uri = "uv://" + _get_uv_hash(uv_dict=uv) + elif isinstance(uv, list): + uri = "uv://" + _get_uv_hash(uv_dict=dict(packages=uv)) + else: + raise TypeError( + "uv field received by RuntimeEnvAgent must be " + f"list or dict, not {type(uv).__name__}." + ) + else: + uri = None + return uri + + +class UvProcessor: + def __init__( + self, + target_dir: str, + runtime_env: "RuntimeEnv", # noqa: F821 + logger: Optional[logging.Logger] = default_logger, + ): + try: + import virtualenv # noqa: F401 ensure virtualenv exists. + except ImportError: + raise RuntimeError( + f"Please install virtualenv " + f"`{sys.executable} -m pip install virtualenv`" + f"to enable uv runtime env." + ) + + logger.debug("Setting up uv for runtime_env: %s", runtime_env) + self._target_dir = target_dir + # An empty directory is created to execute cmd. + self._exec_cwd = os.path.join(self._target_dir, "exec_cwd") + self._runtime_env = runtime_env + self._logger = logger + + self._uv_config = self._runtime_env.uv_config() + self._uv_env = os.environ.copy() + self._uv_env.update(self._runtime_env.env_vars()) + + async def _install_uv( + self, path: str, cwd: str, pip_env: dict, logger: logging.Logger + ): + """Before package install, make sure the required version `uv` (if specifieds) + is installed. + """ + virtualenv_path = virtualenv_utils.get_virtualenv_path(path) + python = virtualenv_utils.get_virtualenv_python(path) + + def _get_uv_exec_to_install() -> str: + """Get `uv` executable with version to install.""" + uv_version = self._uv_config.get("uv_version", None) + if uv_version: + return f"uv{uv_version}" + # Use default version. + return "uv" + + uv_install_cmd = [ + python, + "-m", + "pip", + "install", + "--disable-pip-version-check", + "--no-cache-dir", + _get_uv_exec_to_install(), + ] + logger.info("Installing package uv to %s", virtualenv_path) + await check_output_cmd(uv_install_cmd, logger=logger, cwd=cwd, env=pip_env) + + async def _check_uv_existence( + self, path: str, cwd: str, env: dict, logger: logging.Logger + ) -> bool: + """Check and return the existence of `uv` in virtual env.""" + python = virtualenv_utils.get_virtualenv_python(path) + + check_existence_cmd = [ + python, + "-m", + "uv", + "version", + ] + + try: + # If `uv` doesn't exist, exception will be thrown. + await check_output_cmd(check_existence_cmd, logger=logger, cwd=cwd, env=env) + return True + except Exception: + return False + + async def _uv_check(sef, python: str, cwd: str, logger: logging.Logger) -> None: + """Check virtual env dependency compatibility. + If any incompatibility detected, exception will be thrown. + + param: + python: the path for python executable within virtual environment. + """ + cmd = [python, "-m", "uv", "pip", "check"] + await check_output_cmd( + cmd, + logger=logger, + cwd=cwd, + ) + + async def _install_uv_packages( + self, + path: str, + uv_packages: List[str], + cwd: str, + pip_env: Dict, + logger: logging.Logger, + ): + """Install required python packages via `uv`.""" + virtualenv_path = virtualenv_utils.get_virtualenv_path(path) + python = virtualenv_utils.get_virtualenv_python(path) + # TODO(fyrestone): Support -i, --no-deps, --no-cache-dir, ... + requirements_file = dependency_utils.get_requirements_file(path, uv_packages) + + # Check existence for `uv` and see if we could skip `uv` installation. + uv_exists = await self._check_uv_existence(python, cwd, pip_env, logger) + + # Install uv, which acts as the default package manager. + if (not uv_exists) or (self._uv_config.get("uv_version", None) is not None): + await self._install_uv(path, cwd, pip_env, logger) + + # Avoid blocking the event loop. + loop = get_running_loop() + await loop.run_in_executor( + None, dependency_utils.gen_requirements_txt, requirements_file, uv_packages + ) + + # Install all dependencies. + # + # Difference with pip: + # 1. `--disable-pip-version-check` has no effect for uv. + # 2. Allow user to specify their own options to install packages via `uv`. + uv_install_cmd = [ + python, + "-m", + "uv", + "pip", + "install", + "-r", + requirements_file, + ] + + uv_opt_list = self._uv_config.get("uv_pip_install_options", ["--no-cache"]) + if uv_opt_list: + uv_install_cmd += uv_opt_list + + logger.info("Installing python requirements to %s", virtualenv_path) + await check_output_cmd(uv_install_cmd, logger=logger, cwd=cwd, env=pip_env) + + # Check python environment for conflicts. + if self._uv_config.get("uv_check", False): + await self._uv_check(python, cwd, logger) + + async def _run(self): + path = self._target_dir + logger = self._logger + uv_packages = self._uv_config["packages"] + # We create an empty directory for exec cmd so that the cmd will + # run more stable. e.g. if cwd has ray, then checking ray will + # look up ray in cwd instead of site packages. + os.makedirs(self._exec_cwd, exist_ok=True) + try: + await virtualenv_utils.create_or_get_virtualenv( + path, self._exec_cwd, logger + ) + python = virtualenv_utils.get_virtualenv_python(path) + async with dependency_utils.check_ray(python, self._exec_cwd, logger): + # Install packages with uv. + await self._install_uv_packages( + path, + uv_packages, + self._exec_cwd, + self._uv_env, + logger, + ) + except Exception: + logger.info("Delete incomplete virtualenv: %s", path) + shutil.rmtree(path, ignore_errors=True) + logger.exception("Failed to install uv packages.") + raise + + def __await__(self): + return self._run().__await__() + + +class UvPlugin(RuntimeEnvPlugin): + name = "uv" + + def __init__(self, resources_dir: str): + self._uv_resource_dir = os.path.join(resources_dir, "uv") + self._creating_task = {} + # Maps a URI to a lock that is used to prevent multiple concurrent + # installs of the same virtualenv, see #24513 + self._create_locks: Dict[str, asyncio.Lock] = {} + # Key: created hashes. Value: size of the uv dir. + self._created_hash_bytes: Dict[str, int] = {} + try_to_create_directory(self._uv_resource_dir) + + def _get_path_from_hash(self, hash_val: str) -> str: + """Generate a path from the hash of a uv spec. + + Example output: + /tmp/ray/session_2021-11-03_16-33-59_356303_41018/runtime_resources + /uv/ray-9a7972c3a75f55e976e620484f58410c920db091 + """ + return os.path.join(self._uv_resource_dir, hash_val) + + def get_uris(self, runtime_env: "RuntimeEnv") -> List[str]: # noqa: F821 + """Return the uv URI from the RuntimeEnv if it exists, else return [].""" + uv_uri = runtime_env.uv_uri() + if uv_uri: + return [uv_uri] + return [] + + def delete_uri( + self, uri: str, logger: Optional[logging.Logger] = default_logger + ) -> int: + """Delete URI and return the number of bytes deleted.""" + logger.info("Got request to delete uv URI %s", uri) + protocol, hash_val = parse_uri(uri) + if protocol != Protocol.UV: + raise ValueError( + "UvPlugin can only delete URIs with protocol " + f"uv. Received protocol {protocol}, URI {uri}" + ) + + # Cancel running create task. + task = self._creating_task.pop(hash_val, None) + if task is not None: + task.cancel() + + del self._created_hash_bytes[hash_val] + + uv_env_path = self._get_path_from_hash(hash_val) + local_dir_size = get_directory_size_bytes(uv_env_path) + del self._create_locks[uri] + try: + shutil.rmtree(uv_env_path) + except OSError as e: + logger.warning(f"Error when deleting uv env {uv_env_path}: {str(e)}") + return 0 + + return local_dir_size + + async def create( + self, + uri: str, + runtime_env: "RuntimeEnv", # noqa: F821 + context: "RuntimeEnvContext", # noqa: F821 + logger: Optional[logging.Logger] = default_logger, + ) -> int: + if not runtime_env.has_uv(): + return 0 + + protocol, hash_val = parse_uri(uri) + target_dir = self._get_path_from_hash(hash_val) + + async def _create_for_hash(): + await UvProcessor( + target_dir, + runtime_env, + logger, + ) + + loop = get_running_loop() + return await loop.run_in_executor( + None, get_directory_size_bytes, target_dir + ) + + if uri not in self._create_locks: + # async lock to prevent the same virtualenv being concurrently installed + self._create_locks[uri] = asyncio.Lock() + + async with self._create_locks[uri]: + if hash_val in self._created_hash_bytes: + return self._created_hash_bytes[hash_val] + self._creating_task[hash_val] = task = create_task(_create_for_hash()) + task.add_done_callback(lambda _: self._creating_task.pop(hash_val, None)) + uv_dir_bytes = await task + self._created_hash_bytes[hash_val] = uv_dir_bytes + return uv_dir_bytes + + def modify_context( + self, + uris: List[str], + runtime_env: "RuntimeEnv", # noqa: F821 + context: "RuntimeEnvContext", # noqa: F821 + logger: logging.Logger = default_logger, + ): + if not runtime_env.has_uv(): + return + # UvPlugin only uses a single URI. + uri = uris[0] + # Update py_executable. + protocol, hash_val = parse_uri(uri) + target_dir = self._get_path_from_hash(hash_val) + virtualenv_python = virtualenv_utils.get_virtualenv_python(target_dir) + + if not os.path.exists(virtualenv_python): + raise ValueError( + f"Local directory {target_dir} for URI {uri} does " + "not exist on the cluster. Something may have gone wrong while " + "installing the runtime_env `uv` packages." + ) + context.py_executable = virtualenv_python + context.command_prefix += virtualenv_utils.get_virtualenv_activate_command( + target_dir + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uv_runtime_env_hook.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uv_runtime_env_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..7a72107872f07ab5a1901bcbe07a569612a7c07f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/uv_runtime_env_hook.py @@ -0,0 +1,383 @@ +import argparse +import copy +import optparse +import os +import sys +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple + +import psutil + + +def _create_uv_run_parser(): + """Create and return the argument parser for 'uv run' command.""" + + parser = optparse.OptionParser(prog="uv run", add_help_option=False) + + # Disable interspersed args to stop parsing when we hit the first + # argument that is not recognized by the parser. + parser.disable_interspersed_args() + + # Main options group + main_group = optparse.OptionGroup(parser, "Main options") + main_group.add_option("--extra", action="append", dest="extras") + main_group.add_option("--all-extras", action="store_true") + main_group.add_option("--no-extra", action="append", dest="no_extras") + main_group.add_option("--no-dev", action="store_true") + main_group.add_option("--group", action="append", dest="groups") + main_group.add_option("--no-group", action="append", dest="no_groups") + main_group.add_option("--no-default-groups", action="store_true") + main_group.add_option("--only-group", action="append", dest="only_groups") + main_group.add_option("--all-groups", action="store_true") + main_group.add_option("-m", "--module") + main_group.add_option("--only-dev", action="store_true") + main_group.add_option("--no-editable", action="store_true") + main_group.add_option("--exact", action="store_true") + main_group.add_option("--env-file", action="append", dest="env_files") + main_group.add_option("--no-env-file", action="store_true") + parser.add_option_group(main_group) + + # With options + with_group = optparse.OptionGroup(parser, "With options") + with_group.add_option("--with", action="append", dest="with_packages") + with_group.add_option("--with-editable", action="append", dest="with_editable") + with_group.add_option( + "--with-requirements", action="append", dest="with_requirements" + ) + parser.add_option_group(with_group) + + # Environment options + env_group = optparse.OptionGroup(parser, "Environment options") + env_group.add_option("--isolated", action="store_true") + env_group.add_option("--active", action="store_true") + env_group.add_option("--no-sync", action="store_true") + env_group.add_option("--locked", action="store_true") + env_group.add_option("--frozen", action="store_true") + parser.add_option_group(env_group) + + # Script options + script_group = optparse.OptionGroup(parser, "Script options") + script_group.add_option("-s", "--script", action="store_true") + script_group.add_option("--gui-script", action="store_true") + parser.add_option_group(script_group) + + # Workspace options + workspace_group = optparse.OptionGroup(parser, "Workspace options") + workspace_group.add_option("--all-packages", action="store_true") + workspace_group.add_option("--package") + workspace_group.add_option("--no-project", action="store_true") + parser.add_option_group(workspace_group) + + # Index options + index_group = optparse.OptionGroup(parser, "Index options") + index_group.add_option("--index", action="append", dest="indexes") + index_group.add_option("--default-index") + index_group.add_option("-i", "--index-url") + index_group.add_option( + "--extra-index-url", action="append", dest="extra_index_urls" + ) + index_group.add_option("-f", "--find-links", action="append", dest="find_links") + index_group.add_option("--no-index", action="store_true") + index_group.add_option( + "--index-strategy", + type="choice", + choices=["first-index", "unsafe-first-match", "unsafe-best-match"], + ) + index_group.add_option( + "--keyring-provider", type="choice", choices=["disabled", "subprocess"] + ) + parser.add_option_group(index_group) + + # Resolver options + resolver_group = optparse.OptionGroup(parser, "Resolver options") + resolver_group.add_option("-U", "--upgrade", action="store_true") + resolver_group.add_option( + "-P", "--upgrade-package", action="append", dest="upgrade_packages" + ) + resolver_group.add_option( + "--resolution", type="choice", choices=["highest", "lowest", "lowest-direct"] + ) + resolver_group.add_option( + "--prerelease", + type="choice", + choices=[ + "disallow", + "allow", + "if-necessary", + "explicit", + "if-necessary-or-explicit", + ], + ) + resolver_group.add_option( + "--fork-strategy", type="choice", choices=["fewest", "requires-python"] + ) + resolver_group.add_option("--exclude-newer") + resolver_group.add_option("--no-sources", action="store_true") + parser.add_option_group(resolver_group) + + # Installer options + installer_group = optparse.OptionGroup(parser, "Installer options") + installer_group.add_option("--reinstall", action="store_true") + installer_group.add_option( + "--reinstall-package", action="append", dest="reinstall_packages" + ) + installer_group.add_option( + "--link-mode", type="choice", choices=["clone", "copy", "hardlink", "symlink"] + ) + installer_group.add_option("--compile-bytecode", action="store_true") + parser.add_option_group(installer_group) + + # Build options + build_group = optparse.OptionGroup(parser, "Build options") + build_group.add_option( + "-C", "--config-setting", action="append", dest="config_settings" + ) + build_group.add_option("--no-build-isolation", action="store_true") + build_group.add_option( + "--no-build-isolation-package", + action="append", + dest="no_build_isolation_packages", + ) + build_group.add_option("--no-build", action="store_true") + build_group.add_option( + "--no-build-package", action="append", dest="no_build_packages" + ) + build_group.add_option("--no-binary", action="store_true") + build_group.add_option( + "--no-binary-package", action="append", dest="no_binary_packages" + ) + parser.add_option_group(build_group) + + # Cache options + cache_group = optparse.OptionGroup(parser, "Cache options") + cache_group.add_option("-n", "--no-cache", action="store_true") + cache_group.add_option("--cache-dir") + cache_group.add_option("--refresh", action="store_true") + cache_group.add_option( + "--refresh-package", action="append", dest="refresh_packages" + ) + parser.add_option_group(cache_group) + + # Python options + python_group = optparse.OptionGroup(parser, "Python options") + python_group.add_option("-p", "--python") + python_group.add_option("--managed-python", action="store_true") + python_group.add_option("--no-managed-python", action="store_true") + python_group.add_option("--no-python-downloads", action="store_true") + # note: the following is a legacy option and will be removed at some point + # https://github.com/astral-sh/uv/pull/12246 + python_group.add_option( + "--python-preference", + type="choice", + choices=["only-managed", "managed", "system", "only-system"], + ) + parser.add_option_group(python_group) + + # Global options + global_group = optparse.OptionGroup(parser, "Global options") + global_group.add_option("-q", "--quiet", action="count", default=0) + global_group.add_option("-v", "--verbose", action="count", default=0) + global_group.add_option( + "--color", type="choice", choices=["auto", "always", "never"] + ) + global_group.add_option("--native-tls", action="store_true") + global_group.add_option("--offline", action="store_true") + global_group.add_option( + "--allow-insecure-host", action="append", dest="insecure_hosts" + ) + global_group.add_option("--no-progress", action="store_true") + global_group.add_option("--directory") + global_group.add_option("--project") + global_group.add_option("--config-file") + global_group.add_option("--no-config", action="store_true") + parser.add_option_group(global_group) + + return parser + + +def _parse_args( + parser: optparse.OptionParser, args: List[str] +) -> Tuple[optparse.Values, List[str]]: + """ + Parse the command-line options found in 'args'. + + Replacement for parser.parse_args that handles unknown arguments + by keeping them in the command list instead of erroring and + discarding them. + """ + parser.rargs = args + parser.largs = [] + options = parser.get_default_values() + try: + parser._process_args(parser.largs, parser.rargs, options) + except optparse.BadOptionError as err: + # If we hit an argument that is not recognized, we put it + # back into the unconsumed arguments + parser.rargs = [err.opt_str] + parser.rargs + return options, parser.rargs + + +def _check_working_dir_files( + uv_run_args: optparse.Values, runtime_env: Dict[str, Any] +) -> None: + """ + Check that the files required by uv are local to the working_dir. This catches + the most common cases of how things are different in Ray, i.e. not the whole file + system will be available on the workers, only the working_dir. + + The function won't return anything, it just raises a RuntimeError if there is an error. + """ + working_dir = Path(runtime_env["working_dir"]).resolve() + + # Check if the requirements.txt file is in the working_dir + if uv_run_args.with_requirements: + for requirements_file in uv_run_args.with_requirements: + if not Path(requirements_file).resolve().is_relative_to(working_dir): + raise RuntimeError( + f"You specified --with-requirements={uv_run_args.with_requirements} but " + f"the requirements file is not in the working_dir {runtime_env['working_dir']}, " + "so the workers will not have access to the file. Make sure " + "the requirements file is in the working directory. " + "You can do so by specifying --directory in 'uv run', by changing the current " + "working directory before running 'uv run', or by using the 'working_dir' " + "parameter of the runtime_environment." + ) + + # Check if the pyproject.toml file is in the working_dir + pyproject = None + if uv_run_args.no_project: + pyproject = None + elif uv_run_args.project: + pyproject = Path(uv_run_args.project) + else: + # Walk up the directory tree until pyproject.toml is found + current_path = Path.cwd().resolve() + while current_path != current_path.parent: + if (current_path / "pyproject.toml").exists(): + pyproject = Path(current_path / "pyproject.toml") + break + current_path = current_path.parent + + if pyproject and not pyproject.resolve().is_relative_to(working_dir): + raise RuntimeError( + f"Your {pyproject.resolve()} is not in the working_dir {runtime_env['working_dir']}, " + "so the workers will not have access to the file. Make sure " + "the pyproject.toml file is in the working directory. " + "You can do so by specifying --directory in 'uv run', by changing the current " + "working directory before running 'uv run', or by using the 'working_dir' " + "parameter of the runtime_environment." + ) + + +def _get_uv_run_cmdline() -> Optional[List[str]]: + """ + Return the command line of the first ancestor process that was run with + "uv run" and None if there is no such ancestor. + + uv spawns the python process as a child process, so we first check the + parent process command line. We also check our parent's parents since + the Ray driver might be run as a subprocess of the 'uv run' process. + """ + parents = psutil.Process().parents() + for parent in parents: + try: + cmdline = parent.cmdline() + if ( + len(cmdline) > 1 + and os.path.basename(cmdline[0]) == "uv" + and cmdline[1] == "run" + ): + return cmdline + except psutil.NoSuchProcess: + continue + except psutil.AccessDenied: + continue + return None + + +def hook(runtime_env: Optional[Dict[str, Any]]) -> Dict[str, Any]: + """Hook that detects if the driver is run in 'uv run' and sets the runtime environment accordingly.""" + + runtime_env = copy.deepcopy(runtime_env) or {} + + cmdline = _get_uv_run_cmdline() + if not cmdline: + # This means the driver was not run in a 'uv run' environment -- in this case + # we leave the runtime environment unchanged + return runtime_env + + # First check that the "uv" and "pip" runtime environments are not used. + if "uv" in runtime_env or "pip" in runtime_env: + raise RuntimeError( + "You are using the 'pip' or 'uv' runtime environments together with " + "'uv run'. These are not compatible since 'uv run' will run the workers " + "in an isolated environment -- please add the 'pip' or 'uv' dependencies to your " + "'uv run' environment e.g. by including them in your pyproject.toml." + ) + + # Extract the arguments uv_run_args of 'uv run' that are not part of the command. + parser = _create_uv_run_parser() + (options, command) = _parse_args(parser, cmdline[2:]) + + if cmdline[-len(command) :] != command: + raise AssertionError( + f"uv run command {command} is not a suffix of command line {cmdline}" + ) + uv_run_args = cmdline[: -len(command)] + + # Remove the "--directory" argument since it has already been taken into + # account when setting the current working directory of the current process. + # Also remove the "--module" argument, since the default_worker.py is + # invoked as a script and not as a module. + parser = argparse.ArgumentParser() + parser.add_argument("--directory") + parser.add_argument("-m", "--module") + _, remaining_uv_run_args = parser.parse_known_args(uv_run_args) + + runtime_env["py_executable"] = " ".join(remaining_uv_run_args) + + # If the user specified a working_dir, we always honor it, otherwise + # use the same working_dir that uv run would use + if "working_dir" not in runtime_env: + runtime_env["working_dir"] = os.getcwd() + _check_working_dir_files(options, runtime_env) + + return runtime_env + + +# This __main__ is used for unit testing if the runtime_env_hook picks up the +# right settings. +if __name__ == "__main__": + import json + + test_parser = argparse.ArgumentParser() + test_parser.add_argument("--extra-args", action="store_true") + test_parser.add_argument("runtime_env") + args = test_parser.parse_args() + + # If the env variable is set, add one more level of subprocess indirection + if os.environ.get("RAY_TEST_UV_ADD_SUBPROCESS_INDIRECTION") == "1": + import subprocess + + env = os.environ.copy() + env.pop("RAY_TEST_UV_ADD_SUBPROCESS_INDIRECTION") + subprocess.check_call([sys.executable] + sys.argv, env=env) + sys.exit(0) + + # If the following env variable is set, we use multiprocessing + # spawn to start the subprocess, since it uses a different way to + # modify the command line than subprocess.check_call + if os.environ.get("RAY_TEST_UV_MULTIPROCESSING_SPAWN") == "1": + import multiprocessing + + multiprocessing.set_start_method("spawn") + pool = multiprocessing.Pool(processes=1) + runtime_env = json.loads(args.runtime_env) + print(json.dumps(pool.apply(hook, (runtime_env,)))) + sys.exit(0) + + # We purposefully modify sys.argv here to make sure the hook is robust + # against such modification. + sys.argv.pop(1) + runtime_env = json.loads(args.runtime_env) + print(json.dumps(hook(runtime_env))) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/validation.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/validation.py new file mode 100644 index 0000000000000000000000000000000000000000..214604c42940968775af4711bb3136cdf441a83d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/validation.py @@ -0,0 +1,438 @@ +import logging +import sys +from collections import OrderedDict +from pathlib import Path +from typing import Dict, List, Optional, Union + +import yaml + +from ray._private.path_utils import is_path +from ray._private.runtime_env.packaging import parse_path + +logger = logging.getLogger(__name__) + + +def validate_path(path: str) -> None: + """Parse the path to ensure it is well-formed and exists.""" + parse_path(path) + + +def validate_uri(uri: str): + try: + from ray._private.runtime_env.packaging import Protocol, parse_uri + + protocol, path = parse_uri(uri) + except ValueError: + raise ValueError( + f"{uri} is not a valid URI. Passing directories or modules to " + "be dynamically uploaded is only supported at the job level " + "(i.e., passed to `ray.init`)." + ) + + if ( + protocol in Protocol.remote_protocols() + and not path.endswith(".zip") + and not path.endswith(".whl") + ): + raise ValueError("Only .zip or .whl files supported for remote URIs.") + + +def _handle_local_deps_requirement_file(requirements_file: str): + """Read the given [requirements_file], and return all required dependencies.""" + requirements_path = Path(requirements_file) + if not requirements_path.is_file(): + raise ValueError(f"{requirements_path} is not a valid file") + return requirements_path.read_text().strip().split("\n") + + +def validate_py_modules_uris(py_modules_uris: List[str]) -> List[str]: + """Parses and validates a 'py_modules' option. + + Expects py_modules to be a list of URIs. + """ + if not isinstance(py_modules_uris, list): + raise TypeError( + "`py_modules` must be a list of strings, got " f"{type(py_modules_uris)}." + ) + + for module in py_modules_uris: + + if not isinstance(module, str): + raise TypeError("`py_module` must be a string, got " f"{type(module)}.") + + validate_uri(module) + + +def parse_and_validate_py_modules(py_modules: List[str]) -> List[str]: + """Parses and validates a 'py_modules' option. + + Expects py_modules to be a list of local paths or URIs. + """ + if not isinstance(py_modules, list): + raise TypeError( + "`py_modules` must be a list of strings, got " f"{type(py_modules)}." + ) + + for module in py_modules: + + if not isinstance(module, str): + raise TypeError("`py_module` must be a string, got " f"{type(module)}.") + + if is_path(module): + validate_path(module) + else: + validate_uri(module) + + return py_modules + + +def validate_working_dir_uri(working_dir_uri: str) -> str: + """Parses and validates a 'working_dir' option.""" + if not isinstance(working_dir_uri, str): + raise TypeError( + "`working_dir` must be a string, got " f"{type(working_dir_uri)}." + ) + + validate_uri(working_dir_uri) + + +def parse_and_validate_working_dir(working_dir: str) -> str: + """Parses and validates a 'working_dir' option. + + This can be a URI or a path. + """ + assert working_dir is not None + + if not isinstance(working_dir, str): + raise TypeError("`working_dir` must be a string, got " f"{type(working_dir)}.") + + if is_path(working_dir): + validate_path(working_dir) + else: + validate_uri(working_dir) + + return working_dir + + +def parse_and_validate_conda(conda: Union[str, dict]) -> Union[str, dict]: + """Parses and validates a user-provided 'conda' option. + + Conda can be one of three cases: + 1) A dictionary describing the env. This is passed through directly. + 2) A string referring to the name of a preinstalled conda env. + 3) A string pointing to a local conda YAML file. This is detected + by looking for a '.yaml' or '.yml' suffix. In this case, the file + will be read as YAML and passed through as a dictionary. + """ + assert conda is not None + + if sys.platform == "win32": + logger.warning( + "runtime environment support is experimental on Windows. " + "If you run into issues please file a report at " + "https://github.com/ray-project/ray/issues." + ) + + result = conda + if isinstance(conda, str): + file_path = Path(conda) + if file_path.suffix in (".yaml", ".yml"): + if not file_path.is_file(): + raise ValueError(f"Can't find conda YAML file {file_path}.") + try: + result = yaml.safe_load(file_path.read_text()) + except Exception as e: + raise ValueError(f"Failed to read conda file {file_path}: {e}.") + elif file_path.is_absolute(): + if not file_path.is_dir(): + raise ValueError(f"Can't find conda env directory {file_path}.") + result = str(file_path) + elif isinstance(conda, dict): + result = conda + else: + raise TypeError( + "runtime_env['conda'] must be of type str or " f"dict, got {type(conda)}." + ) + + return result + + +def parse_and_validate_uv(uv: Union[str, List[str], Dict]) -> Optional[Dict]: + """Parses and validates a user-provided 'uv' option. + + The value of the input 'uv' field can be one of two cases: + 1) A List[str] describing the requirements. This is passed through. + Example usage: ["tensorflow", "requests"] + 2) a string containing the path to a local pip “requirements.txt” file. + 3) A python dictionary that has one field: + a) packages (required, List[str]): a list of uv packages, it same as 1). + b) uv_check (optional, bool): whether to enable pip check at the end of uv + install, default to False. + c) uv_version (optional, str): user provides a specific uv to use; if + unspecified, default version of uv will be used. + d) uv_pip_install_options (optional, List[str]): user-provided options for + `uv pip install` command, default to ["--no-cache"]. + + The returned parsed value will be a list of packages. If a Ray library + (e.g. "ray[serve]") is specified, it will be deleted and replaced by its + dependencies (e.g. "uvicorn", "requests"). + """ + assert uv is not None + if sys.platform == "win32": + logger.warning( + "runtime environment support is experimental on Windows. " + "If you run into issues please file a report at " + "https://github.com/ray-project/ray/issues." + ) + + result: str = "" + if isinstance(uv, str): + uv_list = _handle_local_deps_requirement_file(uv) + result = dict(packages=uv_list, uv_check=False) + elif isinstance(uv, list) and all(isinstance(dep, str) for dep in uv): + result = dict(packages=uv, uv_check=False) + elif isinstance(uv, dict): + if set(uv.keys()) - { + "packages", + "uv_check", + "uv_version", + "uv_pip_install_options", + }: + raise ValueError( + "runtime_env['uv'] can only have these fields: " + "packages, uv_check, uv_version and uv_pip_install_options, but got: " + f"{list(uv.keys())}" + ) + if "packages" not in uv: + raise ValueError( + f"runtime_env['uv'] must include field 'packages', but got {uv}" + ) + if "uv_check" in uv and not isinstance(uv["uv_check"], bool): + raise TypeError( + "runtime_env['uv']['uv_check'] must be of type bool, " + f"got {type(uv['uv_check'])}" + ) + if "uv_version" in uv and not isinstance(uv["uv_version"], str): + raise TypeError( + "runtime_env['uv']['uv_version'] must be of type str, " + f"got {type(uv['uv_version'])}" + ) + if "uv_pip_install_options" in uv: + if not isinstance(uv["uv_pip_install_options"], list): + raise TypeError( + "runtime_env['uv']['uv_pip_install_options'] must be of type " + f"list[str] got {type(uv['uv_pip_install_options'])}" + ) + # Check each item in installation option. + for idx, cur_opt in enumerate(uv["uv_pip_install_options"]): + if not isinstance(cur_opt, str): + raise TypeError( + "runtime_env['uv']['uv_pip_install_options'] must be of type " + f"list[str] got {type(cur_opt)} for {idx}-th item." + ) + + result = uv.copy() + result["uv_check"] = uv.get("uv_check", False) + result["uv_pip_install_options"] = uv.get( + "uv_pip_install_options", ["--no-cache"] + ) + if not isinstance(uv["packages"], list): + raise ValueError( + "runtime_env['uv']['packages'] must be of type list, " + f"got: {type(uv['packages'])}" + ) + else: + raise TypeError( + "runtime_env['uv'] must be of type " f"List[str], or dict, got {type(uv)}" + ) + + # Deduplicate packages for package lists. + result["packages"] = list(OrderedDict.fromkeys(result["packages"])) + + if len(result["packages"]) == 0: + result = None + logger.debug(f"Rewrote runtime_env `uv` field from {uv} to {result}.") + return result + + +def parse_and_validate_pip(pip: Union[str, List[str], Dict]) -> Optional[Dict]: + """Parses and validates a user-provided 'pip' option. + + The value of the input 'pip' field can be one of two cases: + 1) A List[str] describing the requirements. This is passed through. + 2) A string pointing to a local requirements file. In this case, the + file contents will be read split into a list. + 3) A python dictionary that has three fields: + a) packages (required, List[str]): a list of pip packages, it same as 1). + b) pip_check (optional, bool): whether to enable pip check at the end of pip + install, default to False. + c) pip_version (optional, str): the version of pip, ray will spell + the package name 'pip' in front of the `pip_version` to form the final + requirement string, the syntax of a requirement specifier is defined in + full in PEP 508. + + The returned parsed value will be a list of pip packages. If a Ray library + (e.g. "ray[serve]") is specified, it will be deleted and replaced by its + dependencies (e.g. "uvicorn", "requests"). + """ + assert pip is not None + + result = None + if sys.platform == "win32": + logger.warning( + "runtime environment support is experimental on Windows. " + "If you run into issues please file a report at " + "https://github.com/ray-project/ray/issues." + ) + if isinstance(pip, str): + # We have been given a path to a requirements.txt file. + pip_list = _handle_local_deps_requirement_file(pip) + result = dict(packages=pip_list, pip_check=False) + elif isinstance(pip, list) and all(isinstance(dep, str) for dep in pip): + result = dict(packages=pip, pip_check=False) + elif isinstance(pip, dict): + if set(pip.keys()) - {"packages", "pip_check", "pip_version"}: + raise ValueError( + "runtime_env['pip'] can only have these fields: " + "packages, pip_check and pip_version, but got: " + f"{list(pip.keys())}" + ) + + if "pip_check" in pip and not isinstance(pip["pip_check"], bool): + raise TypeError( + "runtime_env['pip']['pip_check'] must be of type bool, " + f"got {type(pip['pip_check'])}" + ) + if "pip_version" in pip: + if not isinstance(pip["pip_version"], str): + raise TypeError( + "runtime_env['pip']['pip_version'] must be of type str, " + f"got {type(pip['pip_version'])}" + ) + result = pip.copy() + result["pip_check"] = pip.get("pip_check", False) + if "packages" not in pip: + raise ValueError( + f"runtime_env['pip'] must include field 'packages', but got {pip}" + ) + elif isinstance(pip["packages"], str): + result["packages"] = _handle_local_deps_requirement_file(pip["packages"]) + elif not isinstance(pip["packages"], list): + raise ValueError( + "runtime_env['pip']['packages'] must be of type str of list, " + f"got: {type(pip['packages'])}" + ) + else: + raise TypeError( + "runtime_env['pip'] must be of type str or " f"List[str], got {type(pip)}" + ) + + # Eliminate duplicates to prevent `pip install` from erroring. Use + # OrderedDict to preserve the order of the list. This makes the output + # deterministic and easier to debug, because pip install can have + # different behavior depending on the order of the input. + result["packages"] = list(OrderedDict.fromkeys(result["packages"])) + + if len(result["packages"]) == 0: + result = None + + logger.debug(f"Rewrote runtime_env `pip` field from {pip} to {result}.") + + return result + + +def parse_and_validate_container(container: List[str]) -> List[str]: + """Parses and validates a user-provided 'container' option. + + This is passed through without validation (for now). + """ + assert container is not None + return container + + +def parse_and_validate_excludes(excludes: List[str]) -> List[str]: + """Parses and validates a user-provided 'excludes' option. + + This is validated to verify that it is of type List[str]. + + If an empty list is passed, we return `None` for consistency. + """ + assert excludes is not None + + if isinstance(excludes, list) and len(excludes) == 0: + return None + + if isinstance(excludes, list) and all(isinstance(path, str) for path in excludes): + return excludes + else: + raise TypeError( + "runtime_env['excludes'] must be of type " + f"List[str], got {type(excludes)}" + ) + + +def parse_and_validate_env_vars(env_vars: Dict[str, str]) -> Optional[Dict[str, str]]: + """Parses and validates a user-provided 'env_vars' option. + + This is validated to verify that all keys and vals are strings. + + If an empty dictionary is passed, we return `None` for consistency. + + Args: + env_vars: A dictionary of environment variables to set in the + runtime environment. + + Returns: + The validated env_vars dictionary, or None if it was empty. + + Raises: + TypeError: If the env_vars is not a dictionary of strings. The error message + will include the type of the invalid value. + """ + assert env_vars is not None + if len(env_vars) == 0: + return None + + if not isinstance(env_vars, dict): + raise TypeError( + "runtime_env['env_vars'] must be of type " + f"Dict[str, str], got {type(env_vars)}" + ) + + for key, val in env_vars.items(): + if not isinstance(key, str): + raise TypeError( + "runtime_env['env_vars'] must be of type " + f"Dict[str, str], but the key {key} is of type {type(key)}" + ) + if not isinstance(val, str): + raise TypeError( + "runtime_env['env_vars'] must be of type " + f"Dict[str, str], but the value {val} is of type {type(val)}" + ) + + return env_vars + + +# Dictionary mapping runtime_env options with the function to parse and +# validate them. +OPTION_TO_VALIDATION_FN = { + "py_modules": parse_and_validate_py_modules, + "working_dir": parse_and_validate_working_dir, + "excludes": parse_and_validate_excludes, + "conda": parse_and_validate_conda, + "pip": parse_and_validate_pip, + "uv": parse_and_validate_uv, + "env_vars": parse_and_validate_env_vars, + "container": parse_and_validate_container, +} + +# RuntimeEnv can be created with local paths +# for these options. However, after the packages +# for these options have been uploaded to GCS, +# they must be URIs. These functions provide the ability +# to validate that these options only contain well-formed URIs. +OPTION_TO_NO_PATH_VALIDATION_FN = { + "working_dir": validate_working_dir_uri, + "py_modules": validate_py_modules_uris, +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/virtualenv_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/virtualenv_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..afd3daa352ba07b894926c4cc8df8031fa382411 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/virtualenv_utils.py @@ -0,0 +1,110 @@ +"""Utils to detect runtime environment.""" + +import logging +import os +import sys +from typing import List + +from ray._private.runtime_env.utils import check_output_cmd + +_WIN32 = os.name == "nt" + + +def is_in_virtualenv() -> bool: + # virtualenv <= 16.7.9 sets the real_prefix, + # virtualenv > 16.7.9 & venv set the base_prefix. + # So, we check both of them here. + # https://github.com/pypa/virtualenv/issues/1622#issuecomment-586186094 + return hasattr(sys, "real_prefix") or ( + hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix + ) + + +def get_virtualenv_path(target_dir: str) -> str: + """Get virtual environment path.""" + return os.path.join(target_dir, "virtualenv") + + +def get_virtualenv_python(target_dir: str) -> str: + virtualenv_path = get_virtualenv_path(target_dir) + if _WIN32: + return os.path.join(virtualenv_path, "Scripts", "python.exe") + else: + return os.path.join(virtualenv_path, "bin", "python") + + +def get_virtualenv_activate_command(target_dir: str) -> List[str]: + """Get the command to activate virtual environment.""" + virtualenv_path = get_virtualenv_path(target_dir) + if _WIN32: + cmd = [os.path.join(virtualenv_path, "Scripts", "activate.bat")] + else: + cmd = ["source", os.path.join(virtualenv_path, "bin/activate")] + return cmd + ["1>&2", "&&"] + + +async def create_or_get_virtualenv(path: str, cwd: str, logger: logging.Logger): + """Create or get a virtualenv from path.""" + python = sys.executable + virtualenv_path = os.path.join(path, "virtualenv") + virtualenv_app_data_path = os.path.join(path, "virtualenv_app_data") + + if _WIN32: + current_python_dir = sys.prefix + env = os.environ.copy() + else: + current_python_dir = os.path.abspath( + os.path.join(os.path.dirname(python), "..") + ) + env = {} + + if is_in_virtualenv(): + # virtualenv-clone homepage: + # https://github.com/edwardgeorge/virtualenv-clone + # virtualenv-clone Usage: + # virtualenv-clone /path/to/existing/venv /path/to/cloned/ven + # or + # python -m clonevirtualenv /path/to/existing/venv /path/to/cloned/ven + clonevirtualenv = os.path.join(os.path.dirname(__file__), "_clonevirtualenv.py") + create_venv_cmd = [ + python, + clonevirtualenv, + current_python_dir, + virtualenv_path, + ] + logger.info("Cloning virtualenv %s to %s", current_python_dir, virtualenv_path) + else: + # virtualenv options: + # https://virtualenv.pypa.io/en/latest/cli_interface.html + # + # --app-data + # --reset-app-data + # Set an empty separated app data folder for current virtualenv. + # + # --no-periodic-update + # Disable the periodic (once every 14 days) update of the embedded + # wheels. + # + # --system-site-packages + # Inherit site packages. + # + # --no-download + # Never download the latest pip/setuptools/wheel from PyPI. + create_venv_cmd = [ + python, + "-m", + "virtualenv", + "--app-data", + virtualenv_app_data_path, + "--reset-app-data", + "--no-periodic-update", + "--system-site-packages", + "--no-download", + virtualenv_path, + ] + logger.info( + "Creating virtualenv at %s, current python dir %s", + virtualenv_path, + virtualenv_path, + ) + await check_output_cmd(create_venv_cmd, logger=logger, cwd=cwd, env=env) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/working_dir.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/working_dir.py new file mode 100644 index 0000000000000000000000000000000000000000..59fa66fac83b54a2a7b6e9bb2fc37fce9b3fe1a8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/runtime_env/working_dir.py @@ -0,0 +1,232 @@ +import logging +import os +from contextlib import contextmanager +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional + +import ray._private.ray_constants as ray_constants +from ray._common.utils import try_to_create_directory +from ray._private.runtime_env.context import RuntimeEnvContext +from ray._private.runtime_env.packaging import ( + Protocol, + delete_package, + download_and_unpack_package, + get_local_dir_from_uri, + get_uri_for_directory, + get_uri_for_package, + parse_uri, + upload_package_if_needed, + upload_package_to_gcs, +) +from ray._private.runtime_env.plugin import RuntimeEnvPlugin +from ray._private.utils import get_directory_size_bytes +from ray._raylet import GcsClient +from ray.exceptions import RuntimeEnvSetupError + +default_logger = logging.getLogger(__name__) + +_WIN32 = os.name == "nt" + + +def upload_working_dir_if_needed( + runtime_env: Dict[str, Any], + scratch_dir: Optional[str] = os.getcwd(), + logger: Optional[logging.Logger] = default_logger, + upload_fn: Optional[Callable[[str, Optional[List[str]]], None]] = None, +) -> Dict[str, Any]: + """Uploads the working_dir and replaces it with a URI. + + If the working_dir is already a URI, this is a no-op. + """ + working_dir = runtime_env.get("working_dir") + if working_dir is None: + return runtime_env + + if not isinstance(working_dir, str) and not isinstance(working_dir, Path): + raise TypeError( + "working_dir must be a string or Path (either a local path " + f"or remote URI), got {type(working_dir)}." + ) + + if isinstance(working_dir, Path): + working_dir = str(working_dir) + + # working_dir is already a URI -- just pass it through. + try: + protocol, path = parse_uri(working_dir) + except ValueError: + protocol, path = None, None + + if protocol is not None: + if protocol in Protocol.remote_protocols() and not path.endswith(".zip"): + raise ValueError("Only .zip files supported for remote URIs.") + return runtime_env + + excludes = runtime_env.get("excludes", None) + try: + working_dir_uri = get_uri_for_directory(working_dir, excludes=excludes) + except ValueError: # working_dir is not a directory + package_path = Path(working_dir) + if not package_path.exists() or package_path.suffix != ".zip": + raise ValueError( + f"directory {package_path} must be an existing " + "directory or a zip package" + ) + + pkg_uri = get_uri_for_package(package_path) + try: + upload_package_to_gcs(pkg_uri, package_path.read_bytes()) + except Exception as e: + raise RuntimeEnvSetupError( + f"Failed to upload package {package_path} to the Ray cluster: {e}" + ) from e + runtime_env["working_dir"] = pkg_uri + return runtime_env + if upload_fn is None: + try: + upload_package_if_needed( + working_dir_uri, + scratch_dir, + working_dir, + include_parent_dir=False, + excludes=excludes, + logger=logger, + ) + except Exception as e: + raise RuntimeEnvSetupError( + f"Failed to upload working_dir {working_dir} to the Ray cluster: {e}" + ) from e + else: + upload_fn(working_dir, excludes=excludes) + + runtime_env["working_dir"] = working_dir_uri + return runtime_env + + +def set_pythonpath_in_context(python_path: str, context: RuntimeEnvContext): + """Insert the path as the first entry in PYTHONPATH in the runtime env. + + This is compatible with users providing their own PYTHONPATH in env_vars, + and is also compatible with the existing PYTHONPATH in the cluster. + + The import priority is as follows: + this python_path arg > env_vars PYTHONPATH > existing cluster env PYTHONPATH. + """ + if "PYTHONPATH" in context.env_vars: + python_path += os.pathsep + context.env_vars["PYTHONPATH"] + if "PYTHONPATH" in os.environ: + python_path += os.pathsep + os.environ["PYTHONPATH"] + context.env_vars["PYTHONPATH"] = python_path + + +class WorkingDirPlugin(RuntimeEnvPlugin): + + name = "working_dir" + + # Note working_dir is not following the priority order of other plugins. Instead + # it's specially treated to happen before all other plugins. + priority = 5 + + def __init__(self, resources_dir: str, gcs_client: GcsClient): + self._resources_dir = os.path.join(resources_dir, "working_dir_files") + self._gcs_client = gcs_client + try_to_create_directory(self._resources_dir) + + def delete_uri( + self, uri: str, logger: Optional[logging.Logger] = default_logger + ) -> int: + """Delete URI and return the number of bytes deleted.""" + logger.info("Got request to delete working dir URI %s", uri) + local_dir = get_local_dir_from_uri(uri, self._resources_dir) + local_dir_size = get_directory_size_bytes(local_dir) + + deleted = delete_package(uri, self._resources_dir) + if not deleted: + logger.warning(f"Tried to delete nonexistent URI: {uri}.") + return 0 + + return local_dir_size + + def get_uris(self, runtime_env: "RuntimeEnv") -> List[str]: # noqa: F821 + working_dir_uri = runtime_env.working_dir() + if working_dir_uri != "": + return [working_dir_uri] + return [] + + async def create( + self, + uri: Optional[str], + runtime_env: dict, + context: RuntimeEnvContext, + logger: logging.Logger = default_logger, + ) -> int: + local_dir = await download_and_unpack_package( + uri, + self._resources_dir, + self._gcs_client, + logger=logger, + overwrite=True, + ) + return get_directory_size_bytes(local_dir) + + def modify_context( + self, + uris: List[str], + runtime_env_dict: Dict, + context: RuntimeEnvContext, + logger: Optional[logging.Logger] = default_logger, + ): + if not uris: + return + + # WorkingDirPlugin uses a single URI. + uri = uris[0] + local_dir = get_local_dir_from_uri(uri, self._resources_dir) + if not local_dir.exists(): + raise ValueError( + f"Local directory {local_dir} for URI {uri} does " + "not exist on the cluster. Something may have gone wrong while " + "downloading or unpacking the working_dir." + ) + + if not _WIN32: + context.command_prefix += ["cd", str(local_dir), "&&"] + else: + # Include '/d' incase temp folder is on different drive than Ray install. + context.command_prefix += ["cd", "/d", f"{local_dir}", "&&"] + set_pythonpath_in_context(python_path=str(local_dir), context=context) + + @contextmanager + def with_working_dir_env(self, uri): + """ + If uri is not None, add the local working directory to the environment variable + as "RAY_RUNTIME_ENV_CREATE_WORKING_DIR". This is useful for other plugins to + create their environment with reference to the working directory. For example + `pip -r ${RAY_RUNTIME_ENV_CREATE_WORKING_DIR}/requirements.txt` + + The environment variable is removed after the context manager exits. + """ + if uri is None: + yield + else: + local_dir = get_local_dir_from_uri(uri, self._resources_dir) + if not local_dir.exists(): + raise ValueError( + f"Local directory {local_dir} for URI {uri} does " + "not exist on the cluster. Something may have gone wrong while " + "downloading or unpacking the working_dir." + ) + key = ray_constants.RAY_RUNTIME_ENV_CREATE_WORKING_DIR_ENV_VAR + prev = os.environ.get(key) + # Windows backslash paths are weird. When it's passed to the env var, and + # when Pip expands it, the backslashes are interpreted as escape characters + # and messes up the whole path. So we convert it to forward slashes. + # This works at least for all Python applications, including pip. + os.environ[key] = local_dir.as_posix() + try: + yield + finally: + if prev is None: + del os.environ[key] + else: + os.environ[key] = prev diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/serialization.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..c59b55bf970a5b6220f79696dc78f8f478a80f70 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/serialization.py @@ -0,0 +1,679 @@ +import io +import logging +import threading +import traceback +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, Union + +if TYPE_CHECKING: + import torch + +import google.protobuf.message + +import ray._private.utils +import ray.cloudpickle as pickle +import ray.exceptions +from ray._private import ray_constants +from ray._private.custom_types import TensorTransportEnum +from ray._raylet import ( + DynamicObjectRefGenerator, + MessagePackSerializedObject, + MessagePackSerializer, + Pickle5SerializedObject, + Pickle5Writer, + RawSerializedObject, + SerializedRayObject, + split_buffer, + unpack_pickle5_buffers, +) +from ray.core.generated.common_pb2 import ErrorType, RayErrorInfo +from ray.exceptions import ( + ActorDiedError, + ActorPlacementGroupRemoved, + ActorUnavailableError, + ActorUnschedulableError, + LocalRayletDiedError, + NodeDiedError, + ObjectFetchTimedOutError, + ObjectFreedError, + ObjectLostError, + ObjectReconstructionFailedError, + ObjectReconstructionFailedLineageEvictedError, + ObjectReconstructionFailedMaxAttemptsExceededError, + ObjectRefStreamEndOfStreamError, + OutOfDiskError, + OutOfMemoryError, + OwnerDiedError, + PlasmaObjectNotAvailable, + RayError, + RaySystemError, + RayTaskError, + ReferenceCountingAssertionError, + RuntimeEnvSetupError, + TaskCancelledError, + TaskPlacementGroupRemoved, + TaskUnschedulableError, + WorkerCrashedError, +) +from ray.experimental.compiled_dag_ref import CompiledDAGRef +from ray.util import inspect_serializability, serialization_addons + +logger = logging.getLogger(__name__) +ALLOW_OUT_OF_BAND_OBJECT_REF_SERIALIZATION = ray_constants.env_bool( + "RAY_allow_out_of_band_object_ref_serialization", True +) + + +class DeserializationError(Exception): + pass + + +def pickle_dumps(obj: Any, error_msg: str): + """Wrap cloudpickle.dumps to provide better error message + when the object is not serializable. + """ + try: + return pickle.dumps(obj) + except (TypeError, ray.exceptions.OufOfBandObjectRefSerializationException) as e: + sio = io.StringIO() + inspect_serializability(obj, print_file=sio) + msg = f"{error_msg}:\n{sio.getvalue()}" + if isinstance(e, TypeError): + raise TypeError(msg) from e + else: + raise ray.exceptions.OufOfBandObjectRefSerializationException(msg) + + +def _object_ref_deserializer(binary, call_site, owner_address, object_status): + # NOTE(suquark): This function should be a global function so + # cloudpickle can access it directly. Otherwise cloudpickle + # has to dump the whole function definition, which is inefficient. + + # NOTE(swang): Must deserialize the object first before asking + # the core worker to resolve the value. This is to make sure + # that the ref count for the ObjectRef is greater than 0 by the + # time the core worker resolves the value of the object. + obj_ref = ray.ObjectRef(binary, owner_address, call_site) + + # TODO(edoakes): we should be able to just capture a reference + # to 'self' here instead, but this function is itself pickled + # somewhere, which causes an error. + if owner_address: + worker = ray._private.worker.global_worker + worker.check_connected() + context = worker.get_serialization_context() + outer_id = context.get_outer_object_ref() + # outer_id is None in the case that this ObjectRef was closed + # over in a function or pickled directly using pickle.dumps(). + if outer_id is None: + outer_id = ray.ObjectRef.nil() + worker.core_worker.deserialize_and_register_object_ref( + obj_ref.binary(), outer_id, owner_address, object_status + ) + return obj_ref + + +def _actor_handle_deserializer(serialized_obj, weak_ref): + # If this actor handle was stored in another object, then tell the + # core worker. + context = ray._private.worker.global_worker.get_serialization_context() + outer_id = context.get_outer_object_ref() + return ray.actor.ActorHandle._deserialization_helper( + serialized_obj, weak_ref, outer_id + ) + + +class SerializationContext: + """Initialize the serialization library. + + This defines a custom serializer for object refs and also tells ray to + serialize several exception classes that we define for error handling. + """ + + def __init__(self, worker): + self.worker = worker + self._thread_local = threading.local() + + def actor_handle_reducer(obj): + ray._private.worker.global_worker.check_connected() + serialized, actor_handle_id, weak_ref = obj._serialization_helper() + # Update ref counting for the actor handle + if not weak_ref: + self.add_contained_object_ref( + actor_handle_id, + # Right now, so many tests are failing when this is set. + # Allow it for now, but we should eventually disallow it here. + allow_out_of_band_serialization=True, + ) + return _actor_handle_deserializer, (serialized, weak_ref) + + self._register_cloudpickle_reducer(ray.actor.ActorHandle, actor_handle_reducer) + + def compiled_dag_ref_reducer(obj): + raise TypeError("Serialization of CompiledDAGRef is not supported.") + + self._register_cloudpickle_reducer(CompiledDAGRef, compiled_dag_ref_reducer) + + def object_ref_reducer(obj): + worker = ray._private.worker.global_worker + worker.check_connected() + self.add_contained_object_ref( + obj, + allow_out_of_band_serialization=( + ALLOW_OUT_OF_BAND_OBJECT_REF_SERIALIZATION + ), + call_site=obj.call_site(), + ) + obj, owner_address, object_status = worker.core_worker.serialize_object_ref( + obj + ) + return _object_ref_deserializer, ( + obj.binary(), + obj.call_site(), + owner_address, + object_status, + ) + + self._register_cloudpickle_reducer(ray.ObjectRef, object_ref_reducer) + + def object_ref_generator_reducer(obj): + return DynamicObjectRefGenerator, (obj._refs,) + + self._register_cloudpickle_reducer( + DynamicObjectRefGenerator, object_ref_generator_reducer + ) + + serialization_addons.apply(self) + + def _register_cloudpickle_reducer(self, cls, reducer): + pickle.CloudPickler.dispatch[cls] = reducer + + def _unregister_cloudpickle_reducer(self, cls): + pickle.CloudPickler.dispatch.pop(cls, None) + + def _register_cloudpickle_serializer( + self, cls, custom_serializer, custom_deserializer + ): + def _CloudPicklerReducer(obj): + return custom_deserializer, (custom_serializer(obj),) + + # construct a reducer + pickle.CloudPickler.dispatch[cls] = _CloudPicklerReducer + + def is_in_band_serialization(self): + return getattr(self._thread_local, "in_band", False) + + def set_in_band_serialization(self): + self._thread_local.in_band = True + + def set_out_of_band_serialization(self): + self._thread_local.in_band = False + + def get_outer_object_ref(self): + stack = getattr(self._thread_local, "object_ref_stack", []) + return stack[-1] if stack else None + + def get_and_clear_contained_object_refs(self): + if not hasattr(self._thread_local, "object_refs"): + self._thread_local.object_refs = set() + return set() + + object_refs = self._thread_local.object_refs + self._thread_local.object_refs = set() + return object_refs + + def add_contained_object_ref( + self, + object_ref: "ray.ObjectRef", + *, + allow_out_of_band_serialization: bool, + call_site: Optional[str] = None, + ): + if self.is_in_band_serialization(): + # This object ref is being stored in an object. Add the ID to the + # list of IDs contained in the object so that we keep the inner + # object value alive as long as the outer object is in scope. + if not hasattr(self._thread_local, "object_refs"): + self._thread_local.object_refs = set() + self._thread_local.object_refs.add(object_ref) + else: + if not allow_out_of_band_serialization: + raise ray.exceptions.OufOfBandObjectRefSerializationException( + f"It is not allowed to serialize ray.ObjectRef {object_ref.hex()}. " + "If you want to allow serialization, " + "set `RAY_allow_out_of_band_object_ref_serialization=1.` " + "If you set the env var, the object is pinned forever in the " + "lifetime of the worker process and can cause Ray object leaks. " + "See the callsite and trace to find where the serialization " + "occurs.\nCallsite: " + f"{call_site or 'Disabled. Set RAY_record_ref_creation_sites=1'}" + ) + else: + # If this serialization is out-of-band (e.g., from a call to + # cloudpickle directly or captured in a remote function/actor), + # then pin the object for the lifetime of this worker by adding + # a local reference that won't ever be removed. + ray._private.worker.global_worker.core_worker.add_object_ref_reference( + object_ref + ) + + def _deserialize_pickle5_data( + self, + data: Any, + tensor_transport: TensorTransportEnum, + object_id: Optional[str] = None, + ) -> Any: + """ + + Args: + data: The data to deserialize. + tensor_transport: The tensor transport to use. If not equal to OBJECT_STORE, + it means that any tensors in the object are sent out-of-band + instead of through the object store. In this case, we need to + retrieve the tensors from the in-actor object store. Then, we + deserialize `data` with the retrieved tensors in the + serialization context. + object_id: The object ID to use as the key for the in-actor object store + to retrieve tensors. + + Returns: + Any: The deserialized object. + """ + from ray.experimental.channel import ChannelContext + + ctx = ChannelContext.get_current().serialization_context + + enable_gpu_objects = tensor_transport != TensorTransportEnum.OBJECT_STORE + if enable_gpu_objects: + gpu_object_manager = ray._private.worker.global_worker.gpu_object_manager + if not gpu_object_manager.gpu_object_store.has_gpu_object(object_id): + assert gpu_object_manager.is_managed_gpu_object( + object_id + ), f"obj_id={object_id} not found in GPU object store. This error is unexpected. Please report this issue on GitHub: https://github.com/ray-project/ray/issues/new/choose" + gpu_object_manager.fetch_gpu_object(object_id) + tensors = gpu_object_manager.gpu_object_store.get_gpu_object(object_id) + ctx.reset_out_of_band_tensors(tensors) + # TODO(kevin85421): The current garbage collection implementation for the in-actor object store + # is naive. We garbage collect each object after it is consumed once. + gpu_object_manager.gpu_object_store.remove_gpu_object(object_id) + + try: + in_band, buffers = unpack_pickle5_buffers(data) + if len(buffers) > 0: + obj = pickle.loads(in_band, buffers=buffers) + else: + obj = pickle.loads(in_band) + # cloudpickle does not provide error types + except pickle.pickle.PicklingError: + raise DeserializationError() + finally: + if enable_gpu_objects: + ctx.reset_out_of_band_tensors([]) + return obj + + def _deserialize_msgpack_data( + self, + data, + metadata_fields, + object_id: Optional[str] = None, + tensor_transport: Optional[ + TensorTransportEnum + ] = TensorTransportEnum.OBJECT_STORE, + ): + msgpack_data, pickle5_data = split_buffer(data) + + if metadata_fields[0] == ray_constants.OBJECT_METADATA_TYPE_PYTHON: + python_objects = self._deserialize_pickle5_data( + pickle5_data, tensor_transport, object_id + ) + else: + python_objects = [] + + try: + + def _python_deserializer(index): + return python_objects[index] + + obj = MessagePackSerializer.loads(msgpack_data, _python_deserializer) + except Exception: + raise DeserializationError() + return obj + + def _deserialize_error_info(self, data, metadata_fields): + assert data + pb_bytes = self._deserialize_msgpack_data(data, metadata_fields) + assert pb_bytes + + ray_error_info = RayErrorInfo() + ray_error_info.ParseFromString(pb_bytes) + return ray_error_info + + def _deserialize_actor_died_error(self, data, metadata_fields): + if not data: + return ActorDiedError() + ray_error_info = self._deserialize_error_info(data, metadata_fields) + assert ray_error_info.HasField("actor_died_error") + if ray_error_info.actor_died_error.HasField("creation_task_failure_context"): + return RayError.from_ray_exception( + ray_error_info.actor_died_error.creation_task_failure_context + ) + else: + assert ray_error_info.actor_died_error.HasField("actor_died_error_context") + return ActorDiedError( + cause=ray_error_info.actor_died_error.actor_died_error_context + ) + + def _deserialize_object( + self, + data, + metadata, + object_ref, + tensor_transport: Optional[TensorTransportEnum], + ): + if tensor_transport is None: + tensor_transport = TensorTransportEnum.OBJECT_STORE + if metadata: + metadata_fields = metadata.split(b",") + if metadata_fields[0] in [ + ray_constants.OBJECT_METADATA_TYPE_CROSS_LANGUAGE, + ray_constants.OBJECT_METADATA_TYPE_PYTHON, + ]: + return self._deserialize_msgpack_data( + data, metadata_fields, object_ref.hex(), tensor_transport + ) + # Check if the object should be returned as raw bytes. + if metadata_fields[0] == ray_constants.OBJECT_METADATA_TYPE_RAW: + if data is None: + return b"" + return data.to_pybytes() + elif metadata_fields[0] == ray_constants.OBJECT_METADATA_TYPE_ACTOR_HANDLE: + obj = self._deserialize_msgpack_data(data, metadata_fields) + # The last character is a 1 if weak_ref=True and 0 else. + serialized, weak_ref = obj[:-1], obj[-1:] == b"1" + return _actor_handle_deserializer(serialized, weak_ref) + # Otherwise, return an exception object based on + # the error type. + try: + error_type = int(metadata_fields[0]) + except Exception: + raise Exception( + f"Can't deserialize object: {object_ref}, " f"metadata: {metadata}" + ) + + # RayTaskError is serialized with pickle5 in the data field. + # TODO (kfstorm): exception serialization should be language + # independent. + if error_type == ErrorType.Value("TASK_EXECUTION_EXCEPTION"): + obj = self._deserialize_msgpack_data(data, metadata_fields) + return RayError.from_bytes(obj) + elif error_type == ErrorType.Value("WORKER_DIED"): + return WorkerCrashedError() + elif error_type == ErrorType.Value("ACTOR_DIED"): + return self._deserialize_actor_died_error(data, metadata_fields) + elif error_type == ErrorType.Value("LOCAL_RAYLET_DIED"): + return LocalRayletDiedError() + elif error_type == ErrorType.Value("TASK_CANCELLED"): + # Task cancellations are serialized in two ways, so check both + # deserialization paths. + # TODO(swang): We should only have one serialization path. + try: + # Deserialization from C++ (the CoreWorker task submitter). + # The error info will be stored as a RayErrorInfo. + error_message = "" + if data: + error_info = self._deserialize_error_info(data, metadata_fields) + error_message = error_info.error_message + return TaskCancelledError(error_message=error_message) + except google.protobuf.message.DecodeError: + # Deserialization from Python. The TaskCancelledError is + # serialized and returned directly. + obj = self._deserialize_msgpack_data(data, metadata_fields) + return RayError.from_bytes(obj) + elif error_type == ErrorType.Value("OBJECT_LOST"): + return ObjectLostError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value("OBJECT_FETCH_TIMED_OUT"): + return ObjectFetchTimedOutError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value("OUT_OF_DISK_ERROR"): + return OutOfDiskError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value("OUT_OF_MEMORY"): + error_info = self._deserialize_error_info(data, metadata_fields) + return OutOfMemoryError(error_info.error_message) + elif error_type == ErrorType.Value("NODE_DIED"): + error_info = self._deserialize_error_info(data, metadata_fields) + return NodeDiedError(error_info.error_message) + elif error_type == ErrorType.Value("OBJECT_DELETED"): + return ReferenceCountingAssertionError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value("OBJECT_FREED"): + return ObjectFreedError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value("OWNER_DIED"): + return OwnerDiedError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value("OBJECT_UNRECONSTRUCTABLE"): + return ObjectReconstructionFailedError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value( + "OBJECT_UNRECONSTRUCTABLE_MAX_ATTEMPTS_EXCEEDED" + ): + return ObjectReconstructionFailedMaxAttemptsExceededError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value( + "OBJECT_UNRECONSTRUCTABLE_LINEAGE_EVICTED" + ): + return ObjectReconstructionFailedLineageEvictedError( + object_ref.hex(), object_ref.owner_address(), object_ref.call_site() + ) + elif error_type == ErrorType.Value("RUNTIME_ENV_SETUP_FAILED"): + error_info = self._deserialize_error_info(data, metadata_fields) + # TODO(sang): Assert instead once actor also reports error messages. + error_msg = "" + if error_info.HasField("runtime_env_setup_failed_error"): + error_msg = error_info.runtime_env_setup_failed_error.error_message + return RuntimeEnvSetupError(error_message=error_msg) + elif error_type == ErrorType.Value("TASK_PLACEMENT_GROUP_REMOVED"): + return TaskPlacementGroupRemoved() + elif error_type == ErrorType.Value("ACTOR_PLACEMENT_GROUP_REMOVED"): + return ActorPlacementGroupRemoved() + elif error_type == ErrorType.Value("TASK_UNSCHEDULABLE_ERROR"): + error_info = self._deserialize_error_info(data, metadata_fields) + return TaskUnschedulableError(error_info.error_message) + elif error_type == ErrorType.Value("ACTOR_UNSCHEDULABLE_ERROR"): + error_info = self._deserialize_error_info(data, metadata_fields) + return ActorUnschedulableError(error_info.error_message) + elif error_type == ErrorType.Value("END_OF_STREAMING_GENERATOR"): + return ObjectRefStreamEndOfStreamError() + elif error_type == ErrorType.Value("ACTOR_UNAVAILABLE"): + error_info = self._deserialize_error_info(data, metadata_fields) + if error_info.HasField("actor_unavailable_error"): + actor_id = error_info.actor_unavailable_error.actor_id + else: + actor_id = None + return ActorUnavailableError(error_info.error_message, actor_id) + else: + return RaySystemError("Unrecognized error type " + str(error_type)) + elif data: + raise ValueError("non-null object should always have metadata") + else: + # Object isn't available in plasma. This should never be returned + # to the user. We should only reach this line if this object was + # deserialized as part of a list, and another object in the list + # throws an exception. + return PlasmaObjectNotAvailable + + def deserialize_objects( + self, serialized_ray_objects: List[SerializedRayObject], object_refs + ): + assert len(serialized_ray_objects) == len(object_refs) + # initialize the thread-local field + if not hasattr(self._thread_local, "object_ref_stack"): + self._thread_local.object_ref_stack = [] + results = [] + for object_ref, (data, metadata, tensor_transport_value) in zip( + object_refs, serialized_ray_objects + ): + try: + # Push the object ref to the stack, so the object under + # the object ref knows where it comes from. + self._thread_local.object_ref_stack.append(object_ref) + obj = self._deserialize_object( + data, metadata, object_ref, tensor_transport_value + ) + except Exception as e: + logger.exception(e) + obj = RaySystemError(e, traceback.format_exc()) + finally: + # Must clear ObjectRef to not hold a reference. + if self._thread_local.object_ref_stack: + self._thread_local.object_ref_stack.pop() + results.append(obj) + return results + + def _serialize_to_pickle5(self, metadata, value): + writer = Pickle5Writer() + # TODO(swang): Check that contained_object_refs is empty. + try: + self.set_in_band_serialization() + inband = pickle.dumps( + value, protocol=5, buffer_callback=writer.buffer_callback + ) + except Exception as e: + self.get_and_clear_contained_object_refs() + raise e + finally: + self.set_out_of_band_serialization() + + return Pickle5SerializedObject( + metadata, inband, writer, self.get_and_clear_contained_object_refs() + ) + + def _serialize_to_msgpack(self, value): + # Only RayTaskError is possible to be serialized here. We don't + # need to deal with other exception types here. + contained_object_refs = [] + + if isinstance(value, RayTaskError): + if issubclass(value.cause.__class__, TaskCancelledError): + # Handle task cancellation errors separately because we never + # want to warn about tasks that were intentionally cancelled by + # the user. + metadata = str(ErrorType.Value("TASK_CANCELLED")).encode("ascii") + value = value.to_bytes() + else: + metadata = str(ErrorType.Value("TASK_EXECUTION_EXCEPTION")).encode( + "ascii" + ) + value = value.to_bytes() + elif isinstance(value, ray.actor.ActorHandle): + # TODO(fyresone): ActorHandle should be serialized via the + # custom type feature of cross-language. + serialized, actor_handle_id, weak_ref = value._serialization_helper() + if not weak_ref: + contained_object_refs.append(actor_handle_id) + # Update ref counting for the actor handle + metadata = ray_constants.OBJECT_METADATA_TYPE_ACTOR_HANDLE + # Append a 1 to mean weak ref or 0 for strong ref. + # We do this here instead of in the main serialization helper + # because msgpack expects a bytes object. We cannot serialize + # `weak_ref` in the C++ code because the weak_ref property is only + # available in the Python ActorHandle instance. + value = serialized + (b"1" if weak_ref else b"0") + else: + metadata = ray_constants.OBJECT_METADATA_TYPE_CROSS_LANGUAGE + + python_objects = [] + + def _python_serializer(o): + index = len(python_objects) + python_objects.append(o) + return index + + msgpack_data = MessagePackSerializer.dumps(value, _python_serializer) + + if python_objects: + metadata = ray_constants.OBJECT_METADATA_TYPE_PYTHON + pickle5_serialized_object = self._serialize_to_pickle5( + metadata, python_objects + ) + else: + pickle5_serialized_object = None + + return MessagePackSerializedObject( + metadata, msgpack_data, contained_object_refs, pickle5_serialized_object + ) + + def serialize_and_store_gpu_objects( + self, + value: Any, + obj_id: bytes, + ) -> MessagePackSerializedObject: + """Retrieve GPU data from `value` and store it in the GPU object store. Then, return the serialized value. + + Args: + value: The value to serialize. + obj_id: The object ID of the value. `obj_id` is required, and the GPU data (e.g. tensors) in `value` + will be stored in the GPU object store with the key `obj_id`. + + Returns: + Serialized value. + """ + assert ( + obj_id is not None + ), "`obj_id` is required, and it is the key to retrieve corresponding tensors from the GPU object store." + serialized_val, tensors = self._serialize_and_retrieve_tensors(value) + if tensors: + obj_id = obj_id.decode("ascii") + worker = ray._private.worker.global_worker + gpu_object_manager = worker.gpu_object_manager + gpu_object_manager.gpu_object_store.add_gpu_object(obj_id, tensors) + + return serialized_val + + def serialize( + self, value: Any + ) -> Union[RawSerializedObject, MessagePackSerializedObject]: + """Serialize an object. + + Args: + value: The value to serialize. + + Returns: + Serialized value. + """ + if isinstance(value, bytes): + # If the object is a byte array, skip serializing it and + # use a special metadata to indicate it's raw binary. So + # that this object can also be read by Java. + return RawSerializedObject(value) + else: + return self._serialize_to_msgpack(value) + + def _serialize_and_retrieve_tensors( + self, value: Any + ) -> Tuple[MessagePackSerializedObject, List["torch.Tensor"]]: + """ + Serialize `value` and return the serialized value and any tensors retrieved from `value`. + This is only used for GPU objects. + """ + from ray.experimental.channel import ChannelContext + + ctx = ChannelContext.get_current().serialization_context + prev_use_external_transport = ctx.use_external_transport + ctx.set_use_external_transport(True) + try: + serialized_val = self._serialize_to_msgpack(value) + finally: + ctx.set_use_external_transport(prev_use_external_transport) + + tensors, _ = ctx.reset_out_of_band_tensors([]) + return serialized_val, tensors diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/services.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/services.py new file mode 100644 index 0000000000000000000000000000000000000000..ee7ac25403c9343e573aba6a596faf0301bbd7bd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/services.py @@ -0,0 +1,2405 @@ +import base64 +import collections +import errno +import io +import json +import logging +import mmap +import multiprocessing +import os +import shutil +import signal +import socket +import subprocess +import sys +import time +from pathlib import Path +from typing import IO, AnyStr, List, Optional + +from filelock import FileLock + +# Ray modules +import ray +import ray._private.ray_constants as ray_constants +from ray._private.ray_constants import RAY_NODE_IP_FILENAME +from ray._private.resource_isolation_config import ResourceIsolationConfig +from ray._raylet import GcsClient, GcsClientOptions +from ray.core.generated.common_pb2 import Language + +# Import psutil after ray so the packaged version is used. +import psutil + +resource = None +if sys.platform != "win32": + _timeout = 30 +else: + _timeout = 60 + +EXE_SUFFIX = ".exe" if sys.platform == "win32" else "" + +# True if processes are run in the valgrind profiler. +RUN_RAYLET_PROFILER = False + +# Location of the redis server. +RAY_HOME = os.path.join(os.path.dirname(os.path.dirname(__file__)), "..", "..") +RAY_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) +RAY_PRIVATE_DIR = "_private" +AUTOSCALER_PRIVATE_DIR = os.path.join("autoscaler", "_private") +AUTOSCALER_V2_DIR = os.path.join("autoscaler", "v2") + +# Location of the raylet executables. +RAYLET_EXECUTABLE = os.path.join( + RAY_PATH, "core", "src", "ray", "raylet", "raylet" + EXE_SUFFIX +) +GCS_SERVER_EXECUTABLE = os.path.join( + RAY_PATH, "core", "src", "ray", "gcs", "gcs_server" + EXE_SUFFIX +) + +JEMALLOC_SO = os.path.join(RAY_PATH, "core", "libjemalloc.so") + +JEMALLOC_SO = JEMALLOC_SO if os.path.exists(JEMALLOC_SO) else None + +# Location of the cpp default worker executables. +DEFAULT_WORKER_EXECUTABLE = os.path.join(RAY_PATH, "cpp", "default_worker" + EXE_SUFFIX) + +# Location of the native libraries. +DEFAULT_NATIVE_LIBRARY_PATH = os.path.join(RAY_PATH, "cpp", "lib") + +DASHBOARD_DEPENDENCY_ERROR_MESSAGE = ( + "Not all Ray Dashboard dependencies were " + "found. To use the dashboard please " + "install Ray using `pip install " + "ray[default]`." +) + +RAY_JEMALLOC_LIB_PATH = "RAY_JEMALLOC_LIB_PATH" +RAY_JEMALLOC_CONF = "RAY_JEMALLOC_CONF" +RAY_JEMALLOC_PROFILE = "RAY_JEMALLOC_PROFILE" + +# Comma separated name of components that will run memory profiler. +# Ray uses `memray` to memory profile internal components. +# The name of the component must be one of ray_constants.PROCESS_TYPE*. +RAY_MEMRAY_PROFILE_COMPONENT_ENV = "RAY_INTERNAL_MEM_PROFILE_COMPONENTS" +# Options to specify for `memray run` command. See +# `memray run --help` for more details. +# Example: +# RAY_INTERNAL_MEM_PROFILE_OPTIONS="--live,--live-port,3456,-q," +# -> `memray run --live --live-port 3456 -q` +RAY_MEMRAY_PROFILE_OPTIONS_ENV = "RAY_INTERNAL_MEM_PROFILE_OPTIONS" + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) + +ProcessInfo = collections.namedtuple( + "ProcessInfo", + [ + "process", + "stdout_file", + "stderr_file", + "use_valgrind", + "use_gdb", + "use_valgrind_profiler", + "use_perftools_profiler", + "use_tmux", + ], +) + + +def _site_flags() -> List[str]: + """Detect whether flags related to site packages are enabled for the current + interpreter. To run Ray in hermetic build environments, it helps to pass these flags + down to Python workers. + """ + flags = [] + # sys.flags hidden behind helper methods for unit testing. + if _no_site(): + flags.append("-S") + if _no_user_site(): + flags.append("-s") + return flags + + +# sys.flags hidden behind helper methods for unit testing. +def _no_site(): + return sys.flags.no_site + + +# sys.flags hidden behind helper methods for unit testing. +def _no_user_site(): + return sys.flags.no_user_site + + +def _build_python_executable_command_memory_profileable( + component: str, session_dir: str, unbuffered: bool = True +): + """Build the Python executable command. + + It runs a memory profiler if env var is configured. + + Args: + component: Name of the component. It must be one of + ray_constants.PROCESS_TYPE*. + session_dir: The directory name of the Ray session. + unbuffered: If true, Python executable is started with unbuffered option. + e.g., `-u`. + It means the logs are flushed immediately (good when there's a failure), + but writing to a log file can be slower. + """ + command = [ + sys.executable, + ] + if unbuffered: + command.append("-u") + components_to_memory_profile = os.getenv(RAY_MEMRAY_PROFILE_COMPONENT_ENV, "") + if not components_to_memory_profile: + return command + + components_to_memory_profile = set(components_to_memory_profile.split(",")) + try: + import memray # noqa: F401 + except ImportError: + raise ImportError( + "Memray is required to memory profiler on components " + f"{components_to_memory_profile}. Run `pip install memray`." + ) + if component in components_to_memory_profile: + session_dir = Path(session_dir) + session_name = session_dir.name + profile_dir = session_dir / "profile" + profile_dir.mkdir(exist_ok=True) + output_file_path = profile_dir / f"{session_name}_memory_{component}.bin" + options = os.getenv(RAY_MEMRAY_PROFILE_OPTIONS_ENV, None) + options = options.split(",") if options else [] + command.extend(["-m", "memray", "run", "-o", str(output_file_path), *options]) + + return command + + +def _get_gcs_client_options(gcs_server_address): + return GcsClientOptions.create( + gcs_server_address, + None, + allow_cluster_id_nil=True, + fetch_cluster_id_if_nil=False, + ) + + +def serialize_config(config): + return base64.b64encode(json.dumps(config).encode("utf-8")).decode("utf-8") + + +def propagate_jemalloc_env_var( + *, + jemalloc_path: str, + jemalloc_conf: str, + jemalloc_comps: List[str], + process_type: str, +): + """Read the jemalloc memory profiling related + env var and return the dictionary that translates + them to proper jemalloc related env vars. + + For example, if users specify `RAY_JEMALLOC_LIB_PATH`, + it is translated into `LD_PRELOAD` which is needed to + run Jemalloc as a shared library. + + Params: + jemalloc_path: The path to the jemalloc shared library. + jemalloc_conf: `,` separated string of jemalloc config. + jemalloc_comps: The list of Ray components + that we will profile. + process_type: The process type that needs jemalloc + env var for memory profiling. If it doesn't match one of + jemalloc_comps, the function will return an empty dict. + + Returns: + dictionary of {env_var: value} + that are needed to jemalloc profiling. The caller can + call `dict.update(return_value_of_this_func)` to + update the dict of env vars. If the process_type doesn't + match jemalloc_comps, it will return an empty dict. + """ + assert isinstance(jemalloc_comps, list) + assert process_type is not None + process_type = process_type.lower() + if not jemalloc_path: + return {} + + env_vars = { + "LD_PRELOAD": jemalloc_path, + "RAY_LD_PRELOAD_ON_WORKERS": os.environ.get("RAY_LD_PRELOAD_ON_WORKERS", "0"), + } + if process_type in jemalloc_comps and jemalloc_conf: + env_vars.update({"MALLOC_CONF": jemalloc_conf}) + return env_vars + + +class ConsolePopen(subprocess.Popen): + if sys.platform == "win32": + + def terminate(self): + if isinstance(self.stdin, io.IOBase): + self.stdin.close() + if self._use_signals: + self.send_signal(signal.CTRL_BREAK_EVENT) + else: + super(ConsolePopen, self).terminate() + + def __init__(self, *args, **kwargs): + # CREATE_NEW_PROCESS_GROUP is used to send Ctrl+C on Windows: + # https://docs.python.org/3/library/subprocess.html#subprocess.Popen.send_signal + new_pgroup = subprocess.CREATE_NEW_PROCESS_GROUP + flags_to_add = 0 + if ray._private.utils.detect_fate_sharing_support(): + # If we don't have kernel-mode fate-sharing, then don't do this + # because our children need to be in out process group for + # the process reaper to properly terminate them. + flags_to_add = new_pgroup + flags_key = "creationflags" + if flags_to_add: + kwargs[flags_key] = (kwargs.get(flags_key) or 0) | flags_to_add + self._use_signals = kwargs[flags_key] & new_pgroup + super(ConsolePopen, self).__init__(*args, **kwargs) + + +def address(ip_address, port): + return ip_address + ":" + str(port) + + +def _find_address_from_flag(flag: str): + """ + Attempts to find all valid Ray addresses on this node, specified by the + flag. + + Params: + flag: `--redis-address` or `--gcs-address` + Returns: + Set of detected addresses. + """ + # Using Redis address `--redis-address` as an example: + # Currently, this extracts the deprecated --redis-address from the command + # that launched the raylet running on this node, if any. Anyone looking to + # edit this function should be warned that these commands look like, for + # example: + # /usr/local/lib/python3.8/dist-packages/ray/core/src/ray/raylet/raylet + # --redis_address=123.456.78.910 --node_ip_address=123.456.78.910 + # --raylet_socket_name=... --store_socket_name=... --object_manager_port=0 + # --min_worker_port=10000 --max_worker_port=19999 + # --node_manager_port=58578 --redis_port=6379 + # --maximum_startup_concurrency=8 + # --static_resource_list=node:123.456.78.910,1.0,object_store_memory,66 + # --config_list=plasma_store_as_thread,True + # --python_worker_command=/usr/bin/python + # /usr/local/lib/python3.8/dist-packages/ray/workers/default_worker.py + # --redis-address=123.456.78.910:6379 + # --node-ip-address=123.456.78.910 --node-manager-port=58578 + # --object-store-name=... --raylet-name=... + # --temp-dir=/tmp/ray + # --metrics-agent-port=41856 --redis-password=[MASKED] + # --java_worker_command= --cpp_worker_command= + # --redis_password=[MASKED] --temp_dir=/tmp/ray --session_dir=... + # --metrics-agent-port=41856 --metrics_export_port=64229 + # --dashboard_agent_command=/usr/bin/python + # -u /usr/local/lib/python3.8/dist-packages/ray/dashboard/agent.py + # --redis-address=123.456.78.910:6379 --metrics-export-port=64229 + # --dashboard-agent-port=41856 --node-manager-port=58578 + # --object-store-name=... --raylet-name=... --temp-dir=/tmp/ray + # --log-dir=/tmp/ray/session_2020-11-08_14-29-07_199128_278000/logs + # --redis-password=[MASKED] --object_store_memory=5037192806 + # --plasma_directory=/tmp + # Longer arguments are elided with ... but all arguments from this instance + # are included, to provide a sense of what is in these. + # Indeed, we had to pull --redis-address to the front of each call to make + # this readable. + # As you can see, this is very long and complex, which is why we can't + # simply extract all the arguments using regular expressions and + # present a dict as if we never lost track of these arguments, for + # example. Picking out --redis-address below looks like it might grab the + # wrong thing, but double-checking that we're finding the correct process + # by checking that the contents look like we expect would probably be prone + # to choking in unexpected ways. + # Notice that --redis-address appears twice. This is not a copy-paste + # error; this is the reason why the for loop below attempts to pick out + # every appearance of --redis-address. + + # The --redis-address here is what is now called the --address, but it + # appears in the default_worker.py and agent.py calls as --redis-address. + addresses = set() + for proc in psutil.process_iter(["cmdline"]): + try: + # HACK: Workaround for UNIX idiosyncrasy + # Normally, cmdline() is supposed to return the argument list. + # But it in some cases (such as when setproctitle is called), + # an arbitrary string resembling a command-line is stored in + # the first argument. + # Explanation: https://unix.stackexchange.com/a/432681 + # More info: https://github.com/giampaolo/psutil/issues/1179 + cmdline = proc.info["cmdline"] + # NOTE(kfstorm): To support Windows, we can't use + # `os.path.basename(cmdline[0]) == "raylet"` here. + + if _is_raylet_process(cmdline): + for arglist in cmdline: + # Given we're merely seeking --redis-address, we just split + # every argument on spaces for now. + for arg in arglist.split(" "): + # TODO(ekl): Find a robust solution for locating Redis. + if arg.startswith(flag): + proc_addr = arg.split("=")[1] + # TODO(mwtian): remove this workaround after Ray + # no longer sets --redis-address to None. + if proc_addr != "" and proc_addr != "None": + addresses.add(proc_addr) + except psutil.AccessDenied: + pass + except psutil.NoSuchProcess: + pass + return addresses + + +def find_gcs_addresses(): + """Finds any local GCS processes based on grepping ps.""" + return _find_address_from_flag("--gcs-address") + + +def find_bootstrap_address(temp_dir: Optional[str]): + """Finds the latest Ray cluster address to connect to, if any. This is the + GCS address connected to by the last successful `ray start`.""" + return ray._private.utils.read_ray_address(temp_dir) + + +def get_ray_address_from_environment(addr: str, temp_dir: Optional[str]): + """Attempts to find the address of Ray cluster to use, in this order: + + 1. Use RAY_ADDRESS if defined and nonempty. + 2. If no address is provided or the provided address is "auto", use the + address in /tmp/ray/ray_current_cluster if available. This will error if + the specified address is None and there is no address found. For "auto", + we will fallback to connecting to any detected Ray cluster (legacy). + 3. Otherwise, use the provided address. + + Returns: + A string to pass into `ray.init(address=...)`, e.g. ip:port, `auto`. + """ + env_addr = os.environ.get(ray_constants.RAY_ADDRESS_ENVIRONMENT_VARIABLE) + if env_addr is not None and env_addr != "": + addr = env_addr + + if addr is not None and addr != "auto": + return addr + # We should try to automatically find an active local instance. + gcs_addrs = find_gcs_addresses() + bootstrap_addr = find_bootstrap_address(temp_dir) + + if len(gcs_addrs) > 1 and bootstrap_addr is not None: + logger.warning( + f"Found multiple active Ray instances: {gcs_addrs}. " + f"Connecting to latest cluster at {bootstrap_addr}. " + "You can override this by setting the `--address` flag " + "or `RAY_ADDRESS` environment variable." + ) + elif len(gcs_addrs) > 0 and addr == "auto": + # Preserve legacy "auto" behavior of connecting to any cluster, even if not + # started with ray start. However if addr is None, we will raise an error. + bootstrap_addr = list(gcs_addrs).pop() + + if bootstrap_addr is None: + if addr is None: + # Caller should start a new instance. + return None + else: + raise ConnectionError( + "Could not find any running Ray instance. " + "Please specify the one to connect to by setting `--address` flag " + "or `RAY_ADDRESS` environment variable." + ) + + return bootstrap_addr + + +def wait_for_node( + gcs_address: str, + node_plasma_store_socket_name: str, + timeout: int = _timeout, +): + """Wait until this node has appeared in the client table. + + Args: + gcs_address: The gcs address + node_plasma_store_socket_name: The + plasma_store_socket_name for the given node which we wait for. + timeout: The amount of time in seconds to wait before raising an + exception. + + Raises: + TimeoutError: An exception is raised if the timeout expires before + the node appears in the client table. + """ + gcs_options = GcsClientOptions.create( + gcs_address, None, allow_cluster_id_nil=True, fetch_cluster_id_if_nil=False + ) + global_state = ray._private.state.GlobalState() + global_state._initialize_global_state(gcs_options) + start_time = time.time() + while time.time() - start_time < timeout: + clients = global_state.node_table() + object_store_socket_names = [ + client["ObjectStoreSocketName"] for client in clients + ] + if node_plasma_store_socket_name in object_store_socket_names: + return + else: + time.sleep(0.1) + raise TimeoutError( + f"Timed out after {timeout} seconds while waiting for node to startup. " + f"Did not find socket name {node_plasma_store_socket_name} in the list " + "of object store socket names." + ) + + +def get_node_to_connect_for_driver(gcs_address, node_ip_address): + # Get node table from global state accessor. + global_state = ray._private.state.GlobalState() + gcs_options = _get_gcs_client_options(gcs_address) + global_state._initialize_global_state(gcs_options) + return global_state.get_node_to_connect_for_driver(node_ip_address) + + +def get_node(gcs_address, node_id): + """ + Get the node information from the global state accessor. + """ + global_state = ray._private.state.GlobalState() + gcs_options = _get_gcs_client_options(gcs_address) + global_state._initialize_global_state(gcs_options) + return global_state.get_node(node_id) + + +def get_webui_url_from_internal_kv(): + assert ray.experimental.internal_kv._internal_kv_initialized() + webui_url = ray.experimental.internal_kv._internal_kv_get( + "webui:url", namespace=ray_constants.KV_NAMESPACE_DASHBOARD + ) + return ray._common.utils.decode(webui_url) if webui_url is not None else None + + +def remaining_processes_alive(): + """See if the remaining processes are alive or not. + + Note that this ignores processes that have been explicitly killed, + e.g., via a command like node.kill_raylet(). + + Returns: + True if the remaining processes started by ray.init() are alive and + False otherwise. + + Raises: + Exception: An exception is raised if the processes were not started by + ray.init(). + """ + if ray._private.worker._global_node is None: + raise RuntimeError( + "This process is not in a position to determine " + "whether all processes are alive or not." + ) + return ray._private.worker._global_node.remaining_processes_alive() + + +def canonicalize_bootstrap_address( + addr: str, temp_dir: Optional[str] = None +) -> Optional[str]: + """Canonicalizes Ray cluster bootstrap address to host:port. + Reads address from the environment if needed. + + This function should be used to process user supplied Ray cluster address, + via ray.init() or `--address` flags, before using the address to connect. + + Returns: + Ray cluster address string in format or None if the caller + should start a local Ray instance. + """ + if addr is None or addr == "auto": + addr = get_ray_address_from_environment(addr, temp_dir) + if addr is None or addr == "local": + return None + try: + bootstrap_address = resolve_ip_for_localhost(addr) + except Exception: + logger.exception(f"Failed to convert {addr} to host:port") + raise + return bootstrap_address + + +def canonicalize_bootstrap_address_or_die( + addr: str, temp_dir: Optional[str] = None +) -> str: + """Canonicalizes Ray cluster bootstrap address to host:port. + + This function should be used when the caller expects there to be an active + and local Ray instance. If no address is provided or address="auto", this + will autodetect the latest Ray instance created with `ray start`. + + For convenience, if no address can be autodetected, this function will also + look for any running local GCS processes, based on pgrep output. This is to + allow easier use of Ray CLIs when debugging a local Ray instance (whose GCS + addresses are not recorded). + + Returns: + Ray cluster address string in format. Throws a + ConnectionError if zero or multiple active Ray instances are + autodetected. + """ + bootstrap_addr = canonicalize_bootstrap_address(addr, temp_dir=temp_dir) + if bootstrap_addr is not None: + return bootstrap_addr + + running_gcs_addresses = find_gcs_addresses() + if len(running_gcs_addresses) == 0: + raise ConnectionError( + "Could not find any running Ray instance. " + "Please specify the one to connect to by setting the `--address` " + "flag or `RAY_ADDRESS` environment variable." + ) + if len(running_gcs_addresses) > 1: + raise ConnectionError( + f"Found multiple active Ray instances: {running_gcs_addresses}. " + "Please specify the one to connect to by setting the `--address` " + "flag or `RAY_ADDRESS` environment variable." + ) + return running_gcs_addresses.pop() + + +def extract_ip_port(bootstrap_address: str): + if ":" not in bootstrap_address: + raise ValueError( + f"Malformed address {bootstrap_address}. " f"Expected ':'." + ) + ip, _, port = bootstrap_address.rpartition(":") + try: + port = int(port) + except ValueError: + raise ValueError(f"Malformed address port {port}. Must be an integer.") + if port < 1024 or port > 65535: + raise ValueError( + f"Invalid address port {port}. Must be between 1024 " + "and 65535 (inclusive)." + ) + return ip, port + + +def resolve_ip_for_localhost(address: str): + """Convert to a remotely reachable IP if the address is "localhost" + or "127.0.0.1". Otherwise do nothing. + + Args: + address: This can be either a string containing a hostname (or an IP + address) and a port or it can be just an IP address. + + Returns: + The same address but with the local host replaced by remotely + reachable IP. + """ + if not address: + raise ValueError(f"Malformed address: {address}") + address_parts = address.split(":") + if address_parts[0] == "127.0.0.1" or address_parts[0] == "localhost": + # Make sure localhost isn't resolved to the loopback ip + ip_address = get_node_ip_address() + return ":".join([ip_address] + address_parts[1:]) + else: + return address + + +def node_ip_address_from_perspective(address: str): + """IP address by which the local node can be reached *from* the `address`. + + Args: + address: The IP address and port of any known live service on the + network you care about. + + Returns: + The IP address by which the local node can be reached from the address. + """ + ip_address, port = address.split(":") + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + # This command will raise an exception if there is no internet + # connection. + s.connect((ip_address, int(port))) + node_ip_address = s.getsockname()[0] + except OSError as e: + node_ip_address = "127.0.0.1" + # [Errno 101] Network is unreachable + if e.errno == errno.ENETUNREACH: + try: + # try get node ip address from host name + host_name = socket.getfqdn(socket.gethostname()) + node_ip_address = socket.gethostbyname(host_name) + except Exception: + pass + finally: + s.close() + + return node_ip_address + + +# NOTE: This API should not be used when you obtain the +# IP address when ray.init is not called because +# it cannot find the IP address if it is specified by +# ray start --node-ip-address. You should instead use +# get_cached_node_ip_address. +def get_node_ip_address(address="8.8.8.8:53"): + if ray._private.worker._global_node is not None: + return ray._private.worker._global_node.node_ip_address + if not ray_constants.ENABLE_RAY_CLUSTER: + # Use loopback IP as the local IP address to prevent bothersome + # firewall popups on OSX and Windows. + # https://github.com/ray-project/ray/issues/18730. + return "127.0.0.1" + return node_ip_address_from_perspective(address) + + +def get_cached_node_ip_address(session_dir: str) -> str: + """Get a node address cached on this session. + + If a ray instance is started by `ray start --node-ip-address`, + the node ip address is cached to a file RAY_NODE_IP_FILENAME. + Otherwise, the file exists, but it is emptyl. + + This API is process-safe, meaning the file access is protected by + a file lock. + + Args: + session_dir: Path to the Ray session directory. + + Returns: + node_ip_address cached on the current node. None if the node + the file doesn't exist, meaning ray instance hasn't been + started on a current node. If node_ip_address is not written + to a file, it means --node-ip-address is not given, and in this + case, we find the IP address ourselves. + """ + file_path = Path(os.path.join(session_dir, RAY_NODE_IP_FILENAME)) + cached_node_ip_address = {} + + with FileLock(str(file_path.absolute()) + ".lock"): + if not file_path.exists(): + return None + + with file_path.open() as f: + cached_node_ip_address.update(json.load(f)) + + if "node_ip_address" in cached_node_ip_address: + return cached_node_ip_address["node_ip_address"] + else: + return ray.util.get_node_ip_address() + + +def write_node_ip_address(session_dir: str, node_ip_address: Optional[str]) -> None: + """Write a node ip address of the current session to + RAY_NODE_IP_FILENAME. + + If a ray instance is started by `ray start --node-ip-address`, + the node ip address is cached to a file RAY_NODE_IP_FILENAME. + + This API is process-safe, meaning the file access is protected by + a file lock. + + The file contains a single string node_ip_address. If nothing + is written, it means --node-ip-address was not given, and Ray + resolves the IP address on its own. It assumes in a single node, + you can have only 1 IP address (which is the assumption ray + has in general). + + node_ip_address is the ip address of the current node. + + Args: + session_dir: The path to Ray session directory. + node_ip_address: The node IP address of the current node. + If None, it means the node ip address is not given + by --node-ip-address. In this case, we don't write + anything to a file. + """ + file_path = Path(os.path.join(session_dir, RAY_NODE_IP_FILENAME)) + cached_node_ip_address = {} + + with FileLock(str(file_path.absolute()) + ".lock"): + if not file_path.exists(): + with file_path.open(mode="w") as f: + json.dump({}, f) + + with file_path.open() as f: + cached_node_ip_address.update(json.load(f)) + + cached_node_ip = cached_node_ip_address.get("node_ip_address") + + if node_ip_address is not None: + if cached_node_ip: + if cached_node_ip == node_ip_address: + # Nothing to do. + return + else: + logger.warning( + "The node IP address of the current host recorded " + f"in {RAY_NODE_IP_FILENAME} ({cached_node_ip}) " + "is different from the current IP address: " + f"{node_ip_address}. Ray will use {node_ip_address} " + "as the current node's IP address. " + "Creating 2 instances in the same host with different " + "IP address is not supported. " + "Please create an enhnacement request to" + "https://github.com/ray-project/ray/issues." + ) + + cached_node_ip_address["node_ip_address"] = node_ip_address + with file_path.open(mode="w") as f: + json.dump(cached_node_ip_address, f) + + +def get_node_instance_id(): + """Get the specified node instance id of the current node. + + Returns: + The node instance id of the current node. + """ + return os.getenv("RAY_CLOUD_INSTANCE_ID", "") + + +def create_redis_client(redis_address, password=None, username=None): + """Create a Redis client. + + Args: + redis_address: The IP address and port of the Redis server. + password: The password for Redis authentication. + username: The username for Redis authentication. + + Returns: + A Redis client. + """ + import redis + + if not hasattr(create_redis_client, "instances"): + create_redis_client.instances = {} + + num_retries = ray_constants.START_REDIS_WAIT_RETRIES + delay = 0.001 + for i in range(num_retries): + cli = create_redis_client.instances.get(redis_address) + if cli is None: + redis_ip_address, redis_port = extract_ip_port( + canonicalize_bootstrap_address_or_die(redis_address) + ) + cli = redis.StrictRedis( + host=redis_ip_address, + port=int(redis_port), + username=username, + password=password, + ) + create_redis_client.instances[redis_address] = cli + try: + cli.ping() + return cli + except Exception as e: + create_redis_client.instances.pop(redis_address) + if i >= num_retries - 1: + raise RuntimeError( + f"Unable to connect to Redis at {redis_address}: {e}" + ) + # Wait a little bit. + time.sleep(delay) + # Make sure the retry interval doesn't increase too large. + delay = min(1, delay * 2) + + +def start_ray_process( + command: List[str], + process_type: str, + fate_share: bool, + env_updates: Optional[dict] = None, + cwd: Optional[str] = None, + use_valgrind: bool = False, + use_gdb: bool = False, + use_valgrind_profiler: bool = False, + use_perftools_profiler: bool = False, + use_tmux: bool = False, + stdout_file: Optional[IO[AnyStr]] = None, + stderr_file: Optional[IO[AnyStr]] = None, + pipe_stdin: bool = False, +): + """Start one of the Ray processes. + + TODO(rkn): We need to figure out how these commands interact. For example, + it may only make sense to start a process in gdb if we also start it in + tmux. Similarly, certain combinations probably don't make sense, like + simultaneously running the process in valgrind and the profiler. + + Args: + command: The command to use to start the Ray process. + process_type: The type of the process that is being started + (e.g., "raylet"). + fate_share: If true, the child will be killed if its parent (us) dies. + True must only be passed after detection of this functionality. + env_updates: A dictionary of additional environment variables to + run the command with (in addition to the caller's environment + variables). + cwd: The directory to run the process in. + use_valgrind: True if we should start the process in valgrind. + use_gdb: True if we should start the process in gdb. + use_valgrind_profiler: True if we should start the process in + the valgrind profiler. + use_perftools_profiler: True if we should profile the process + using perftools. + use_tmux: True if we should start the process in tmux. + stdout_file: A file handle opened for writing to redirect stdout to. If + no redirection should happen, then this should be None. + stderr_file: A file handle opened for writing to redirect stderr to. If + no redirection should happen, then this should be None. + pipe_stdin: If true, subprocess.PIPE will be passed to the process as + stdin. + + Returns: + Information about the process that was started including a handle to + the process that was started. + """ + # Detect which flags are set through environment variables. + valgrind_env_var = f"RAY_{process_type.upper()}_VALGRIND" + if os.environ.get(valgrind_env_var) == "1": + logger.info("Detected environment variable '%s'.", valgrind_env_var) + use_valgrind = True + valgrind_profiler_env_var = f"RAY_{process_type.upper()}_VALGRIND_PROFILER" + if os.environ.get(valgrind_profiler_env_var) == "1": + logger.info("Detected environment variable '%s'.", valgrind_profiler_env_var) + use_valgrind_profiler = True + perftools_profiler_env_var = f"RAY_{process_type.upper()}_PERFTOOLS_PROFILER" + if os.environ.get(perftools_profiler_env_var) == "1": + logger.info("Detected environment variable '%s'.", perftools_profiler_env_var) + use_perftools_profiler = True + tmux_env_var = f"RAY_{process_type.upper()}_TMUX" + if os.environ.get(tmux_env_var) == "1": + logger.info("Detected environment variable '%s'.", tmux_env_var) + use_tmux = True + gdb_env_var = f"RAY_{process_type.upper()}_GDB" + if os.environ.get(gdb_env_var) == "1": + logger.info("Detected environment variable '%s'.", gdb_env_var) + use_gdb = True + # Jemalloc memory profiling. + if os.environ.get("LD_PRELOAD") is None: + jemalloc_lib_path = os.environ.get(RAY_JEMALLOC_LIB_PATH, JEMALLOC_SO) + jemalloc_conf = os.environ.get(RAY_JEMALLOC_CONF) + jemalloc_comps = os.environ.get(RAY_JEMALLOC_PROFILE) + jemalloc_comps = [] if not jemalloc_comps else jemalloc_comps.split(",") + jemalloc_env_vars = propagate_jemalloc_env_var( + jemalloc_path=jemalloc_lib_path, + jemalloc_conf=jemalloc_conf, + jemalloc_comps=jemalloc_comps, + process_type=process_type, + ) + else: + jemalloc_env_vars = {} + + use_jemalloc_mem_profiler = "MALLOC_CONF" in jemalloc_env_vars + + if ( + sum( + [ + use_gdb, + use_valgrind, + use_valgrind_profiler, + use_perftools_profiler, + use_jemalloc_mem_profiler, + ] + ) + > 1 + ): + raise ValueError( + "At most one of the 'use_gdb', 'use_valgrind', " + "'use_valgrind_profiler', 'use_perftools_profiler', " + "and 'use_jemalloc_mem_profiler' flags can " + "be used at a time." + ) + if env_updates is None: + env_updates = {} + if not isinstance(env_updates, dict): + raise ValueError("The 'env_updates' argument must be a dictionary.") + + modified_env = os.environ.copy() + modified_env.update(env_updates) + + if use_gdb: + if not use_tmux: + raise ValueError( + "If 'use_gdb' is true, then 'use_tmux' must be true as well." + ) + + # TODO(suquark): Any better temp file creation here? + gdb_init_path = os.path.join( + ray._common.utils.get_ray_temp_dir(), + f"gdb_init_{process_type}_{time.time()}", + ) + ray_process_path = command[0] + ray_process_args = command[1:] + run_args = " ".join(["'{}'".format(arg) for arg in ray_process_args]) + with open(gdb_init_path, "w") as gdb_init_file: + gdb_init_file.write(f"run {run_args}") + command = ["gdb", ray_process_path, "-x", gdb_init_path] + + if use_valgrind: + command = [ + "valgrind", + "--track-origins=yes", + "--leak-check=full", + "--show-leak-kinds=all", + "--leak-check-heuristics=stdstring", + "--error-exitcode=1", + ] + command + + if use_valgrind_profiler: + command = ["valgrind", "--tool=callgrind"] + command + + if use_perftools_profiler: + modified_env["LD_PRELOAD"] = os.environ["PERFTOOLS_PATH"] + modified_env["CPUPROFILE"] = os.environ["PERFTOOLS_LOGFILE"] + + modified_env.update(jemalloc_env_vars) + + if use_tmux: + # The command has to be created exactly as below to ensure that it + # works on all versions of tmux. (Tested with tmux 1.8-5, travis' + # version, and tmux 2.1) + command = ["tmux", "new-session", "-d", f"{' '.join(command)}"] + + if fate_share: + assert ray._private.utils.detect_fate_sharing_support(), ( + "kernel-level fate-sharing must only be specified if " + "detect_fate_sharing_support() has returned True" + ) + + def preexec_fn(): + import signal + + signal.pthread_sigmask(signal.SIG_BLOCK, {signal.SIGINT}) + if fate_share and sys.platform.startswith("linux"): + ray._private.utils.set_kill_on_parent_death_linux() + + win32_fate_sharing = fate_share and sys.platform == "win32" + # With Windows fate-sharing, we need special care: + # The process must be added to the job before it is allowed to execute. + # Otherwise, there's a race condition: the process might spawn children + # before the process itself is assigned to the job. + # After that point, its children will not be added to the job anymore. + CREATE_SUSPENDED = 0x00000004 # from Windows headers + if sys.platform == "win32": + # CreateProcess, which underlies Popen, is limited to + # 32,767 characters, including the Unicode terminating null + # character + total_chrs = sum([len(x) for x in command]) + if total_chrs > 31766: + raise ValueError( + f"command is limited to a total of 31767 characters, " + f"got {total_chrs}" + ) + + process = ConsolePopen( + command, + env=modified_env, + cwd=cwd, + stdout=stdout_file, + stderr=stderr_file, + stdin=subprocess.PIPE if pipe_stdin else None, + preexec_fn=preexec_fn if sys.platform != "win32" else None, + creationflags=CREATE_SUSPENDED if win32_fate_sharing else 0, + ) + + if win32_fate_sharing: + try: + ray._private.utils.set_kill_child_on_death_win32(process) + psutil.Process(process.pid).resume() + except (psutil.Error, OSError): + process.kill() + raise + + def _get_stream_name(stream): + if stream is not None: + try: + return stream.name + except AttributeError: + return str(stream) + return None + + return ProcessInfo( + process=process, + stdout_file=_get_stream_name(stdout_file), + stderr_file=_get_stream_name(stderr_file), + use_valgrind=use_valgrind, + use_gdb=use_gdb, + use_valgrind_profiler=use_valgrind_profiler, + use_perftools_profiler=use_perftools_profiler, + use_tmux=use_tmux, + ) + + +def start_reaper(fate_share=None): + """Start the reaper process. + + This is a lightweight process that simply + waits for its parent process to die and then terminates its own + process group. This allows us to ensure that ray processes are always + terminated properly so long as that process itself isn't SIGKILLed. + + Returns: + ProcessInfo for the process that was started. + """ + # Make ourselves a process group leader so that the reaper can clean + # up other ray processes without killing the process group of the + # process that started us. + try: + if sys.platform != "win32": + os.setpgrp() + except OSError as e: + errcode = e.errno + if errcode == errno.EPERM and os.getpgrp() == os.getpid(): + # Nothing to do; we're already a session leader. + pass + else: + logger.warning( + f"setpgrp failed, processes may not be cleaned up properly: {e}." + ) + # Don't start the reaper in this case as it could result in killing + # other user processes. + return None + + reaper_filepath = os.path.join(RAY_PATH, RAY_PRIVATE_DIR, "ray_process_reaper.py") + command = [sys.executable, "-u", reaper_filepath] + process_info = start_ray_process( + command, + ray_constants.PROCESS_TYPE_REAPER, + pipe_stdin=True, + fate_share=fate_share, + ) + return process_info + + +def start_log_monitor( + session_dir: str, + logs_dir: str, + gcs_address: str, + fate_share: Optional[bool] = None, + max_bytes: int = 0, + backup_count: int = 0, + stdout_filepath: Optional[str] = None, + stderr_filepath: Optional[str] = None, +): + """Start a log monitor process. + + Args: + session_dir: The session directory. + logs_dir: The directory of logging files. + gcs_address: GCS address for pubsub. + fate_share: Whether to share fate between log_monitor + and this process. + max_bytes: Log rotation parameter. Corresponding to + RotatingFileHandler's maxBytes. + backup_count: Log rotation parameter. Corresponding to + RotatingFileHandler's backupCount. + redirect_logging: Whether we should redirect logging to + the provided log directory. + stdout_filepath: The file path to dump log monitor stdout. + If None, stdout is not redirected. + stderr_filepath: The file path to dump log monitor stderr. + If None, stderr is not redirected. + + Returns: + ProcessInfo for the process that was started. + """ + log_monitor_filepath = os.path.join(RAY_PATH, RAY_PRIVATE_DIR, "log_monitor.py") + + command = [ + sys.executable, + "-u", + log_monitor_filepath, + f"--session-dir={session_dir}", + f"--logs-dir={logs_dir}", + f"--gcs-address={gcs_address}", + f"--logging-rotate-bytes={max_bytes}", + f"--logging-rotate-backup-count={backup_count}", + ] + + if stdout_filepath: + command.append(f"--stdout-filepath={stdout_filepath}") + if stderr_filepath: + command.append(f"--stderr-filepath={stderr_filepath}") + + if stdout_filepath is None and stderr_filepath is None: + # If not redirecting logging to files, unset log filename. + # This will cause log records to go to stderr. + command.append("--logging-filename=") + # Use stderr log format with the component name as a message prefix. + logging_format = ray_constants.LOGGER_FORMAT_STDERR.format( + component=ray_constants.PROCESS_TYPE_LOG_MONITOR + ) + command.append(f"--logging-format={logging_format}") + + stdout_file = None + if stdout_filepath: + stdout_file = open(os.devnull, "w") + + stderr_file = None + if stderr_filepath: + stderr_file = open(os.devnull, "w") + + process_info = start_ray_process( + command, + ray_constants.PROCESS_TYPE_LOG_MONITOR, + stdout_file=stdout_file, + stderr_file=stderr_file, + fate_share=fate_share, + ) + return process_info + + +def start_api_server( + include_dashboard: Optional[bool], + raise_on_failure: bool, + host: str, + gcs_address: str, + cluster_id_hex: str, + node_ip_address: str, + temp_dir: str, + logdir: str, + session_dir: str, + port: Optional[int] = None, + fate_share: Optional[bool] = None, + max_bytes: int = 0, + backup_count: int = 0, + stdout_filepath: Optional[str] = None, + stderr_filepath: Optional[str] = None, +): + """Start a API server process. + + Args: + include_dashboard: If true, this will load all dashboard-related modules + when starting the API server, or fail. If None, it will load all + dashboard-related modules conditioned on dependencies being present. + Otherwise, it will only start the modules that are not relevant to + the dashboard. + raise_on_failure: If true, this will raise an exception + if we fail to start the API server. Otherwise it will print + a warning if we fail to start the API server. + host: The host to bind the dashboard web server to. + gcs_address: The gcs address the dashboard should connect to + cluster_id_hex: Cluster ID in hex. + node_ip_address: The IP address where this is running. + temp_dir: The temporary directory used for log files and + information for this Ray session. + session_dir: The session directory under temp_dir. + It is used as a identifier of individual cluster. + logdir: The log directory used to generate dashboard log. + port: The port to bind the dashboard web server to. + Defaults to 8265. + max_bytes: Log rotation parameter. Corresponding to + RotatingFileHandler's maxBytes. + backup_count: Log rotation parameter. Corresponding to + RotatingFileHandler's backupCount. + stdout_filepath: The file path to dump dashboard stdout. + If None, stdout is not redirected. + stderr_filepath: The file path to dump dashboard stderr. + If None, stderr is not redirected. + + Returns: + A tuple of : + - Dashboard URL if dashboard enabled and started. + - ProcessInfo for the process that was started. + """ + try: + # Make sure port is available. + if port is None: + port_retries = 50 + port = ray_constants.DEFAULT_DASHBOARD_PORT + else: + port_retries = 0 + port_test_socket = socket.socket() + port_test_socket.setsockopt( + socket.SOL_SOCKET, + socket.SO_REUSEADDR, + 1, + ) + try: + port_test_socket.bind((host, port)) + port_test_socket.close() + except socket.error as e: + # 10013 on windows is a bit more broad than just + # "address in use": it can also indicate "permission denied". + # TODO: improve the error message? + if e.errno in {48, 98, 10013}: # address already in use. + raise ValueError( + f"Failed to bind to {host}:{port} because it's " + "already occupied. You can use `ray start " + "--dashboard-port ...` or `ray.init(dashboard_port=..." + ")` to select a different port." + ) + else: + raise e + # Make sure the process can start. + minimal: bool = not ray._private.utils.check_dashboard_dependencies_installed() + + # Explicitly check here that when the user explicitly specifies + # dashboard inclusion, the install is not minimal. + if include_dashboard and minimal: + logger.error( + "--include-dashboard is not supported when minimal ray is used. " + "Download ray[default] to use the dashboard." + ) + raise Exception("Cannot include dashboard with missing packages.") + + include_dash: bool = True if include_dashboard is None else include_dashboard + + # Start the dashboard process. + dashboard_dir = "dashboard" + dashboard_filepath = os.path.join(RAY_PATH, dashboard_dir, "dashboard.py") + + command = [ + *_build_python_executable_command_memory_profileable( + ray_constants.PROCESS_TYPE_DASHBOARD, + session_dir, + unbuffered=False, + ), + dashboard_filepath, + f"--host={host}", + f"--port={port}", + f"--port-retries={port_retries}", + f"--temp-dir={temp_dir}", + f"--log-dir={logdir}", + f"--session-dir={session_dir}", + f"--logging-rotate-bytes={max_bytes}", + f"--logging-rotate-backup-count={backup_count}", + f"--gcs-address={gcs_address}", + f"--cluster-id-hex={cluster_id_hex}", + f"--node-ip-address={node_ip_address}", + ] + + if stdout_filepath: + command.append(f"--stdout-filepath={stdout_filepath}") + if stderr_filepath: + command.append(f"--stderr-filepath={stderr_filepath}") + + if stdout_filepath is None and stderr_filepath is None: + # If not redirecting logging to files, unset log filename. + # This will cause log records to go to stderr. + command.append("--logging-filename=") + # Use stderr log format with the component name as a message prefix. + logging_format = ray_constants.LOGGER_FORMAT_STDERR.format( + component=ray_constants.PROCESS_TYPE_DASHBOARD + ) + command.append(f"--logging-format={logging_format}") + if minimal: + command.append("--minimal") + + if not include_dash: + # If dashboard is not included, load modules + # that are irrelevant to the dashboard. + # TODO(sang): Modules like job or state APIs should be + # loaded although dashboard is disabled. Fix it. + command.append("--modules-to-load=UsageStatsHead") + command.append("--disable-frontend") + + stdout_file = None + if stdout_filepath: + stdout_file = open(os.devnull, "w") + + stderr_file = None + if stderr_filepath: + stderr_file = open(os.devnull, "w") + + process_info = start_ray_process( + command, + ray_constants.PROCESS_TYPE_DASHBOARD, + stdout_file=stdout_file, + stderr_file=stderr_file, + fate_share=fate_share, + ) + + # Retrieve the dashboard url + gcs_client = GcsClient(address=gcs_address, cluster_id=cluster_id_hex) + ray.experimental.internal_kv._initialize_internal_kv(gcs_client) + dashboard_url = None + dashboard_returncode = None + for _ in range(200): + dashboard_url = ray.experimental.internal_kv._internal_kv_get( + ray_constants.DASHBOARD_ADDRESS, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + ) + if dashboard_url is not None: + dashboard_url = dashboard_url.decode("utf-8") + break + dashboard_returncode = process_info.process.poll() + if dashboard_returncode is not None: + break + # This is often on the critical path of ray.init() and ray start, + # so we need to poll often. + time.sleep(0.1) + + # Dashboard couldn't be started. + if dashboard_url is None: + returncode_str = ( + f", return code {dashboard_returncode}" + if dashboard_returncode is not None + else "" + ) + logger.error(f"Failed to start the dashboard {returncode_str}") + + def read_log(filename, lines_to_read): + """Read a log file and return the last 20 lines.""" + dashboard_log = os.path.join(logdir, filename) + # Read last n lines of dashboard log. The log file may be large. + lines_to_read = 20 + lines = [] + with open(dashboard_log, "rb") as f: + with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as mm: + end = mm.size() + for _ in range(lines_to_read): + sep = mm.rfind(b"\n", 0, end - 1) + if sep == -1: + break + lines.append(mm[sep + 1 : end].decode("utf-8")) + end = sep + lines.append( + f"The last {lines_to_read} lines of {dashboard_log} " + "(it contains the error message from the dashboard): " + ) + return lines + + if logdir: + lines_to_read = 20 + logger.error( + "Error should be written to 'dashboard.log' or " + "'dashboard.err'. We are printing the last " + f"{lines_to_read} lines for you. See " + "'https://docs.ray.io/en/master/ray-observability/user-guides/configure-logging.html#logging-directory-structure' " # noqa + "to find where the log file is." + ) + try: + lines = read_log("dashboard.log", lines_to_read=lines_to_read) + except Exception as e: + logger.error( + f"Couldn't read dashboard.log file. Error: {e}. " + "It means the dashboard is broken even before it " + "initializes the logger (mostly dependency issues). " + "Reading the dashboard.err file which contains stdout/stderr." + ) + # If we cannot read the .log file, we fallback to .err file. + # This is the case where dashboard couldn't be started at all + # and couldn't even initialize the logger to write logs to .log + # file. + try: + lines = read_log("dashboard.err", lines_to_read=lines_to_read) + except Exception as e: + raise Exception( + f"Failed to read dashboard.err file: {e}. " + "It is unexpected. Please report an issue to " + "Ray github. " + "https://github.com/ray-project/ray/issues" + ) + last_log_str = "\n" + "\n".join(reversed(lines[-lines_to_read:])) + raise Exception(last_log_str) + else: + # Is it reachable? + raise Exception("Failed to start a dashboard.") + + if minimal or not include_dash: + # If it is the minimal installation, the web url (dashboard url) + # shouldn't be configured because it doesn't start a server. + dashboard_url = "" + return dashboard_url, process_info + except Exception as e: + if raise_on_failure: + raise e from e + else: + logger.error(e) + return None, None + + +def get_address(redis_address): + parts = redis_address.split("://", 1) + enable_redis_ssl = False + if len(parts) == 1: + redis_ip_address, redis_port = parts[0].rsplit(":", 1) + else: + # rediss for SSL + if len(parts) != 2 or parts[0] not in ("redis", "rediss"): + raise ValueError( + f"Invalid redis address {redis_address}." + "Expected format is ip:port or redis://ip:port, " + "or rediss://ip:port for SSL." + ) + redis_ip_address, redis_port = parts[1].rsplit(":", 1) + if parts[0] == "rediss": + enable_redis_ssl = True + return redis_ip_address, redis_port, enable_redis_ssl + + +def start_gcs_server( + redis_address: str, + log_dir: str, + stdout_filepath: Optional[str], + stderr_filepath: Optional[str], + session_name: str, + redis_username: Optional[str] = None, + redis_password: Optional[str] = None, + config: Optional[dict] = None, + fate_share: Optional[bool] = None, + gcs_server_port: Optional[int] = None, + metrics_agent_port: Optional[int] = None, + node_ip_address: Optional[str] = None, +): + """Start a gcs server. + + Args: + redis_address: The address that the Redis server is listening on. + log_dir: The path of the dir where gcs log files are created. + stdout_filepath: The file path to dump gcs server stdout. + If None, stdout is not redirected. + stderr_filepath: The file path to dump gcs server stderr. + If None, stderr is not redirected. + session_name: The session name (cluster id) of this cluster. + redis_username: The username of the Redis server. + redis_password: The password of the Redis server. + config: Optional configuration that will + override defaults in RayConfig. + gcs_server_port: Port number of the gcs server. + metrics_agent_port: The port where metrics agent is bound to. + node_ip_address: IP Address of a node where gcs server starts. + + Returns: + ProcessInfo for the process that was started. + """ + assert gcs_server_port > 0 + + command = [ + GCS_SERVER_EXECUTABLE, + f"--log_dir={log_dir}", + f"--config_list={serialize_config(config)}", + f"--gcs_server_port={gcs_server_port}", + f"--metrics-agent-port={metrics_agent_port}", + f"--node-ip-address={node_ip_address}", + f"--session-name={session_name}", + f"--ray-commit={ray.__commit__}", + ] + + if stdout_filepath: + command += [f"--stdout_filepath={stdout_filepath}"] + if stderr_filepath: + command += [f"--stderr_filepath={stderr_filepath}"] + + if redis_address: + redis_ip_address, redis_port, enable_redis_ssl = get_address(redis_address) + + command += [ + f"--redis_address={redis_ip_address}", + f"--redis_port={redis_port}", + f"--redis_enable_ssl={'true' if enable_redis_ssl else 'false'}", + ] + if redis_username: + command += [f"--redis_username={redis_username}"] + if redis_password: + command += [f"--redis_password={redis_password}"] + + stdout_file = None + if stdout_filepath: + stdout_file = open(os.devnull, "w") + + stderr_file = None + if stderr_filepath: + stderr_file = open(os.devnull, "w") + + process_info = start_ray_process( + command, + ray_constants.PROCESS_TYPE_GCS_SERVER, + stdout_file=stdout_file, + stderr_file=stderr_file, + fate_share=fate_share, + ) + return process_info + + +def start_raylet( + redis_address: str, + gcs_address: str, + node_id: str, + node_ip_address: str, + node_manager_port: int, + raylet_name: str, + plasma_store_name: str, + cluster_id: str, + worker_path: str, + setup_worker_path: str, + temp_dir: str, + session_dir: str, + resource_dir: str, + log_dir: str, + resource_spec, + plasma_directory: str, + fallback_directory: str, + object_store_memory: int, + session_name: str, + is_head_node: bool, + resource_isolation_config: ResourceIsolationConfig, + min_worker_port: Optional[int] = None, + max_worker_port: Optional[int] = None, + worker_port_list: Optional[List[int]] = None, + object_manager_port: Optional[int] = None, + redis_username: Optional[str] = None, + redis_password: Optional[str] = None, + metrics_agent_port: Optional[int] = None, + metrics_export_port: Optional[int] = None, + dashboard_agent_listen_port: Optional[int] = None, + runtime_env_agent_port: Optional[int] = None, + use_valgrind: bool = False, + use_profiler: bool = False, + raylet_stdout_filepath: Optional[str] = None, + raylet_stderr_filepath: Optional[str] = None, + dashboard_agent_stdout_filepath: Optional[str] = None, + dashboard_agent_stderr_filepath: Optional[str] = None, + runtime_env_agent_stdout_filepath: Optional[str] = None, + runtime_env_agent_stderr_filepath: Optional[str] = None, + huge_pages: bool = False, + fate_share: Optional[bool] = None, + socket_to_use: Optional[int] = None, + max_bytes: int = 0, + backup_count: int = 0, + ray_debugger_external: bool = False, + env_updates: Optional[dict] = None, + node_name: Optional[str] = None, + webui: Optional[str] = None, + labels: Optional[dict] = None, +): + """Start a raylet, which is a combined local scheduler and object manager. + + Args: + redis_address: The address of the primary Redis server. + gcs_address: The address of GCS server. + node_id: The hex ID of this node. + node_ip_address: The IP address of this node. + node_manager_port: The port to use for the node manager. If it's + 0, a random port will be used. + raylet_name: The name of the raylet socket to create. + plasma_store_name: The name of the plasma store socket to connect + to. + worker_path: The path of the Python file that new worker + processes will execute. + setup_worker_path: The path of the Python file that will set up + the environment for the worker process. + temp_dir: The path of the temporary directory Ray will use. + session_dir: The path of this session. + resource_dir: The path of resource of this session . + log_dir: The path of the dir where log files are created. + resource_spec: Resources for this raylet. + plasma_directory: A directory where the Plasma memory mapped files will + be created. + fallback_directory: A directory where the Object store fallback files will be created. + object_store_memory: The amount of memory (in bytes) to start the + object store with. + session_name: The session name (cluster id) of this cluster. + resource_isolation_config: Resource isolation configuration for reserving + memory and cpu resources for ray system processes through cgroupv2 + is_head_node: whether this node is the head node. + min_worker_port: The lowest port number that workers will bind + on. If not set, random ports will be chosen. + max_worker_port: The highest port number that workers will bind + on. If set, min_worker_port must also be set. + worker_port_list: An explicit list of ports to be used for + workers (comma-separated). Overrides min_worker_port and + max_worker_port. + object_manager_port: The port to use for the object manager. If this is + None, then the object manager will choose its own port. + redis_username: The username to use when connecting to Redis. + redis_password: The password to use when connecting to Redis. + metrics_agent_port: The port where metrics agent is bound to. + metrics_export_port: The port at which metrics are exposed to. + dashboard_agent_listen_port: The port at which the dashboard agent + listens to for HTTP. + runtime_env_agent_port: The port at which the runtime env agent + listens to for HTTP. + use_valgrind: True if the raylet should be started inside + of valgrind. If this is True, use_profiler must be False. + use_profiler: True if the raylet should be started inside + a profiler. If this is True, use_valgrind must be False. + raylet_stdout_filepath: The file path to dump raylet stdout. + If None, stdout is not redirected. + raylet_stderr_filepath: The file path to dump raylet stderr. + If None, stderr is not redirected. + dashboard_agent_stdout_filepath: The file path to dump + dashboard agent stdout. If None, stdout is not redirected. + dashboard_agent_stderr_filepath: The file path to dump + dashboard agent stderr. If None, stderr is not redirected. + runtime_env_agent_stdout_filepath: The file path to dump + runtime env agent stdout. If None, stdout is not redirected. + runtime_env_agent_stderr_filepath: The file path to dump + runtime env agent stderr. If None, stderr is not redirected. + huge_pages: Boolean flag indicating whether to start the Object + Store with hugetlbfs support. Requires plasma_directory. + fate_share: Whether to share fate between raylet and this process. + max_bytes: Log rotation parameter. Corresponding to + RotatingFileHandler's maxBytes. + backup_count: Log rotation parameter. Corresponding to + RotatingFileHandler's backupCount. + ray_debugger_external: True if the Ray debugger should be made + available externally to this node. + env_updates: Environment variable overrides. + node_name: The name of the node. + webui: The url of the UI. + labels: The key-value labels of the node. + Returns: + ProcessInfo for the process that was started. + """ + assert node_manager_port is not None and type(node_manager_port) is int + + if use_valgrind and use_profiler: + raise ValueError("Cannot use valgrind and profiler at the same time.") + + assert resource_spec.resolved() + static_resources = resource_spec.to_resource_dict() + + # Limit the number of workers that can be started in parallel by the + # raylet. However, make sure it is at least 1. + num_cpus_static = static_resources.get("CPU", 0) + maximum_startup_concurrency = max( + 1, min(multiprocessing.cpu_count(), num_cpus_static) + ) + + # Format the resource argument in a form like 'CPU,1.0,GPU,0,Custom,3'. + resource_argument = ",".join( + ["{},{}".format(*kv) for kv in static_resources.items()] + ) + + has_java_command = False + if shutil.which("java") is not None: + has_java_command = True + + ray_java_installed = False + try: + jars_dir = get_ray_jars_dir() + if os.path.exists(jars_dir): + ray_java_installed = True + except Exception: + pass + + include_java = has_java_command and ray_java_installed + if include_java is True: + java_worker_command = build_java_worker_command( + gcs_address, + plasma_store_name, + raylet_name, + redis_username, + redis_password, + session_dir, + node_ip_address, + setup_worker_path, + ) + else: + java_worker_command = [] + + if os.path.exists(DEFAULT_WORKER_EXECUTABLE): + cpp_worker_command = build_cpp_worker_command( + gcs_address, + plasma_store_name, + raylet_name, + redis_username, + redis_password, + session_dir, + log_dir, + node_ip_address, + setup_worker_path, + ) + else: + cpp_worker_command = [] + + # Create the command that the Raylet will use to start workers. + # TODO(architkulkarni): Pipe in setup worker args separately instead of + # inserting them into start_worker_command and later erasing them if + # needed. + start_worker_command = ( + [ + sys.executable, + setup_worker_path, + ] + + _site_flags() # Inherit "-S" and "-s" flags from current Python interpreter. + + [ + worker_path, + f"--node-ip-address={node_ip_address}", + "--node-manager-port=RAY_NODE_MANAGER_PORT_PLACEHOLDER", + f"--object-store-name={plasma_store_name}", + f"--raylet-name={raylet_name}", + f"--redis-address={redis_address}", + f"--metrics-agent-port={metrics_agent_port}", + f"--logging-rotate-bytes={max_bytes}", + f"--logging-rotate-backup-count={backup_count}", + f"--runtime-env-agent-port={runtime_env_agent_port}", + f"--gcs-address={gcs_address}", + f"--session-name={session_name}", + f"--temp-dir={temp_dir}", + f"--webui={webui}", + f"--cluster-id={cluster_id}", + ] + ) + + if resource_isolation_config.is_enabled(): + # TODO(irabbani): enable passing args to raylet once the raylet has been modified + logging.info( + f"Resource isolation enabled with cgroup_path={resource_isolation_config.cgroup_path}, " + f"system_reserved_cpu={resource_isolation_config.system_reserved_cpu_weight} " + f"system_reserved_memory={resource_isolation_config.system_reserved_memory}" + ) + # start_worker_command.append("--enable-resource-isolation") + # start_worker_command.append(f"--cgroup-path={resource_isolation_config.cgroup_path}") + # start_worker_command.append(f"--system-reserved-cpu={resource_isolation_config.system_reserved_cpu_weight}") + # start_worker_command.append(f"--system-reserved-memory={resource_isolation_config.system_reserved_memory}") + + start_worker_command.append("RAY_WORKER_DYNAMIC_OPTION_PLACEHOLDER") + + if redis_username: + start_worker_command += [f"--redis-username={redis_username}"] + + if redis_password: + start_worker_command += [f"--redis-password={redis_password}"] + + # If the object manager port is None, then use 0 to cause the object + # manager to choose its own port. + if object_manager_port is None: + object_manager_port = 0 + + if min_worker_port is None: + min_worker_port = 0 + + if max_worker_port is None: + max_worker_port = 0 + + labels_json_str = "" + if labels: + labels_json_str = json.dumps(labels) + + dashboard_agent_command = [ + *_build_python_executable_command_memory_profileable( + ray_constants.PROCESS_TYPE_DASHBOARD_AGENT, session_dir + ), + os.path.join(RAY_PATH, "dashboard", "agent.py"), + f"--node-ip-address={node_ip_address}", + f"--metrics-export-port={metrics_export_port}", + f"--dashboard-agent-port={metrics_agent_port}", + f"--listen-port={dashboard_agent_listen_port}", + "--node-manager-port=RAY_NODE_MANAGER_PORT_PLACEHOLDER", + f"--object-store-name={plasma_store_name}", + f"--raylet-name={raylet_name}", + f"--temp-dir={temp_dir}", + f"--session-dir={session_dir}", + f"--log-dir={log_dir}", + f"--logging-rotate-bytes={max_bytes}", + f"--logging-rotate-backup-count={backup_count}", + f"--session-name={session_name}", + f"--gcs-address={gcs_address}", + f"--cluster-id-hex={cluster_id}", + ] + if dashboard_agent_stdout_filepath: + dashboard_agent_command.append( + f"--stdout-filepath={dashboard_agent_stdout_filepath}" + ) + if dashboard_agent_stderr_filepath: + dashboard_agent_command.append( + f"--stderr-filepath={dashboard_agent_stderr_filepath}" + ) + if ( + dashboard_agent_stdout_filepath is None + and dashboard_agent_stderr_filepath is None + ): + # If not redirecting logging to files, unset log filename. + # This will cause log records to go to stderr. + dashboard_agent_command.append("--logging-filename=") + # Use stderr log format with the component name as a message prefix. + logging_format = ray_constants.LOGGER_FORMAT_STDERR.format( + component=ray_constants.PROCESS_TYPE_DASHBOARD_AGENT + ) + dashboard_agent_command.append(f"--logging-format={logging_format}") + + if not ray._private.utils.check_dashboard_dependencies_installed(): + # If dependencies are not installed, it is the minimally packaged + # ray. We should restrict the features within dashboard agent + # that requires additional dependencies to be downloaded. + dashboard_agent_command.append("--minimal") + + runtime_env_agent_command = [ + *_build_python_executable_command_memory_profileable( + ray_constants.PROCESS_TYPE_RUNTIME_ENV_AGENT, session_dir + ), + os.path.join(RAY_PATH, "_private", "runtime_env", "agent", "main.py"), + f"--node-ip-address={node_ip_address}", + f"--runtime-env-agent-port={runtime_env_agent_port}", + f"--gcs-address={gcs_address}", + f"--cluster-id-hex={cluster_id}", + f"--runtime-env-dir={resource_dir}", + f"--logging-rotate-bytes={max_bytes}", + f"--logging-rotate-backup-count={backup_count}", + f"--log-dir={log_dir}", + f"--temp-dir={temp_dir}", + ] + if runtime_env_agent_stdout_filepath: + runtime_env_agent_command.append( + f"--stdout-filepath={runtime_env_agent_stdout_filepath}" + ) + if runtime_env_agent_stderr_filepath: + runtime_env_agent_command.append( + f"--stderr-filepath={runtime_env_agent_stderr_filepath}" + ) + if ( + runtime_env_agent_stdout_filepath is None + and runtime_env_agent_stderr_filepath is None + ): + # If not redirecting logging to files, unset log filename. + # This will cause log records to go to stderr. + runtime_env_agent_command.append("--logging-filename=") + # Use stderr log format with the component name as a message prefix. + logging_format = ray_constants.LOGGER_FORMAT_STDERR.format( + component=ray_constants.PROCESS_TYPE_RUNTIME_ENV_AGENT + ) + runtime_env_agent_command.append(f"--logging-format={logging_format}") + + command = [ + RAYLET_EXECUTABLE, + f"--raylet_socket_name={raylet_name}", + f"--store_socket_name={plasma_store_name}", + f"--object_manager_port={object_manager_port}", + f"--min_worker_port={min_worker_port}", + f"--max_worker_port={max_worker_port}", + f"--node_manager_port={node_manager_port}", + f"--node_id={node_id}", + f"--node_ip_address={node_ip_address}", + f"--maximum_startup_concurrency={maximum_startup_concurrency}", + f"--static_resource_list={resource_argument}", + f"--python_worker_command={subprocess.list2cmdline(start_worker_command)}", # noqa + f"--java_worker_command={subprocess.list2cmdline(java_worker_command)}", # noqa + f"--cpp_worker_command={subprocess.list2cmdline(cpp_worker_command)}", # noqa + f"--native_library_path={DEFAULT_NATIVE_LIBRARY_PATH}", + f"--temp_dir={temp_dir}", + f"--session_dir={session_dir}", + f"--log_dir={log_dir}", + f"--resource_dir={resource_dir}", + f"--metrics-agent-port={metrics_agent_port}", + f"--metrics_export_port={metrics_export_port}", + f"--runtime_env_agent_port={runtime_env_agent_port}", + f"--object_store_memory={object_store_memory}", + f"--plasma_directory={plasma_directory}", + f"--fallback_directory={fallback_directory}", + f"--ray-debugger-external={1 if ray_debugger_external else 0}", + f"--gcs-address={gcs_address}", + f"--session-name={session_name}", + f"--labels={labels_json_str}", + f"--cluster-id={cluster_id}", + ] + + if raylet_stdout_filepath: + command.append(f"--stdout_filepath={raylet_stdout_filepath}") + if raylet_stderr_filepath: + command.append(f"--stderr_filepath={raylet_stderr_filepath}") + + if is_head_node: + command.append("--head") + + if worker_port_list is not None: + command.append(f"--worker_port_list={worker_port_list}") + command.append( + "--num_prestart_python_workers={}".format(int(resource_spec.num_cpus)) + ) + command.append( + "--dashboard_agent_command={}".format( + subprocess.list2cmdline(dashboard_agent_command) + ) + ) + command.append( + "--runtime_env_agent_command={}".format( + subprocess.list2cmdline(runtime_env_agent_command) + ) + ) + if huge_pages: + command.append("--huge_pages") + if socket_to_use: + socket_to_use.close() + if node_name is not None: + command.append( + f"--node-name={node_name}", + ) + + stdout_file = None + if raylet_stdout_filepath: + stdout_file = open(os.devnull, "w") + + stderr_file = None + if raylet_stderr_filepath: + stderr_file = open(os.devnull, "w") + + process_info = start_ray_process( + command, + ray_constants.PROCESS_TYPE_RAYLET, + use_valgrind=use_valgrind, + use_gdb=False, + use_valgrind_profiler=use_profiler, + use_perftools_profiler=("RAYLET_PERFTOOLS_PATH" in os.environ), + stdout_file=stdout_file, + stderr_file=stderr_file, + fate_share=fate_share, + env_updates=env_updates, + ) + return process_info + + +def get_ray_jars_dir(): + """Return a directory where all ray-related jars and + their dependencies locate.""" + current_dir = RAY_PATH + jars_dir = os.path.abspath(os.path.join(current_dir, "jars")) + if not os.path.exists(jars_dir): + raise RuntimeError( + "Ray jars is not packaged into ray. " + "Please build ray with java enabled " + "(set env var RAY_INSTALL_JAVA=1)" + ) + return os.path.abspath(os.path.join(current_dir, "jars")) + + +def build_java_worker_command( + bootstrap_address: str, + plasma_store_name: str, + raylet_name: str, + redis_username: str, + redis_password: str, + session_dir: str, + node_ip_address: str, + setup_worker_path: str, +): + """This method assembles the command used to start a Java worker. + + Args: + bootstrap_address: Bootstrap address of ray cluster. + plasma_store_name: The name of the plasma store socket to connect + to. + raylet_name: The name of the raylet socket to create. + redis_username: The username to connect to Redis. + redis_password: The password to connect to Redis. + session_dir: The path of this session. + node_ip_address: The IP address for this node. + setup_worker_path: The path of the Python file that will set up + the environment for the worker process. + Returns: + The command string for starting Java worker. + """ + pairs = [] + if bootstrap_address is not None: + pairs.append(("ray.address", bootstrap_address)) + pairs.append(("ray.raylet.node-manager-port", "RAY_NODE_MANAGER_PORT_PLACEHOLDER")) + + if plasma_store_name is not None: + pairs.append(("ray.object-store.socket-name", plasma_store_name)) + + if raylet_name is not None: + pairs.append(("ray.raylet.socket-name", raylet_name)) + + if redis_username is not None: + pairs.append(("ray.redis.username", redis_username)) + + if redis_password is not None: + pairs.append(("ray.redis.password", redis_password)) + + if node_ip_address is not None: + pairs.append(("ray.node-ip", node_ip_address)) + + pairs.append(("ray.home", RAY_HOME)) + pairs.append(("ray.logging.dir", os.path.join(session_dir, "logs"))) + pairs.append(("ray.session-dir", session_dir)) + command = ( + [sys.executable] + + [setup_worker_path] + + ["-D{}={}".format(*pair) for pair in pairs] + ) + + command += ["RAY_WORKER_DYNAMIC_OPTION_PLACEHOLDER"] + command += ["io.ray.runtime.runner.worker.DefaultWorker"] + + return command + + +def build_cpp_worker_command( + bootstrap_address: str, + plasma_store_name: str, + raylet_name: str, + redis_username: str, + redis_password: str, + session_dir: str, + log_dir: str, + node_ip_address: str, + setup_worker_path: str, +): + """This method assembles the command used to start a CPP worker. + + Args: + bootstrap_address: The bootstrap address of the cluster. + plasma_store_name: The name of the plasma store socket to connect + to. + raylet_name: The name of the raylet socket to create. + redis_username: The username to connect to Redis. + redis_password: The password to connect to Redis. + session_dir: The path of this session. + log_dir: The path of logs. + node_ip_address: The ip address for this node. + setup_worker_path: The path of the Python file that will set up + the environment for the worker process. + Returns: + The command string for starting CPP worker. + """ + + command = [ + sys.executable, + setup_worker_path, + DEFAULT_WORKER_EXECUTABLE, + f"--ray_plasma_store_socket_name={plasma_store_name}", + f"--ray_raylet_socket_name={raylet_name}", + "--ray_node_manager_port=RAY_NODE_MANAGER_PORT_PLACEHOLDER", + f"--ray_address={bootstrap_address}", + f"--ray_redis_username={redis_username}", + f"--ray_redis_password={redis_password}", + f"--ray_session_dir={session_dir}", + f"--ray_logs_dir={log_dir}", + f"--ray_node_ip_address={node_ip_address}", + "RAY_WORKER_DYNAMIC_OPTION_PLACEHOLDER", + ] + + return command + + +def determine_plasma_store_config( + object_store_memory: int, + temp_dir: str, + plasma_directory: Optional[str] = None, + fallback_directory: Optional[str] = None, + huge_pages: bool = False, +): + """Figure out how to configure the plasma object store. + + This will determine: + 1. which directory to use for the plasma store. On Linux, + we will try to use /dev/shm unless the shared memory file system is too + small, in which case we will fall back to /tmp. If any of the object store + memory or plasma directory parameters are specified by the user, then those + values will be preserved. + 2. which directory to use for the fallback files. It will default to the temp_dir + if it is not extracted from the object_spilling_config. + + Args: + object_store_memory: The object store memory to use. + plasma_directory: The user-specified plasma directory parameter. + fallback_directory: The path extracted from the object_spilling_config when the + object spilling config is set and the spilling type is to + filesystem. + huge_pages: The user-specified huge pages parameter. + + Returns: + A tuple of plasma directory to use, the fallback directory to use, and the + object store memory to use. If it is specified by the user, then that value will + be preserved. + """ + if not isinstance(object_store_memory, int): + object_store_memory = int(object_store_memory) + + if huge_pages and not (sys.platform == "linux" or sys.platform == "linux2"): + raise ValueError("The huge_pages argument is only supported on Linux.") + + system_memory = ray._common.utils.get_system_memory() + + # Determine which directory to use. By default, use /tmp on MacOS and + # /dev/shm on Linux, unless the shared-memory file system is too small, + # in which case we default to /tmp on Linux. + if plasma_directory is None: + if sys.platform == "linux" or sys.platform == "linux2": + shm_avail = ray._private.utils.get_shared_memory_bytes() + # Compare the requested memory size to the memory available in + # /dev/shm. + if shm_avail >= object_store_memory: + plasma_directory = "/dev/shm" + elif ( + not os.environ.get("RAY_OBJECT_STORE_ALLOW_SLOW_STORAGE") + and object_store_memory > ray_constants.REQUIRE_SHM_SIZE_THRESHOLD + ): + raise ValueError( + "The configured object store size ({} GB) exceeds " + "/dev/shm size ({} GB). This will harm performance. " + "Consider deleting files in /dev/shm or increasing its " + "size with " + "--shm-size in Docker. To ignore this warning, " + "set RAY_OBJECT_STORE_ALLOW_SLOW_STORAGE=1.".format( + object_store_memory / 1e9, shm_avail / 1e9 + ) + ) + else: + plasma_directory = ray._common.utils.get_user_temp_dir() + logger.warning( + "WARNING: The object store is using {} instead of " + "/dev/shm because /dev/shm has only {} bytes available. " + "This will harm performance! You may be able to free up " + "space by deleting files in /dev/shm. If you are inside a " + "Docker container, you can increase /dev/shm size by " + "passing '--shm-size={:.2f}gb' to 'docker run' (or add it " + "to the run_options list in a Ray cluster config). Make " + "sure to set this to more than 30% of available RAM.".format( + ray._common.utils.get_user_temp_dir(), + shm_avail, + object_store_memory * (1.1) / (2**30), + ) + ) + else: + plasma_directory = ray._common.utils.get_user_temp_dir() + + # Do some sanity checks. + if object_store_memory > system_memory: + raise ValueError( + "The requested object store memory size is greater " + "than the total available memory." + ) + else: + plasma_directory = os.path.abspath(plasma_directory) + logger.info("object_store_memory is not verified when plasma_directory is set.") + + if not os.path.isdir(plasma_directory): + raise ValueError( + f"The plasma directory file {plasma_directory} does not exist or is not a directory." + ) + + if huge_pages and plasma_directory is None: + raise ValueError( + "If huge_pages is True, then the " + "plasma_directory argument must be provided." + ) + + if object_store_memory < ray_constants.OBJECT_STORE_MINIMUM_MEMORY_BYTES: + raise ValueError( + "Attempting to cap object store memory usage at {} " + "bytes, but the minimum allowed is {} bytes.".format( + object_store_memory, ray_constants.OBJECT_STORE_MINIMUM_MEMORY_BYTES + ) + ) + + if ( + sys.platform == "darwin" + and object_store_memory > ray_constants.MAC_DEGRADED_PERF_MMAP_SIZE_LIMIT + and os.environ.get("RAY_ENABLE_MAC_LARGE_OBJECT_STORE") != "1" + ): + raise ValueError( + "The configured object store size ({:.4}GiB) exceeds " + "the optimal size on Mac ({:.4}GiB). " + "This will harm performance! There is a known issue where " + "Ray's performance degrades with object store size greater" + " than {:.4}GB on a Mac." + "To reduce the object store capacity, specify" + "`object_store_memory` when calling ray.init() or ray start." + "To ignore this warning, " + "set RAY_ENABLE_MAC_LARGE_OBJECT_STORE=1.".format( + object_store_memory / 2**30, + ray_constants.MAC_DEGRADED_PERF_MMAP_SIZE_LIMIT / 2**30, + ray_constants.MAC_DEGRADED_PERF_MMAP_SIZE_LIMIT / 2**30, + ) + ) + + if fallback_directory is None: + fallback_directory = temp_dir + else: + fallback_directory = os.path.abspath(fallback_directory) + + if not os.path.isdir(fallback_directory): + raise ValueError( + f"The fallback directory file {fallback_directory} does not exist or is not a directory." + ) + + # Print the object store memory using two decimal places. + logger.debug( + "Determine to start the Plasma object store with {} GB memory " + "using {} and fallback to {}".format( + round(object_store_memory / 10**9, 2), + plasma_directory, + fallback_directory, + ) + ) + + return plasma_directory, fallback_directory, object_store_memory + + +def start_monitor( + gcs_address: str, + logs_dir: str, + stdout_filepath: Optional[str] = None, + stderr_filepath: Optional[str] = None, + autoscaling_config: Optional[str] = None, + fate_share: Optional[bool] = None, + max_bytes: int = 0, + backup_count: int = 0, + monitor_ip: Optional[str] = None, + autoscaler_v2: bool = False, +): + """Run a process to monitor the other processes. + + Args: + gcs_address: The address of GCS server. + logs_dir: The path to the log directory. + stdout_filepath: The file path to dump monitor stdout. + If None, stdout is not redirected. + stderr_filepath: The file path to dump monitor stderr. + If None, stderr is not redirected. + autoscaling_config: path to autoscaling config file. + max_bytes: Log rotation parameter. Corresponding to + RotatingFileHandler's maxBytes. + backup_count: Log rotation parameter. Corresponding to + RotatingFileHandler's backupCount. + monitor_ip: IP address of the machine that the monitor will be + run on. Can be excluded, but required for autoscaler metrics. + Returns: + ProcessInfo for the process that was started. + """ + if autoscaler_v2: + entrypoint = os.path.join(RAY_PATH, AUTOSCALER_V2_DIR, "monitor.py") + else: + entrypoint = os.path.join(RAY_PATH, AUTOSCALER_PRIVATE_DIR, "monitor.py") + + command = [ + sys.executable, + "-u", + entrypoint, + f"--logs-dir={logs_dir}", + f"--logging-rotate-bytes={max_bytes}", + f"--logging-rotate-backup-count={backup_count}", + ] + assert gcs_address is not None + command.append(f"--gcs-address={gcs_address}") + + if stdout_filepath: + command.append(f"--stdout-filepath={stdout_filepath}") + if stderr_filepath: + command.append(f"--stderr-filepath={stderr_filepath}") + + if stdout_filepath is None and stderr_filepath is None: + # If not redirecting logging to files, unset log filename. + # This will cause log records to go to stderr. + command.append("--logging-filename=") + # Use stderr log format with the component name as a message prefix. + logging_format = ray_constants.LOGGER_FORMAT_STDERR.format( + component=ray_constants.PROCESS_TYPE_MONITOR + ) + command.append(f"--logging-format={logging_format}") + if autoscaling_config: + command.append("--autoscaling-config=" + str(autoscaling_config)) + if monitor_ip: + command.append("--monitor-ip=" + monitor_ip) + + stdout_file = None + if stdout_filepath: + stdout_file = open(os.devnull, "w") + + stderr_file = None + if stderr_filepath: + stderr_file = open(os.devnull, "w") + + process_info = start_ray_process( + command, + ray_constants.PROCESS_TYPE_MONITOR, + stdout_file=stdout_file, + stderr_file=stderr_file, + fate_share=fate_share, + ) + return process_info + + +def start_ray_client_server( + address: str, + ray_client_server_ip: str, + ray_client_server_port: int, + stdout_file: Optional[int] = None, + stderr_file: Optional[int] = None, + redis_username: Optional[int] = None, + redis_password: Optional[int] = None, + fate_share: Optional[bool] = None, + runtime_env_agent_address: Optional[str] = None, + server_type: str = "proxy", + serialized_runtime_env_context: Optional[str] = None, +): + """Run the server process of the Ray client. + + Args: + address: The address of the cluster. + ray_client_server_ip: Host IP the Ray client server listens on. + ray_client_server_port: Port the Ray client server listens on. + stdout_file: A file handle opened for writing to redirect stdout to. If + no redirection should happen, then this should be None. + stderr_file: A file handle opened for writing to redirect stderr to. If + no redirection should happen, then this should be None. + redis_username: The username of the Redis server. + redis_password: The password of the Redis server. + runtime_env_agent_address: Address to the Runtime Env Agent listens on via HTTP. + Only needed when server_type == "proxy". + server_type: Whether to start the proxy version of Ray Client. + serialized_runtime_env_context (str|None): If specified, the serialized + runtime_env_context to start the client server in. + + Returns: + ProcessInfo for the process that was started. + """ + root_ray_dir = Path(__file__).resolve().parents[1] + setup_worker_path = os.path.join( + root_ray_dir, "_private", "workers", ray_constants.SETUP_WORKER_FILENAME + ) + + ray_client_server_host = ( + "127.0.0.1" if ray_client_server_ip == "127.0.0.1" else "0.0.0.0" + ) + command = [ + sys.executable, + setup_worker_path, + "-m", + "ray.util.client.server", + f"--address={address}", + f"--host={ray_client_server_host}", + f"--port={ray_client_server_port}", + f"--mode={server_type}", + f"--language={Language.Name(Language.PYTHON)}", + ] + if redis_username: + command.append(f"--redis-username={redis_username}") + if redis_password: + command.append(f"--redis-password={redis_password}") + if serialized_runtime_env_context: + command.append( + f"--serialized-runtime-env-context={serialized_runtime_env_context}" # noqa: E501 + ) + if server_type == "proxy": + assert len(runtime_env_agent_address) > 0 + if runtime_env_agent_address: + command.append(f"--runtime-env-agent-address={runtime_env_agent_address}") + + process_info = start_ray_process( + command, + ray_constants.PROCESS_TYPE_RAY_CLIENT_SERVER, + stdout_file=stdout_file, + stderr_file=stderr_file, + fate_share=fate_share, + ) + return process_info + + +def _is_raylet_process(cmdline: Optional[List[str]]) -> bool: + """Check if the command line belongs to a raylet process. + + Args: + cmdline: List of command line arguments or None + + Returns: + bool: True if this is a raylet process, False otherwise + """ + if cmdline is None or len(cmdline) == 0: + return False + + executable = os.path.basename(cmdline[0]) + return "raylet" in executable diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/state.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/state.py new file mode 100644 index 0000000000000000000000000000000000000000..4ded93b92ba4c6a53d6584e62dcd90851d06ee8c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/state.py @@ -0,0 +1,1148 @@ +import json +import logging +import sys +from collections import defaultdict +from typing import Dict, Optional + +import ray +from ray._common.utils import binary_to_hex, decode, hex_to_binary +from ray._private.client_mode_hook import client_mode_hook +from ray._private.protobuf_compat import message_to_dict +from ray._private.resource_spec import HEAD_NODE_RESOURCE_NAME, NODE_ID_PREFIX +from ray._private.utils import ( + validate_actor_state_name, +) +from ray._raylet import GlobalStateAccessor +from ray.core.generated import autoscaler_pb2, common_pb2, gcs_pb2 +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + + +class GlobalState: + """A class used to interface with the Ray control state. + + Attributes: + global_state_accessor: The client used to query gcs table from gcs + server. + """ + + def __init__(self): + """Create a GlobalState object.""" + # Args used for lazy init of this object. + self.gcs_options = None + self.global_state_accessor = None + + def _check_connected(self): + """Ensure that the object has been initialized before it is used. + + This lazily initializes clients needed for state accessors. + + Raises: + RuntimeError: An exception is raised if ray.init() has not been + called yet. + """ + if self.gcs_options is not None and self.global_state_accessor is None: + self._really_init_global_state() + + # _really_init_global_state should have set self.global_state_accessor + if self.global_state_accessor is None: + raise ray.exceptions.RaySystemError( + "Ray has not been started yet. You can start Ray with 'ray.init()'." + ) + + def disconnect(self): + """Disconnect global state from GCS.""" + self.gcs_options = None + if self.global_state_accessor is not None: + self.global_state_accessor.disconnect() + self.global_state_accessor = None + + def _initialize_global_state(self, gcs_options): + """Set args for lazily initialization of the GlobalState object. + + It's possible that certain keys in gcs kv may not have been fully + populated yet. In this case, we will retry this method until they have + been populated or we exceed a timeout. + + Args: + gcs_options: The client options for gcs + """ + + # Save args for lazy init of global state. This avoids opening extra + # gcs connections from each worker until needed. + self.gcs_options = gcs_options + + def _really_init_global_state(self): + self.global_state_accessor = GlobalStateAccessor(self.gcs_options) + self.global_state_accessor.connect() + + def actor_table( + self, + actor_id: Optional[str], + job_id: Optional[ray.JobID] = None, + actor_state_name: Optional[str] = None, + ): + """Fetch and parse the actor table information for a single actor ID. + + Args: + actor_id: A hex string of the actor ID to fetch information about. + If this is None, then the actor table is fetched. + If this is not None, `job_id` and `actor_state_name` + will not take effect. + job_id: To filter actors by job_id, which is of type `ray.JobID`. + You can use the `ray.get_runtime_context().job_id` function + to get the current job ID + actor_state_name: To filter actors based on actor state, + which can be one of the following: "DEPENDENCIES_UNREADY", + "PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD". + Returns: + Information from the actor table. + """ + self._check_connected() + + if actor_id is not None: + actor_id = ray.ActorID(hex_to_binary(actor_id)) + actor_info = self.global_state_accessor.get_actor_info(actor_id) + if actor_info is None: + return {} + else: + actor_table_data = gcs_pb2.ActorTableData.FromString(actor_info) + return self._gen_actor_info(actor_table_data) + else: + validate_actor_state_name(actor_state_name) + actor_table = self.global_state_accessor.get_actor_table( + job_id, actor_state_name + ) + results = {} + for i in range(len(actor_table)): + actor_table_data = gcs_pb2.ActorTableData.FromString(actor_table[i]) + results[ + binary_to_hex(actor_table_data.actor_id) + ] = self._gen_actor_info(actor_table_data) + + return results + + def _gen_actor_info(self, actor_table_data): + """Parse actor table data. + + Returns: + Information from actor table. + """ + actor_info = { + "ActorID": binary_to_hex(actor_table_data.actor_id), + "ActorClassName": actor_table_data.class_name, + "IsDetached": actor_table_data.is_detached, + "Name": actor_table_data.name, + "JobID": binary_to_hex(actor_table_data.job_id), + "Address": { + "IPAddress": actor_table_data.address.ip_address, + "Port": actor_table_data.address.port, + "NodeID": binary_to_hex(actor_table_data.address.raylet_id), + }, + "OwnerAddress": { + "IPAddress": actor_table_data.owner_address.ip_address, + "Port": actor_table_data.owner_address.port, + "NodeID": binary_to_hex(actor_table_data.owner_address.raylet_id), + }, + "State": gcs_pb2.ActorTableData.ActorState.DESCRIPTOR.values_by_number[ + actor_table_data.state + ].name, + "NumRestarts": actor_table_data.num_restarts, + "Timestamp": actor_table_data.timestamp, + "StartTime": actor_table_data.start_time, + "EndTime": actor_table_data.end_time, + "DeathCause": actor_table_data.death_cause, + "Pid": actor_table_data.pid, + } + return actor_info + + def node_table(self): + """Fetch and parse the Gcs node info table. + + Returns: + Information about the node in the cluster. + """ + self._check_connected() + + return self.global_state_accessor.get_node_table() + + def job_table(self): + """Fetch and parse the gcs job table. + + Returns: + Information about the Ray jobs in the cluster, + namely a list of dicts with keys: + - "JobID" (identifier for the job), + - "DriverIPAddress" (IP address of the driver for this job), + - "DriverPid" (process ID of the driver for this job), + - "StartTime" (UNIX timestamp of the start time of this job), + - "StopTime" (UNIX timestamp of the stop time of this job, if any) + """ + self._check_connected() + + job_table = self.global_state_accessor.get_job_table( + skip_submission_job_info_field=True, skip_is_running_tasks_field=True + ) + + results = [] + for i in range(len(job_table)): + entry = gcs_pb2.JobTableData.FromString(job_table[i]) + job_info = {} + job_info["JobID"] = entry.job_id.hex() + job_info["DriverIPAddress"] = entry.driver_address.ip_address + job_info["DriverPid"] = entry.driver_pid + job_info["Timestamp"] = entry.timestamp + job_info["StartTime"] = entry.start_time + job_info["EndTime"] = entry.end_time + job_info["IsDead"] = entry.is_dead + job_info["Entrypoint"] = entry.entrypoint + results.append(job_info) + + return results + + def next_job_id(self): + """Get next job id from GCS. + + Returns: + Next job id in the cluster. + """ + self._check_connected() + + return ray.JobID.from_int(self.global_state_accessor.get_next_job_id()) + + def profile_events(self): + """Retrieve and return task profiling events from GCS. + + Return: + Profiling events by component id (e.g. worker id). + { + : [ + { + event_type: , + component_id: , + node_ip_address: , + component_type: , + start_time: , + end_time: , + extra_data: , + } + ] + } + """ + self._check_connected() + + result = defaultdict(list) + task_events = self.global_state_accessor.get_task_events() + for i in range(len(task_events)): + event = gcs_pb2.TaskEvents.FromString(task_events[i]) + profile = event.profile_events + if not profile: + continue + + component_type = profile.component_type + component_id = binary_to_hex(profile.component_id) + node_ip_address = profile.node_ip_address + + for event in profile.events: + try: + extra_data = json.loads(event.extra_data) + except ValueError: + extra_data = {} + profile_event = { + "event_type": event.event_name, + "component_id": component_id, + "node_ip_address": node_ip_address, + "component_type": component_type, + "start_time": event.start_time, + "end_time": event.end_time, + "extra_data": extra_data, + } + + result[component_id].append(profile_event) + + return dict(result) + + def get_placement_group_by_name(self, placement_group_name, ray_namespace): + self._check_connected() + + placement_group_info = self.global_state_accessor.get_placement_group_by_name( + placement_group_name, ray_namespace + ) + if placement_group_info is None: + return None + else: + placement_group_table_data = gcs_pb2.PlacementGroupTableData.FromString( + placement_group_info + ) + return self._gen_placement_group_info(placement_group_table_data) + + def placement_group_table(self, placement_group_id=None): + self._check_connected() + + if placement_group_id is not None: + placement_group_id = ray.PlacementGroupID( + hex_to_binary(placement_group_id.hex()) + ) + placement_group_info = self.global_state_accessor.get_placement_group_info( + placement_group_id + ) + if placement_group_info is None: + return {} + else: + placement_group_info = gcs_pb2.PlacementGroupTableData.FromString( + placement_group_info + ) + return self._gen_placement_group_info(placement_group_info) + else: + placement_group_table = ( + self.global_state_accessor.get_placement_group_table() + ) + results = {} + for placement_group_info in placement_group_table: + placement_group_table_data = gcs_pb2.PlacementGroupTableData.FromString( + placement_group_info + ) + placement_group_id = binary_to_hex( + placement_group_table_data.placement_group_id + ) + results[placement_group_id] = self._gen_placement_group_info( + placement_group_table_data + ) + + return results + + def _gen_placement_group_info(self, placement_group_info): + # This should be imported here, otherwise, it will error doc build. + from ray.core.generated.common_pb2 import PlacementStrategy + + def get_state(state): + if state == gcs_pb2.PlacementGroupTableData.PENDING: + return "PENDING" + elif state == gcs_pb2.PlacementGroupTableData.PREPARED: + return "PREPARED" + elif state == gcs_pb2.PlacementGroupTableData.CREATED: + return "CREATED" + elif state == gcs_pb2.PlacementGroupTableData.RESCHEDULING: + return "RESCHEDULING" + else: + return "REMOVED" + + def get_strategy(strategy): + if strategy == PlacementStrategy.PACK: + return "PACK" + elif strategy == PlacementStrategy.STRICT_PACK: + return "STRICT_PACK" + elif strategy == PlacementStrategy.STRICT_SPREAD: + return "STRICT_SPREAD" + elif strategy == PlacementStrategy.SPREAD: + return "SPREAD" + else: + raise ValueError(f"Invalid strategy returned: {PlacementStrategy}") + + stats = placement_group_info.stats + assert placement_group_info is not None + return { + "placement_group_id": binary_to_hex( + placement_group_info.placement_group_id + ), + "name": placement_group_info.name, + "bundles": { + # The value here is needs to be dictionarified + # otherwise, the payload becomes unserializable. + bundle.bundle_id.bundle_index: message_to_dict(bundle)["unitResources"] + for bundle in placement_group_info.bundles + }, + "bundles_to_node_id": { + bundle.bundle_id.bundle_index: binary_to_hex(bundle.node_id) + for bundle in placement_group_info.bundles + }, + "strategy": get_strategy(placement_group_info.strategy), + "state": get_state(placement_group_info.state), + "stats": { + "end_to_end_creation_latency_ms": ( + stats.end_to_end_creation_latency_us / 1000.0 + ), + "scheduling_latency_ms": (stats.scheduling_latency_us / 1000.0), + "scheduling_attempt": stats.scheduling_attempt, + "highest_retry_delay_ms": stats.highest_retry_delay_ms, + "scheduling_state": gcs_pb2.PlacementGroupStats.SchedulingState.DESCRIPTOR.values_by_number[ # noqa: E501 + stats.scheduling_state + ].name, + }, + } + + def _nanoseconds_to_microseconds(self, time_in_nanoseconds): + """A helper function for converting nanoseconds to microseconds.""" + time_in_microseconds = time_in_nanoseconds / 1000 + return time_in_microseconds + + # Colors are specified at + # https://github.com/catapult-project/catapult/blob/master/tracing/tracing/base/color_scheme.html. # noqa: E501 + _default_color_mapping = defaultdict( + lambda: "generic_work", + { + "worker_idle": "cq_build_abandoned", + "task": "rail_response", + "task:deserialize_arguments": "rail_load", + "task:execute": "rail_animation", + "task:store_outputs": "rail_idle", + "wait_for_function": "detailed_memory_dump", + "ray.get": "good", + "ray.put": "terrible", + "ray.wait": "vsync_highlight_color", + "submit_task": "background_memory_dump", + "fetch_and_run_function": "detailed_memory_dump", + "register_remote_function": "detailed_memory_dump", + }, + ) + + # These colors are for use in Chrome tracing. + _chrome_tracing_colors = [ + "thread_state_uninterruptible", + "thread_state_iowait", + "thread_state_running", + "thread_state_runnable", + "thread_state_sleeping", + "thread_state_unknown", + "background_memory_dump", + "light_memory_dump", + "detailed_memory_dump", + "vsync_highlight_color", + "generic_work", + "good", + "bad", + "terrible", + # "black", + # "grey", + # "white", + "yellow", + "olive", + "rail_response", + "rail_animation", + "rail_idle", + "rail_load", + "startup", + "heap_dump_stack_frame", + "heap_dump_object_type", + "heap_dump_child_node_arrow", + "cq_build_running", + "cq_build_passed", + "cq_build_failed", + "cq_build_abandoned", + "cq_build_attempt_runnig", + "cq_build_attempt_passed", + "cq_build_attempt_failed", + ] + + def chrome_tracing_dump(self, filename=None): + """Return a list of profiling events that can viewed as a timeline. + + To view this information as a timeline, simply dump it as a json file + by passing in "filename" or using using json.dump, and then load go to + chrome://tracing in the Chrome web browser and load the dumped file. + Make sure to enable "Flow events" in the "View Options" menu. + + Args: + filename: If a filename is provided, the timeline is dumped to that + file. + + Returns: + If filename is not provided, this returns a list of profiling + events. Each profile event is a dictionary. + """ + # TODO(rkn): Support including the task specification data in the + # timeline. + # TODO(rkn): This should support viewing just a window of time or a + # limited number of events. + + self._check_connected() + + # Add a small delay to account for propagation delay of events to the GCS. + # This should be harmless enough but prevents calls to timeline() from + # missing recent timeline data. + import time + + time.sleep(1) + + profile_events = self.profile_events() + all_events = [] + + for component_id_hex, component_events in profile_events.items(): + # Only consider workers and drivers. + component_type = component_events[0]["component_type"] + if component_type not in ["worker", "driver"]: + continue + + for event in component_events: + new_event = { + # The category of the event. + "cat": event["event_type"], + # The string displayed on the event. + "name": event["event_type"], + # The identifier for the group of rows that the event + # appears in. + "pid": event["node_ip_address"], + # The identifier for the row that the event appears in. + "tid": event["component_type"] + ":" + event["component_id"], + # The start time in microseconds. + "ts": self._nanoseconds_to_microseconds(event["start_time"]), + # The duration in microseconds. + "dur": self._nanoseconds_to_microseconds( + event["end_time"] - event["start_time"] + ), + # What is this? + "ph": "X", + # This is the name of the color to display the box in. + "cname": self._default_color_mapping[event["event_type"]], + # The extra user-defined data. + "args": event["extra_data"], + } + + # Modify the json with the additional user-defined extra data. + # This can be used to add fields or override existing fields. + if "cname" in event["extra_data"]: + new_event["cname"] = event["extra_data"]["cname"] + if "name" in event["extra_data"]: + new_event["name"] = event["extra_data"]["name"] + + all_events.append(new_event) + + if not all_events: + logger.warning( + "No profiling events found. Ray profiling must be enabled " + "by setting RAY_PROFILING=1, and make sure " + "RAY_task_events_report_interval_ms=0." + ) + + if filename is not None: + with open(filename, "w") as outfile: + json.dump(all_events, outfile) + else: + return all_events + + def chrome_tracing_object_transfer_dump(self, filename=None): + """Return a list of transfer events that can viewed as a timeline. + + To view this information as a timeline, simply dump it as a json file + by passing in "filename" or using json.dump, and then load go to + chrome://tracing in the Chrome web browser and load the dumped file. + Make sure to enable "Flow events" in the "View Options" menu. + + Args: + filename: If a filename is provided, the timeline is dumped to that + file. + + Returns: + If filename is not provided, this returns a list of profiling + events. Each profile event is a dictionary. + """ + self._check_connected() + + node_id_to_address = {} + for node_info in self.node_table(): + node_id_to_address[node_info["NodeID"]] = "{}:{}".format( + node_info["NodeManagerAddress"], node_info["ObjectManagerPort"] + ) + + all_events = [] + + for key, items in self.profile_events().items(): + # Only consider object manager events. + if items[0]["component_type"] != "object_manager": + continue + + for event in items: + if event["event_type"] == "transfer_send": + object_ref, remote_node_id, _, _ = event["extra_data"] + + elif event["event_type"] == "transfer_receive": + object_ref, remote_node_id, _ = event["extra_data"] + + elif event["event_type"] == "receive_pull_request": + object_ref, remote_node_id = event["extra_data"] + + else: + assert False, "This should be unreachable." + + # Choose a color by reading the first couple of hex digits of + # the object ref as an integer and turning that into a color. + object_ref_int = int(object_ref[:2], 16) + color = self._chrome_tracing_colors[ + object_ref_int % len(self._chrome_tracing_colors) + ] + + new_event = { + # The category of the event. + "cat": event["event_type"], + # The string displayed on the event. + "name": event["event_type"], + # The identifier for the group of rows that the event + # appears in. + "pid": node_id_to_address[key], + # The identifier for the row that the event appears in. + "tid": node_id_to_address[remote_node_id], + # The start time in microseconds. + "ts": self._nanoseconds_to_microseconds(event["start_time"]), + # The duration in microseconds. + "dur": self._nanoseconds_to_microseconds( + event["end_time"] - event["start_time"] + ), + # What is this? + "ph": "X", + # This is the name of the color to display the box in. + "cname": color, + # The extra user-defined data. + "args": event["extra_data"], + } + all_events.append(new_event) + + # Add another box with a color indicating whether it was a send + # or a receive event. + if event["event_type"] == "transfer_send": + additional_event = new_event.copy() + additional_event["cname"] = "black" + all_events.append(additional_event) + elif event["event_type"] == "transfer_receive": + additional_event = new_event.copy() + additional_event["cname"] = "grey" + all_events.append(additional_event) + else: + pass + + if filename is not None: + with open(filename, "w") as outfile: + json.dump(all_events, outfile) + else: + return all_events + + def workers(self): + """Get a dictionary mapping worker ID to worker information.""" + self._check_connected() + + # Get all data in worker table + worker_table = self.global_state_accessor.get_worker_table() + workers_data = {} + for i in range(len(worker_table)): + worker_table_data = gcs_pb2.WorkerTableData.FromString(worker_table[i]) + if ( + worker_table_data.is_alive + and worker_table_data.worker_type == common_pb2.WORKER + ): + worker_id = binary_to_hex(worker_table_data.worker_address.worker_id) + worker_info = worker_table_data.worker_info + + workers_data[worker_id] = { + "node_ip_address": decode(worker_info[b"node_ip_address"]), + "plasma_store_socket": decode(worker_info[b"plasma_store_socket"]), + } + if b"stderr_file" in worker_info: + workers_data[worker_id]["stderr_file"] = decode( + worker_info[b"stderr_file"] + ) + if b"stdout_file" in worker_info: + workers_data[worker_id]["stdout_file"] = decode( + worker_info[b"stdout_file"] + ) + return workers_data + + def add_worker(self, worker_id, worker_type, worker_info): + """Add a worker to the cluster. + + Args: + worker_id: ID of this worker. Type is bytes. + worker_type: Type of this worker. Value is common_pb2.DRIVER or + common_pb2.WORKER. + worker_info: Info of this worker. Type is dict{str: str}. + + Returns: + Is operation success + """ + worker_data = gcs_pb2.WorkerTableData() + worker_data.is_alive = True + worker_data.worker_address.worker_id = worker_id + worker_data.worker_type = worker_type + for k, v in worker_info.items(): + worker_data.worker_info[k] = bytes(v, encoding="utf-8") + return self.global_state_accessor.add_worker_info( + worker_data.SerializeToString() + ) + + def update_worker_debugger_port(self, worker_id, debugger_port): + """Update the debugger port of a worker. + + Args: + worker_id: ID of this worker. Type is bytes. + debugger_port: Port of the debugger. Type is int. + + Returns: + Is operation success + """ + self._check_connected() + + assert worker_id is not None, "worker_id is not valid" + assert ( + debugger_port is not None and debugger_port > 0 + ), "debugger_port is not valid" + + return self.global_state_accessor.update_worker_debugger_port( + worker_id, debugger_port + ) + + def get_worker_debugger_port(self, worker_id): + """Get the debugger port of a worker. + + Args: + worker_id: ID of this worker. Type is bytes. + + Returns: + Debugger port of the worker. + """ + self._check_connected() + + assert worker_id is not None, "worker_id is not valid" + + return self.global_state_accessor.get_worker_debugger_port(worker_id) + + def update_worker_num_paused_threads(self, worker_id, num_paused_threads_delta): + """Updates the number of paused threads of a worker. + + Args: + worker_id: ID of this worker. Type is bytes. + num_paused_threads_delta: The delta of the number of paused threads. + + Returns: + Is operation success + """ + self._check_connected() + + assert worker_id is not None, "worker_id is not valid" + assert num_paused_threads_delta is not None, "worker_id is not valid" + + return self.global_state_accessor.update_worker_num_paused_threads( + worker_id, num_paused_threads_delta + ) + + def cluster_resources(self): + """Get the current total cluster resources. + + Note that this information can grow stale as nodes are added to or + removed from the cluster. + + Returns: + A dictionary mapping resource name to the total quantity of that + resource in the cluster. + """ + self._check_connected() + + # Calculate total resources. + total_resources = defaultdict(int) + for node_total_resources in self.total_resources_per_node().values(): + for resource_id, value in node_total_resources.items(): + total_resources[resource_id] += value + + return dict(total_resources) + + def _live_node_ids(self): + """Returns a set of node IDs corresponding to nodes still alive.""" + return set(self.total_resources_per_node().keys()) + + def available_resources_per_node(self): + """Returns a dictionary mapping node id to available resources.""" + self._check_connected() + available_resources_by_id = {} + + all_available_resources = ( + self.global_state_accessor.get_all_available_resources() + ) + for available_resource in all_available_resources: + message = gcs_pb2.AvailableResources.FromString(available_resource) + # Calculate available resources for this node. + dynamic_resources = {} + for resource_id, capacity in message.resources_available.items(): + dynamic_resources[resource_id] = capacity + # Update available resources for this node. + node_id = ray._common.utils.binary_to_hex(message.node_id) + available_resources_by_id[node_id] = dynamic_resources + + return available_resources_by_id + + # returns a dict that maps node_id(hex string) to a dict of {resource_id: capacity} + def total_resources_per_node(self) -> Dict[str, Dict[str, int]]: + self._check_connected() + total_resources_by_node = {} + + all_total_resources = self.global_state_accessor.get_all_total_resources() + for node_total_resources in all_total_resources: + message = gcs_pb2.TotalResources.FromString(node_total_resources) + # Calculate total resources for this node. + node_resources = {} + for resource_id, capacity in message.resources_total.items(): + node_resources[resource_id] = capacity + # Update total resources for this node. + node_id = ray._common.utils.binary_to_hex(message.node_id) + total_resources_by_node[node_id] = node_resources + + return total_resources_by_node + + def available_resources(self): + """Get the current available cluster resources. + + This is different from `cluster_resources` in that this will return + idle (available) resources rather than total resources. + + Note that this information can grow stale as tasks start and finish. + + Returns: + A dictionary mapping resource name to the total quantity of that + resource in the cluster. Note that if a resource (e.g., "CPU") + is currently not available (i.e., quantity is 0), it will not + be included in this dictionary. + """ + self._check_connected() + + available_resources_by_id = self.available_resources_per_node() + + # Calculate total available resources. + total_available_resources = defaultdict(int) + for available_resources in available_resources_by_id.values(): + for resource_id, num_available in available_resources.items(): + total_available_resources[resource_id] += num_available + + return dict(total_available_resources) + + def get_system_config(self): + """Get the system config of the cluster.""" + self._check_connected() + return json.loads(self.global_state_accessor.get_system_config()) + + def get_node_to_connect_for_driver(self, node_ip_address): + """Get the node to connect for a Ray driver.""" + self._check_connected() + return self.global_state_accessor.get_node_to_connect_for_driver( + node_ip_address + ) + + def get_node(self, node_id: str): + """Get the node information for a node id.""" + self._check_connected() + return self.global_state_accessor.get_node(node_id) + + def get_draining_nodes(self) -> Dict[str, int]: + """Get all the hex ids of nodes that are being drained + and the corresponding draining deadline timestamps in ms. + + There is no deadline if the timestamp is 0. + """ + self._check_connected() + return self.global_state_accessor.get_draining_nodes() + + def get_cluster_config(self) -> autoscaler_pb2.ClusterConfig: + """Get the cluster config of the current cluster.""" + self._check_connected() + serialized_cluster_config = self.global_state_accessor.get_internal_kv( + ray._raylet.GCS_AUTOSCALER_STATE_NAMESPACE.encode(), + ray._raylet.GCS_AUTOSCALER_CLUSTER_CONFIG_KEY.encode(), + ) + if serialized_cluster_config: + return autoscaler_pb2.ClusterConfig.FromString(serialized_cluster_config) + return None + + @staticmethod + def _calculate_max_resource_from_cluster_config( + cluster_config: Optional[autoscaler_pb2.ClusterConfig], key: str + ) -> Optional[int]: + """Calculate the maximum available resources for a given resource type from cluster config. + If the resource type is not available, return None. + """ + if cluster_config is None: + return None + + max_value = 0 + for node_group_config in cluster_config.node_group_configs: + num_resources = node_group_config.resources.get(key, default=0) + num_nodes = node_group_config.max_count + if num_nodes == 0 or num_resources == 0: + continue + if num_nodes == -1 or num_resources == -1: + return sys.maxsize + max_value += num_nodes * num_resources + if max_value == 0: + return None + max_value_limit = cluster_config.max_resources.get(key, default=sys.maxsize) + return min(max_value, max_value_limit) + + def get_max_resources_from_cluster_config(self) -> Optional[Dict[str, int]]: + """Get the maximum available resources for all resource types from cluster config. + + Returns: + A dictionary mapping resource name to the maximum quantity of that + resource that could be available in the cluster based on the cluster config. + Returns None if the config is not available. + Values in the dictionary default to 0 if there is no such resource. + """ + all_resource_keys = set() + + config = self.get_cluster_config() + if config is None: + return None + + if config.node_group_configs: + for node_group_config in config.node_group_configs: + all_resource_keys.update(node_group_config.resources.keys()) + if len(all_resource_keys) == 0: + return None + + result = {} + for key in all_resource_keys: + max_value = self._calculate_max_resource_from_cluster_config(config, key) + result[key] = max_value if max_value is not None else 0 + + return result + + +state = GlobalState() +"""A global object used to access the cluster's global state.""" + + +def jobs(): + """Get a list of the jobs in the cluster (for debugging only). + + Returns: + Information from the job table, namely a list of dicts with keys: + - "JobID" (identifier for the job), + - "DriverIPAddress" (IP address of the driver for this job), + - "DriverPid" (process ID of the driver for this job), + - "StartTime" (UNIX timestamp of the start time of this job), + - "StopTime" (UNIX timestamp of the stop time of this job, if any) + """ + return state.job_table() + + +def next_job_id(): + """Get next job id from GCS. + + Returns: + Next job id in integer representation in the cluster. + """ + return state.next_job_id() + + +@DeveloperAPI +@client_mode_hook +def nodes(): + """Get a list of the nodes in the cluster (for debugging only). + + Returns: + Information about the Ray clients in the cluster. + """ + return state.node_table() + + +def workers(): + """Get a list of the workers in the cluster. + + Returns: + Information about the Ray workers in the cluster. + """ + return state.workers() + + +def current_node_id(): + """Return the node id of the current node. + + For example, "node:172.10.5.34". This can be used as a custom resource, + e.g., {node_id: 1} to reserve the whole node, or {node_id: 0.001} to + just force placement on the node. + + Returns: + Id of the current node. + """ + return NODE_ID_PREFIX + ray.util.get_node_ip_address() + + +def node_ids(): + """Get a list of the node ids in the cluster. + + For example, ["node:172.10.5.34", "node:172.42.3.77"]. These can be used + as custom resources, e.g., {node_id: 1} to reserve the whole node, or + {node_id: 0.001} to just force placement on the node. + + Returns: + List of the node resource ids. + """ + node_ids = [] + for node_total_resources in state.total_resources_per_node().values(): + for resource_id in node_total_resources.keys(): + if ( + resource_id.startswith(NODE_ID_PREFIX) + and resource_id != HEAD_NODE_RESOURCE_NAME + ): + node_ids.append(resource_id) + return node_ids + + +def actors( + actor_id: Optional[str] = None, + job_id: Optional[ray.JobID] = None, + actor_state_name: Optional[str] = None, +): + """Fetch actor info for one or more actor IDs (for debugging only). + + Args: + actor_id: A hex string of the actor ID to fetch information about. If + this is None, then all actor information is fetched. + If this is not None, `job_id` and `actor_state_name` + will not take effect. + job_id: To filter actors by job_id, which is of type `ray.JobID`. + You can use the `ray.get_runtime_context().job_id` function + to get the current job ID + actor_state_name: To filter actors based on actor state, + which can be one of the following: "DEPENDENCIES_UNREADY", + "PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD". + Returns: + Information about the actors. + """ + return state.actor_table( + actor_id=actor_id, job_id=job_id, actor_state_name=actor_state_name + ) + + +@DeveloperAPI +@client_mode_hook +def timeline(filename=None): + """Return a list of profiling events that can viewed as a timeline. + + Ray profiling must be enabled by setting the RAY_PROFILING=1 environment + variable prior to starting Ray, and set RAY_task_events_report_interval_ms=0 + + To view this information as a timeline, simply dump it as a json file by + passing in "filename" or using json.dump, and then load go to + chrome://tracing in the Chrome web browser and load the dumped file. + + Args: + filename: If a filename is provided, the timeline is dumped to that + file. + + Returns: + If filename is not provided, this returns a list of profiling events. + Each profile event is a dictionary. + """ + return state.chrome_tracing_dump(filename=filename) + + +def object_transfer_timeline(filename=None): + """Return a list of transfer events that can viewed as a timeline. + + To view this information as a timeline, simply dump it as a json file by + passing in "filename" or using json.dump, and then load go to + chrome://tracing in the Chrome web browser and load the dumped file. Make + sure to enable "Flow events" in the "View Options" menu. + + Args: + filename: If a filename is provided, the timeline is dumped to that + file. + + Returns: + If filename is not provided, this returns a list of profiling events. + Each profile event is a dictionary. + """ + return state.chrome_tracing_object_transfer_dump(filename=filename) + + +@DeveloperAPI +@client_mode_hook +def cluster_resources(): + """Get the current total cluster resources. + + Note that this information can grow stale as nodes are added to or removed + from the cluster. + + Returns: + A dictionary mapping resource name to the total quantity of that + resource in the cluster. + """ + return state.cluster_resources() + + +@DeveloperAPI +@client_mode_hook +def available_resources(): + """Get the current available cluster resources. + + This is different from `cluster_resources` in that this will return idle + (available) resources rather than total resources. + + Note that this information can grow stale as tasks start and finish. + + Returns: + A dictionary mapping resource name to the total quantity of that + resource in the cluster. Note that if a resource (e.g., "CPU") + is currently not available (i.e., quantity is 0), it will not + be included in this dictionary. + """ + return state.available_resources() + + +@DeveloperAPI +def available_resources_per_node(): + """Get the current available resources of each live node. + + Note that this information can grow stale as tasks start and finish. + + Returns: + A dictionary mapping node hex id to available resources dictionary. + """ + + return state.available_resources_per_node() + + +@DeveloperAPI +def total_resources_per_node(): + """Get the current total resources of each live node. + + Note that this information can grow stale as tasks start and finish. + + Returns: + A dictionary mapping node hex id to total resources dictionary. + """ + + return state.total_resources_per_node() + + +def update_worker_debugger_port(worker_id, debugger_port): + """Update the debugger port of a worker. + + Args: + worker_id: ID of this worker. Type is bytes. + debugger_port: Port of the debugger. Type is int. + + Returns: + Is operation success + """ + return state.update_worker_debugger_port(worker_id, debugger_port) + + +def update_worker_num_paused_threads(worker_id, num_paused_threads_delta): + """Update the number of paused threads of a worker. + + Args: + worker_id: ID of this worker. Type is bytes. + num_paused_threads_delta: The delta of the number of paused threads. + + Returns: + Is operation success + """ + return state.update_worker_num_paused_threads(worker_id, num_paused_threads_delta) + + +def get_worker_debugger_port(worker_id): + """Get the debugger port of a worker. + + Args: + worker_id: ID of this worker. Type is bytes. + + Returns: + Debugger port of the worker. + """ + return state.get_worker_debugger_port(worker_id) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/state_api_test_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/state_api_test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a013842fa4586d4896651b4a711316dc5584a030 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/state_api_test_utils.py @@ -0,0 +1,582 @@ +import asyncio +import concurrent.futures +import logging +import pprint +import sys +import time +import traceback +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor +from copy import deepcopy +from dataclasses import dataclass, field +from typing import Callable, Dict, List, Optional, Tuple, Union + +import numpy as np + +import ray +import ray._common.test_utils as test_utils +from ray._private.gcs_utils import GcsChannel +from ray._raylet import GcsClient +from ray.actor import ActorHandle +from ray.dashboard.state_aggregator import ( + StateAPIManager, +) +from ray.util.state import list_tasks, list_workers +from ray.util.state.common import ( + DEFAULT_LIMIT, + DEFAULT_RPC_TIMEOUT, + ListApiOptions, + PredicateType, + SupportedFilterType, +) +from ray.util.state.state_manager import StateDataSourceClient + +import psutil + + +@dataclass +class StateAPIMetric: + latency_sec: float + result_size: int + + +@dataclass +class StateAPICallSpec: + api: Callable + verify_cb: Callable + kwargs: Dict = field(default_factory=dict) + + +@dataclass +class StateAPIStats: + pending_calls: int = 0 + total_calls: int = 0 + calls: Dict = field(default_factory=lambda: defaultdict(list)) + + +GLOBAL_STATE_STATS = StateAPIStats() + +STATE_LIST_LIMIT = int(1e6) # 1m +STATE_LIST_TIMEOUT = 600 # 10min + + +def invoke_state_api( + verify_cb: Callable, + state_api_fn: Callable, + state_stats: StateAPIStats = GLOBAL_STATE_STATS, + key_suffix: Optional[str] = None, + print_result: Optional[bool] = False, + err_msg: Optional[str] = None, + **kwargs, +): + """Invoke a State API + + Args: + - verify_cb: Callback that takes in the response from `state_api_fn` and + returns a boolean, indicating the correctness of the results. + - state_api_fn: Function of the state API + - state_stats: Stats + - kwargs: Keyword arguments to be forwarded to the `state_api_fn` + """ + if "timeout" not in kwargs: + kwargs["timeout"] = STATE_LIST_TIMEOUT + + # Suppress missing output warning + kwargs["raise_on_missing_output"] = False + + res = None + try: + state_stats.total_calls += 1 + state_stats.pending_calls += 1 + + t_start = time.perf_counter() + res = state_api_fn(**kwargs) + t_end = time.perf_counter() + + if print_result: + pprint.pprint(res) + + metric = StateAPIMetric(t_end - t_start, len(res)) + if key_suffix: + key = f"{state_api_fn.__name__}_{key_suffix}" + else: + key = state_api_fn.__name__ + state_stats.calls[key].append(metric) + assert verify_cb( + res + ), f"Calling State API failed. len(res)=({len(res)}): {err_msg}" + except Exception as e: + traceback.print_exc() + assert ( + False + ), f"Calling {state_api_fn.__name__}({kwargs}) failed with {repr(e)}." + finally: + state_stats.pending_calls -= 1 + + return res + + +def invoke_state_api_n(*args, **kwargs): + def verify(): + NUM_API_CALL_SAMPLES = 10 + for _ in range(NUM_API_CALL_SAMPLES): + invoke_state_api(*args, **kwargs) + return True + + test_utils.wait_for_condition(verify, retry_interval_ms=2000, timeout=30) + + +def aggregate_perf_results(state_stats: StateAPIStats = GLOBAL_STATE_STATS): + """Aggregate stats of state API calls + + Return: + This returns a dict of below fields: + - max_{api_key_name}_latency_sec: + Max latency of call to {api_key_name} + - {api_key_name}_result_size_with_max_latency: + The size of the result (or the number of bytes for get_log API) + for the max latency invocation + - avg/p99/p95/p50_{api_key_name}_latency_sec: + The percentile latency stats + - avg_state_api_latency_sec: + The average latency of all the state apis tracked + """ + # Prevent iteration when modifying error + state_stats = deepcopy(state_stats) + perf_result = {} + for api_key_name, metrics in state_stats.calls.items(): + # Per api aggregation + # Max latency + latency_key = f"max_{api_key_name}_latency_sec" + size_key = f"{api_key_name}_result_size_with_max_latency" + metric = max(metrics, key=lambda metric: metric.latency_sec) + + perf_result[latency_key] = metric.latency_sec + perf_result[size_key] = metric.result_size + + latency_list = np.array([metric.latency_sec for metric in metrics]) + # avg latency + key = f"avg_{api_key_name}_latency_sec" + perf_result[key] = np.average(latency_list) + + # p99 latency + key = f"p99_{api_key_name}_latency_sec" + perf_result[key] = np.percentile(latency_list, 99) + + # p95 latency + key = f"p95_{api_key_name}_latency_sec" + perf_result[key] = np.percentile(latency_list, 95) + + # p50 latency + key = f"p50_{api_key_name}_latency_sec" + perf_result[key] = np.percentile(latency_list, 50) + + all_state_api_latency = sum( + metric.latency_sec + for metric_samples in state_stats.calls.values() + for metric in metric_samples + ) + + perf_result["avg_state_api_latency_sec"] = ( + (all_state_api_latency / state_stats.total_calls) + if state_stats.total_calls != 0 + else -1 + ) + + return perf_result + + +@ray.remote(num_cpus=0) +class StateAPIGeneratorActor: + def __init__( + self, + apis: List[StateAPICallSpec], + call_interval_s: float = 5.0, + print_interval_s: float = 20.0, + wait_after_stop: bool = True, + print_result: bool = False, + ) -> None: + """An actor that periodically issues state API + + Args: + - apis: List of StateAPICallSpec + - call_interval_s: State apis in the `apis` will be issued + every `call_interval_s` seconds. + - print_interval_s: How frequent state api stats will be dumped. + - wait_after_stop: When true, call to `ray.get(actor.stop.remote())` + will wait for all pending state APIs to return. + Setting it to `False` might miss some long-running state apis calls. + - print_result: True if result of each API call is printed. Default False. + """ + # Configs + self._apis = apis + self._call_interval_s = call_interval_s + self._print_interval_s = print_interval_s + self._wait_after_cancel = wait_after_stop + self._logger = logging.getLogger(self.__class__.__name__) + self._print_result = print_result + + # States + self._tasks = None + self._fut_queue = None + self._executor = None + self._loop = None + self._stopping = False + self._stopped = False + self._stats = StateAPIStats() + + async def start(self): + # Run the periodic api generator + self._fut_queue = asyncio.Queue() + self._executor = concurrent.futures.ThreadPoolExecutor() + + self._tasks = [ + asyncio.ensure_future(awt) + for awt in [ + self._run_generator(), + self._run_result_waiter(), + self._run_stats_reporter(), + ] + ] + await asyncio.gather(*self._tasks) + + def call(self, fn, verify_cb, **kwargs): + def run_fn(): + try: + self._logger.debug(f"calling {fn.__name__}({kwargs})") + return invoke_state_api( + verify_cb, + fn, + state_stats=self._stats, + print_result=self._print_result, + **kwargs, + ) + except Exception as e: + self._logger.warning(f"{fn.__name__}({kwargs}) failed with: {repr(e)}") + return None + + fut = asyncio.get_running_loop().run_in_executor(self._executor, run_fn) + return fut + + async def _run_stats_reporter(self): + while not self._stopped: + # Keep the reporter running until all pending apis finish and the bool + # `self._stopped` is then True + self._logger.info(pprint.pprint(aggregate_perf_results(self._stats))) + try: + await asyncio.sleep(self._print_interval_s) + except asyncio.CancelledError: + self._logger.info( + "_run_stats_reporter cancelled, " + f"waiting for all api {self._stats.pending_calls}calls to return..." + ) + + async def _run_generator(self): + try: + while not self._stopping: + # Run the state API in another thread + for api_spec in self._apis: + fut = self.call(api_spec.api, api_spec.verify_cb, **api_spec.kwargs) + self._fut_queue.put_nowait(fut) + + await asyncio.sleep(self._call_interval_s) + except asyncio.CancelledError: + # Stop running + self._logger.info("_run_generator cancelled, now stopping...") + return + + async def _run_result_waiter(self): + try: + while not self._stopping: + fut = await self._fut_queue.get() + await fut + except asyncio.CancelledError: + self._logger.info( + f"_run_result_waiter cancelled, cancelling {self._fut_queue.qsize()} " + "pending futures..." + ) + while not self._fut_queue.empty(): + fut = self._fut_queue.get_nowait() + if self._wait_after_cancel: + await fut + else: + # Ignore the queue futures if we are not + # waiting on them after stop() called + fut.cancel() + return + + def get_stats(self): + # deep copy to prevent race between reporting and modifying stats + return aggregate_perf_results(self._stats) + + def ready(self): + pass + + def stop(self): + self._stopping = True + self._logger.debug(f"calling stop, canceling {len(self._tasks)} tasks") + for task in self._tasks: + task.cancel() + + # This will block the stop() function until all futures are cancelled + # if _wait_after_cancel=True. When _wait_after_cancel=False, it will still + # wait for any in-progress futures. + # See: https://docs.python.org/3.8/library/concurrent.futures.html + self._executor.shutdown(wait=self._wait_after_cancel) + self._stopped = True + + +def periodic_invoke_state_apis_with_actor(*args, **kwargs) -> ActorHandle: + current_node_ip = ray._private.worker.global_worker.node_ip_address + # Schedule the actor on the current node. + actor = StateAPIGeneratorActor.options( + resources={f"node:{current_node_ip}": 0.001} + ).remote(*args, **kwargs) + print("Waiting for state api actor to be ready...") + ray.get(actor.ready.remote()) + print("State api actor is ready now.") + actor.start.remote() + return actor + + +def get_state_api_manager(gcs_address: str) -> StateAPIManager: + gcs_client = GcsClient(address=gcs_address) + gcs_channel = GcsChannel(gcs_address=gcs_address, aio=True) + gcs_channel.connect() + state_api_data_source_client = StateDataSourceClient( + gcs_channel.channel(), gcs_client + ) + return StateAPIManager( + state_api_data_source_client, + thread_pool_executor=ThreadPoolExecutor( + thread_name_prefix="state_api_test_utils" + ), + ) + + +def summarize_worker_startup_time(): + workers = list_workers( + detail=True, + filters=[("worker_type", "=", "WORKER")], + limit=10000, + raise_on_missing_output=False, + ) + time_to_launch = [] + time_to_initialize = [] + for worker in workers: + launch_time = worker.get("worker_launch_time_ms") + launched_time = worker.get("worker_launched_time_ms") + start_time = worker.get("start_time_ms") + + if launched_time > 0: + time_to_launch.append(launched_time - launch_time) + if start_time: + time_to_initialize.append(start_time - launched_time) + time_to_launch.sort() + time_to_initialize.sort() + + def print_latencies(latencies): + print(f"Avg: {round(sum(latencies) / len(latencies), 2)} ms") + print(f"P25: {round(latencies[int(len(latencies) * 0.25)], 2)} ms") + print(f"P50: {round(latencies[int(len(latencies) * 0.5)], 2)} ms") + print(f"P95: {round(latencies[int(len(latencies) * 0.95)], 2)} ms") + print(f"P99: {round(latencies[int(len(latencies) * 0.99)], 2)} ms") + + print("Time to launch workers") + print_latencies(time_to_launch) + print("=======================") + print("Time to initialize workers") + print_latencies(time_to_initialize) + + +def verify_failed_task( + name: str, error_type: str, error_message: Union[str, List[str], None] = None +) -> bool: + """ + Check if a task with 'name' has failed with the exact error type 'error_type' + and 'error_message' in the error message. + """ + tasks = list_tasks(filters=[("name", "=", name)], detail=True) + assert len(tasks) == 1, tasks + t = tasks[0] + assert t["state"] == "FAILED", t + assert t["error_type"] == error_type, t + if error_message is not None: + if isinstance(error_message, str): + error_message = [error_message] + for msg in error_message: + assert msg in t.get("error_message", None), t + return True + + +@ray.remote +class PidActor: + def __init__(self): + self.name_to_pid = {} + + def get_pids(self): + return self.name_to_pid + + def report_pid(self, name, pid, state=None): + self.name_to_pid[name] = (pid, state) + + +def _is_actor_task_running(actor_pid: int, task_name: str): + """ + Check whether the actor task `task_name` is running on the actor process + with pid `actor_pid`. + + Args: + actor_pid: The pid of the actor process. + task_name: The name of the actor task. + + Returns: + True if the actor task is running, False otherwise. + + Limitation: + If the actor task name is set using options.name and is a substring of + the actor name, this function may return true even if the task is not + running on the actor process. To resolve this issue, we can possibly + pass in the actor name. + """ + if not psutil.pid_exists(actor_pid): + return False + + """ + Why use both `psutil.Process.name()` and `psutil.Process.cmdline()`? + + 1. Core worker processes call `setproctitle` to set the process title before + and after executing tasks. However, the definition of "title" is a bit + complex. + + [ref]: https://github.com/dvarrazzo/py-setproctitle + + > The process title is usually visible in files such as /proc/PID/cmdline, + /proc/PID/status, /proc/PID/comm, depending on the operating system and + kernel version. This information is used by user-space tools such as ps + and top. + + Ideally, we would only need to check `psutil.Process.cmdline()`, but I decided + to check both `psutil.Process.name()` and `psutil.Process.cmdline()` based on + the definition of "title" stated above. + + 2. Additionally, the definition of `psutil.Process.name()` is not consistent + with the definition of "title" in `setproctitle`. The length of `/proc/PID/comm` and + the prefix of `/proc/PID/cmdline` affect the return value of + `psutil.Process.name()`. + + In addition, executing `setproctitle` in different threads within the same + process may result in different outcomes. + + To learn more details, please refer to the source code of `psutil`: + + [ref]: + https://github.com/giampaolo/psutil/blob/a17550784b0d3175da01cdb02cee1bc6b61637dc/psutil/__init__.py#L664-L693 + + 3. `/proc/PID/comm` will be truncated to TASK_COMM_LEN (16) characters + (including the terminating null byte). + + [ref]: + https://man7.org/linux/man-pages/man5/proc_pid_comm.5.html + """ + name = psutil.Process(actor_pid).name() + if task_name in name and name.startswith("ray::"): + return True + + cmdline = psutil.Process(actor_pid).cmdline() + # If `options.name` is set, the format is `ray::`. If not, + # the format is `ray::.`. + if cmdline and task_name in cmdline[0] and cmdline[0].startswith("ray::"): + return True + return False + + +def verify_tasks_running_or_terminated( + task_pids: Dict[str, Tuple[int, Optional[str]]], expect_num_tasks: int +): + """ + Check if the tasks in task_pids are in RUNNING state if pid exists + and running the task. + If the pid is missing or the task is not running the task, check if the task + is marked FAILED or FINISHED. + + Args: + task_pids: A dict of task name to (pid, expected terminal state). + + """ + assert len(task_pids) == expect_num_tasks, task_pids + for task_name, pid_and_state in task_pids.items(): + tasks = list_tasks(detail=True, filters=[("name", "=", task_name)]) + assert len(tasks) == 1, ( + f"One unique task with {task_name} should be found. " + "Use `options(name=)` when creating the task." + ) + task = tasks[0] + pid, expected_state = pid_and_state + + # If it's windows/macos, we don't have a way to check if the process + # is actually running the task since the process name is just python, + # rather than the actual task name. + if sys.platform in ["win32", "darwin"]: + if expected_state is not None: + assert task["state"] == expected_state, task + continue + if _is_actor_task_running(pid, task_name): + assert ( + "ray::IDLE" not in task["name"] + ), "One should not name it 'IDLE' since it's reserved in Ray" + assert task["state"] == "RUNNING", task + if expected_state is not None: + assert task["state"] == expected_state, task + else: + # Tasks no longer running. + if expected_state is None: + assert task["state"] in [ + "FAILED", + "FINISHED", + ], f"{task_name}: {task['task_id']} = {task['state']}" + else: + assert ( + task["state"] == expected_state + ), f"expect {expected_state} but {task['state']} for {task}" + + return True + + +def verify_schema(state, result_dict: dict, detail: bool = False): + """ + Verify the schema of the result_dict is the same as the state. + """ + state_fields_columns = set() + if detail: + state_fields_columns = state.columns() + else: + state_fields_columns = state.base_columns() + + for k in state_fields_columns: + assert k in result_dict + + for k in result_dict: + assert k in state_fields_columns + + # Make the field values can be converted without error as well + state(**result_dict) + + +def create_api_options( + timeout: int = DEFAULT_RPC_TIMEOUT, + limit: int = DEFAULT_LIMIT, + filters: List[Tuple[str, PredicateType, SupportedFilterType]] = None, + detail: bool = False, + exclude_driver: bool = True, +): + if not filters: + filters = [] + return ListApiOptions( + limit=limit, + timeout=timeout, + filters=filters, + server_timeout_multiplier=1.0, + detail=detail, + exclude_driver=exclude_driver, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/telemetry/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/telemetry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/telemetry/open_telemetry_metric_recorder.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/telemetry/open_telemetry_metric_recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..78c53165003412a4e96a5ab1cbb9d6c84730b55e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/telemetry/open_telemetry_metric_recorder.py @@ -0,0 +1,124 @@ +import logging +import threading +from collections import defaultdict +from typing import List, Optional + +from opentelemetry import metrics +from opentelemetry.exporter.prometheus import PrometheusMetricReader +from opentelemetry.metrics import Observation +from opentelemetry.sdk.metrics import MeterProvider + +from ray._private.metrics_agent import Record + +logger = logging.getLogger(__name__) + +NAMESPACE = "ray" + + +class OpenTelemetryMetricRecorder: + """ + A class to record OpenTelemetry metrics. This is the main entry point for exporting + all ray telemetries to Prometheus server. + It uses OpenTelemetry's Prometheus exporter to export metrics. + """ + + def __init__(self): + self._lock = threading.Lock() + self._registered_instruments = {} + self._observations_by_name = defaultdict(dict) + + prometheus_reader = PrometheusMetricReader() + provider = MeterProvider(metric_readers=[prometheus_reader]) + metrics.set_meter_provider(provider) + self.meter = metrics.get_meter(__name__) + + def register_gauge_metric(self, name: str, description: str) -> None: + with self._lock: + if name in self._registered_instruments: + # Gauge with the same name is already registered. + return + + # Register ObservableGauge with a dynamic callback. Callbacks are special + # features in OpenTelemetry that allow you to provide a function that will + # compute the telemetry at collection time. + def callback(options): + # Take snapshot of current observations. + with self._lock: + observations = self._observations_by_name.get(name, {}).items() + return [ + Observation(val, attributes=dict(tag_set)) + for tag_set, val in observations + ] + + instrument = self.meter.create_observable_gauge( + name=f"{NAMESPACE}_{name}", + description=description, + unit="1", + callbacks=[callback], + ) + self._registered_instruments[name] = instrument + self._observations_by_name[name] = {} + + def register_counter_metric(self, name: str, description: str) -> None: + """ + Register a counter metric with the given name and description. + """ + with self._lock: + if name in self._registered_instruments: + # Counter with the same name is already registered. + return + + instrument = self.meter.create_counter( + name=f"{NAMESPACE}_{name}", + description=description, + unit="1", + ) + self._registered_instruments[name] = instrument + + def set_metric_value(self, name: str, tags: dict, value: float): + """ + Set the value of a metric with the given name and tags. If the metric is not + registered, it lazily records the value for observable metrics or is a no-op for + synchronous metrics. + """ + with self._lock: + if self._observations_by_name.get(name) is not None: + # Set the value of an observable metric with the given name and tags. It + # lazily records the metric value by storing it in a dictionary until + # the value actually gets exported by OpenTelemetry. + self._observations_by_name[name][frozenset(tags.items())] = value + else: + # Set the value of a synchronous metric with the given name and tags. + # It is a no-op if the metric is not registered. + instrument = self._registered_instruments.get(name) + if isinstance(instrument, metrics.Counter): + instrument.add(value, attributes=tags) + else: + logger.warning( + f"Unsupported synchronous instrument type for metric: {name}." + ) + + def record_and_export(self, records: List[Record], global_tags=None): + """ + Record a list of telemetry records and export them to Prometheus. + """ + global_tags = global_tags or {} + + for record in records: + gauge = record.gauge + value = record.value + tags = {**record.tags, **global_tags} + try: + self.register_gauge_metric(gauge.name, gauge.description or "") + self.set_metric_value(gauge.name, tags, value) + except Exception as e: + logger.error( + f"Failed to record metric {gauge.name} with value {value} with tags {tags!r} and global tags {global_tags!r} due to: {e!r}" + ) + + def _get_observable_metric_value(self, name: str, tags: dict) -> Optional[float]: + """ + Get the value of a metric with the given name and tags. This method is mainly + used for testing purposes. + """ + return self._observations_by_name[name].get(frozenset(tags.items()), 0.0) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/test_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8117338d99b17173cec814151befac287c4f1435 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/test_utils.py @@ -0,0 +1,1997 @@ +import asyncio +import fnmatch +import io +import json +import logging +import os +import pathlib +import random +import socket +import subprocess +import sys +import tempfile +import threading +import time +import timeit +import traceback +import uuid +from collections import defaultdict +from contextlib import contextmanager, redirect_stderr, redirect_stdout +from dataclasses import dataclass +from datetime import datetime +from typing import Any, Callable, Dict, List, Optional, Set, Tuple + +import requests +import yaml + +import ray +import ray._private.gcs_utils as gcs_utils +import ray._private.memory_monitor as memory_monitor +import ray._private.services +import ray._private.services as services +import ray._private.utils +from ray._common.test_utils import wait_for_condition +from ray._common.utils import get_or_create_event_loop +from ray._private import ( + ray_constants, +) +from ray._private.internal_api import memory_summary +from ray._private.tls_utils import generate_self_signed_tls_certs +from ray._private.worker import RayContext +from ray._raylet import Config, GcsClientOptions, GlobalStateAccessor +from ray.core.generated import ( + gcs_pb2, + gcs_service_pb2, + node_manager_pb2, +) +from ray.util.queue import Empty, Queue, _QueueActor +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +import psutil # We must import psutil after ray because we bundle it with ray. + +logger = logging.getLogger(__name__) + +EXE_SUFFIX = ".exe" if sys.platform == "win32" else "" +RAY_PATH = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) +REDIS_EXECUTABLE = os.path.join( + RAY_PATH, "core/src/ray/thirdparty/redis/src/redis-server" + EXE_SUFFIX +) + +try: + from prometheus_client.parser import Sample, text_string_to_metric_families +except (ImportError, ModuleNotFoundError): + + Sample = None + + def text_string_to_metric_families(*args, **kwargs): + raise ModuleNotFoundError("`prometheus_client` not found") + + +def make_global_state_accessor(ray_context): + gcs_options = GcsClientOptions.create( + ray_context.address_info["gcs_address"], + None, + allow_cluster_id_nil=True, + fetch_cluster_id_if_nil=False, + ) + global_state_accessor = GlobalStateAccessor(gcs_options) + global_state_accessor.connect() + return global_state_accessor + + +def external_redis_test_enabled(): + return os.environ.get("TEST_EXTERNAL_REDIS") == "1" + + +def redis_replicas(): + return int(os.environ.get("TEST_EXTERNAL_REDIS_REPLICAS", "1")) + + +def redis_sentinel_replicas(): + return int(os.environ.get("TEST_EXTERNAL_REDIS_SENTINEL_REPLICAS", "2")) + + +def get_redis_cli(port, enable_tls): + try: + # If there is no redis libs installed, skip the check. + # This could happen In minimal test, where we don't have + # redis. + import redis + except Exception: + return True + + params = {} + if enable_tls: + from ray._raylet import Config + + params = {"ssl": True, "ssl_cert_reqs": "required"} + if Config.REDIS_CA_CERT(): + params["ssl_ca_certs"] = Config.REDIS_CA_CERT() + if Config.REDIS_CLIENT_CERT(): + params["ssl_certfile"] = Config.REDIS_CLIENT_CERT() + if Config.REDIS_CLIENT_KEY(): + params["ssl_keyfile"] = Config.REDIS_CLIENT_KEY() + + return redis.Redis("localhost", str(port), **params) + + +def start_redis_sentinel_instance( + session_dir_path: str, + port: int, + redis_master_port: int, + password: Optional[str] = None, + enable_tls: bool = False, + db_dir=None, + free_port=0, +): + config_file = os.path.join( + session_dir_path, "redis-sentinel-" + uuid.uuid4().hex + ".conf" + ) + config_lines = [] + # Port for this Sentinel instance + if enable_tls: + config_lines.append(f"port {free_port}") + else: + config_lines.append(f"port {port}") + + # Monitor the Redis master + config_lines.append(f"sentinel monitor redis-test 127.0.0.1 {redis_master_port} 1") + config_lines.append( + "sentinel down-after-milliseconds redis-test 1000" + ) # failover after 1 second + config_lines.append("sentinel failover-timeout redis-test 5000") # + config_lines.append("sentinel parallel-syncs redis-test 1") + + if password: + config_lines.append(f"sentinel auth-pass redis-test {password}") + + if enable_tls: + config_lines.append(f"tls-port {port}") + if Config.REDIS_CA_CERT(): + config_lines.append(f"tls-ca-cert-file {Config.REDIS_CA_CERT()}") + # Check and add TLS client certificate file + if Config.REDIS_CLIENT_CERT(): + config_lines.append(f"tls-cert-file {Config.REDIS_CLIENT_CERT()}") + # Check and add TLS client key file + if Config.REDIS_CLIENT_KEY(): + config_lines.append(f"tls-key-file {Config.REDIS_CLIENT_KEY()}") + config_lines.append("tls-auth-clients no") + config_lines.append("sentinel tls-auth-clients redis-test no") + if db_dir: + config_lines.append(f"dir {db_dir}") + + with open(config_file, "w") as f: + f.write("\n".join(config_lines)) + + command = [REDIS_EXECUTABLE, config_file, "--sentinel"] + process_info = ray._private.services.start_ray_process( + command, + ray_constants.PROCESS_TYPE_REDIS_SERVER, + fate_share=False, + ) + return process_info + + +def start_redis_instance( + session_dir_path: str, + port: int, + redis_max_clients: Optional[int] = None, + num_retries: int = 20, + stdout_file: Optional[str] = None, + stderr_file: Optional[str] = None, + password: Optional[str] = None, + fate_share: Optional[bool] = None, + port_denylist: Optional[List[int]] = None, + listen_to_localhost_only: bool = False, + enable_tls: bool = False, + replica_of=None, + leader_id=None, + db_dir=None, + free_port=0, +): + """Start a single Redis server. + + Notes: + We will initially try to start the Redis instance at the given port, + and then try at most `num_retries - 1` times to start the Redis + instance at successive random ports. + + Args: + session_dir_path: Path to the session directory of + this Ray cluster. + port: Try to start a Redis server at this port. + redis_max_clients: If this is provided, Ray will attempt to configure + Redis with this maxclients number. + num_retries: The number of times to attempt to start Redis at + successive ports. + stdout_file: A file handle opened for writing to redirect stdout to. If + no redirection should happen, then this should be None. + stderr_file: A file handle opened for writing to redirect stderr to. If + no redirection should happen, then this should be None. + password: Prevents external clients without the password + from connecting to Redis if provided. + port_denylist: A set of denylist ports that shouldn't + be used when allocating a new port. + listen_to_localhost_only: Redis server only listens to + localhost (127.0.0.1) if it's true, + otherwise it listens to all network interfaces. + enable_tls: Enable the TLS/SSL in Redis or not + + Returns: + A tuple of the port used by Redis and ProcessInfo for the process that + was started. If a port is passed in, then the returned port value + is the same. + + Raises: + Exception: An exception is raised if Redis could not be started. + """ + + assert os.path.isfile(REDIS_EXECUTABLE) + + # Construct the command to start the Redis server. + command = [REDIS_EXECUTABLE] + if password: + if " " in password: + raise ValueError("Spaces not permitted in redis password.") + command += ["--requirepass", password] + if redis_replicas() > 1: + command += ["--cluster-enabled", "yes", "--cluster-config-file", f"node-{port}"] + if enable_tls: + command += [ + "--tls-port", + str(port), + "--loglevel", + "warning", + "--port", + str(free_port), + ] + else: + command += ["--port", str(port), "--loglevel", "warning"] + + if listen_to_localhost_only: + command += ["--bind", "127.0.0.1"] + pidfile = os.path.join(session_dir_path, "redis-" + uuid.uuid4().hex + ".pid") + command += ["--pidfile", pidfile] + if enable_tls: + if Config.REDIS_CA_CERT(): + command += ["--tls-ca-cert-file", Config.REDIS_CA_CERT()] + if Config.REDIS_CLIENT_CERT(): + command += ["--tls-cert-file", Config.REDIS_CLIENT_CERT()] + if Config.REDIS_CLIENT_KEY(): + command += ["--tls-key-file", Config.REDIS_CLIENT_KEY()] + if replica_of is not None: + command += ["--tls-replication", "yes"] + command += ["--tls-auth-clients", "no", "--tls-cluster", "yes"] + if sys.platform != "win32": + command += ["--save", "", "--appendonly", "no"] + if db_dir is not None: + command += ["--dir", str(db_dir)] + + process_info = ray._private.services.start_ray_process( + command, + ray_constants.PROCESS_TYPE_REDIS_SERVER, + stdout_file=stdout_file, + stderr_file=stderr_file, + fate_share=fate_share, + ) + node_id = None + if redis_replicas() > 1: + # Setup redis cluster + import redis + + while True: + try: + redis_cli = get_redis_cli(port, enable_tls) + if replica_of is None: + slots = [str(i) for i in range(16384)] + redis_cli.cluster("addslots", *slots) + else: + logger.info(redis_cli.cluster("meet", "127.0.0.1", str(replica_of))) + logger.info(redis_cli.cluster("replicate", leader_id)) + node_id = redis_cli.cluster("myid") + break + except ( + redis.exceptions.ConnectionError, + redis.exceptions.ResponseError, + ) as e: + from time import sleep + + logger.info( + f"Waiting for redis to be up. Check failed with error: {e}. " + "Will retry in 0.1s" + ) + + if process_info.process.poll() is not None: + raise Exception( + f"Redis process exited unexpectedly: {process_info}. " + f"Exit code: {process_info.process.returncode}" + ) + + sleep(0.1) + + logger.info( + f"Redis started with node_id {node_id} and pid {process_info.process.pid}" + ) + + return node_id, process_info + + +def _pid_alive(pid): + """Check if the process with this PID is alive or not. + + Args: + pid: The pid to check. + + Returns: + This returns false if the process is dead. Otherwise, it returns true. + """ + alive = True + try: + proc = psutil.Process(pid) + if proc.status() == psutil.STATUS_ZOMBIE: + alive = False + except psutil.NoSuchProcess: + alive = False + return alive + + +def _check_call_windows(main, argv, capture_stdout=False, capture_stderr=False): + # We use this function instead of calling the "ray" command to work around + # some deadlocks that occur when piping ray's output on Windows + stream = io.TextIOWrapper(io.BytesIO(), encoding=sys.stdout.encoding) + old_argv = sys.argv[:] + try: + sys.argv = argv[:] + try: + with redirect_stderr(stream if capture_stderr else sys.stderr): + with redirect_stdout(stream if capture_stdout else sys.stdout): + main() + finally: + stream.flush() + except SystemExit as ex: + if ex.code: + output = stream.buffer.getvalue() + raise subprocess.CalledProcessError(ex.code, argv, output) + except Exception as ex: + output = stream.buffer.getvalue() + raise subprocess.CalledProcessError(1, argv, output, ex.args[0]) + finally: + sys.argv = old_argv + if capture_stdout: + sys.stdout.buffer.write(stream.buffer.getvalue()) + elif capture_stderr: + sys.stderr.buffer.write(stream.buffer.getvalue()) + return stream.buffer.getvalue() + + +def check_call_subprocess(argv, capture_stdout=False, capture_stderr=False): + # We use this function instead of calling the "ray" command to work around + # some deadlocks that occur when piping ray's output on Windows + from ray.scripts.scripts import main as ray_main + + if sys.platform == "win32": + result = _check_call_windows( + ray_main, argv, capture_stdout=capture_stdout, capture_stderr=capture_stderr + ) + else: + stdout_redir = None + stderr_redir = None + if capture_stdout: + stdout_redir = subprocess.PIPE + if capture_stderr and capture_stdout: + stderr_redir = subprocess.STDOUT + elif capture_stderr: + stderr_redir = subprocess.PIPE + proc = subprocess.Popen(argv, stdout=stdout_redir, stderr=stderr_redir) + (stdout, stderr) = proc.communicate() + if proc.returncode: + raise subprocess.CalledProcessError(proc.returncode, argv, stdout, stderr) + result = b"".join([s for s in [stdout, stderr] if s is not None]) + return result + + +def check_call_ray(args, capture_stdout=False, capture_stderr=False): + check_call_subprocess(["ray"] + args, capture_stdout, capture_stderr) + + +def wait_for_pid_to_exit(pid: int, timeout: float = 20): + start_time = time.time() + while time.time() - start_time < timeout: + if not _pid_alive(pid): + return + time.sleep(0.1) + raise TimeoutError(f"Timed out while waiting for process {pid} to exit.") + + +def wait_for_children_of_pid(pid, num_children=1, timeout=20): + p = psutil.Process(pid) + start_time = time.time() + alive = [] + while time.time() - start_time < timeout: + alive = p.children(recursive=False) + num_alive = len(alive) + if num_alive >= num_children: + return + time.sleep(0.1) + raise TimeoutError( + f"Timed out while waiting for process {pid} children to start " + f"({num_alive}/{num_children} started: {alive})." + ) + + +def wait_for_children_of_pid_to_exit(pid, timeout=20): + children = psutil.Process(pid).children() + if len(children) == 0: + return + + _, alive = psutil.wait_procs(children, timeout=timeout) + if len(alive) > 0: + raise TimeoutError( + "Timed out while waiting for process children to exit." + " Children still alive: {}.".format([p.name() for p in alive]) + ) + + +def kill_process_by_name(name, SIGKILL=False): + for p in psutil.process_iter(attrs=["name"]): + if p.info["name"] == name + ray._private.services.EXE_SUFFIX: + if SIGKILL: + p.kill() + else: + p.terminate() + + +def run_string_as_driver(driver_script: str, env: Dict = None, encode: str = "utf-8"): + """Run a driver as a separate process. + + Args: + driver_script: A string to run as a Python script. + env: The environment variables for the driver. + + Returns: + The script's output. + """ + proc = subprocess.Popen( + [sys.executable, "-"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=env, + ) + with proc: + output = proc.communicate(driver_script.encode(encoding=encode))[0] + if proc.returncode: + print(ray._common.utils.decode(output, encode_type=encode)) + logger.error(proc.stderr) + raise subprocess.CalledProcessError( + proc.returncode, proc.args, output, proc.stderr + ) + out = ray._common.utils.decode(output, encode_type=encode) + return out + + +def run_string_as_driver_stdout_stderr( + driver_script: str, env: Dict = None, encode: str = "utf-8" +) -> Tuple[str, str]: + """Run a driver as a separate process. + + Args: + driver_script: A string to run as a Python script. + env: The environment variables for the driver. + + Returns: + The script's stdout and stderr. + """ + proc = subprocess.Popen( + [sys.executable, "-"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + with proc: + outputs_bytes = proc.communicate(driver_script.encode(encoding=encode)) + out_str, err_str = [ + ray._common.utils.decode(output, encode_type=encode) + for output in outputs_bytes + ] + if proc.returncode: + print(out_str) + print(err_str) + raise subprocess.CalledProcessError( + proc.returncode, proc.args, out_str, err_str + ) + return out_str, err_str + + +def run_string_as_driver_nonblocking(driver_script, env: Dict = None): + """Start a driver as a separate process and return immediately. + + Args: + driver_script: A string to run as a Python script. + + Returns: + A handle to the driver process. + """ + script = "; ".join( + [ + "import sys", + "script = sys.stdin.read()", + "sys.stdin.close()", + "del sys", + 'exec("del script\\n" + script)', + ] + ) + proc = subprocess.Popen( + [sys.executable, "-c", script], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + env=env, + ) + proc.stdin.write(driver_script.encode("ascii")) + proc.stdin.close() + return proc + + +def convert_actor_state(state): + if not state: + return None + return gcs_pb2.ActorTableData.ActorState.DESCRIPTOR.values_by_number[state].name + + +def wait_for_num_actors(num_actors, state=None, timeout=10): + state = convert_actor_state(state) + start_time = time.time() + while time.time() - start_time < timeout: + if ( + len( + [ + _ + for _ in ray._private.state.actors().values() + if state is None or _["State"] == state + ] + ) + >= num_actors + ): + return + time.sleep(0.1) + raise TimeoutError("Timed out while waiting for global state.") + + +def kill_actor_and_wait_for_failure(actor, timeout=10, retry_interval_ms=100): + actor_id = actor._actor_id.hex() + current_num_restarts = ray._private.state.actors(actor_id)["NumRestarts"] + ray.kill(actor) + start = time.time() + while time.time() - start <= timeout: + actor_status = ray._private.state.actors(actor_id) + if ( + actor_status["State"] == convert_actor_state(gcs_utils.ActorTableData.DEAD) + or actor_status["NumRestarts"] > current_num_restarts + ): + return + time.sleep(retry_interval_ms / 1000.0) + raise RuntimeError("It took too much time to kill an actor: {}".format(actor_id)) + + +def wait_for_assertion( + assertion_predictor: Callable, + timeout: int = 10, + retry_interval_ms: int = 100, + raise_exceptions: bool = False, + **kwargs: Any, +): + """Wait until an assertion is met or time out with an exception. + + Args: + assertion_predictor: A function that predicts the assertion. + timeout: Maximum timeout in seconds. + retry_interval_ms: Retry interval in milliseconds. + raise_exceptions: If true, exceptions that occur while executing + assertion_predictor won't be caught and instead will be raised. + **kwargs: Arguments to pass to the condition_predictor. + + Raises: + RuntimeError: If the assertion is not met before the timeout expires. + """ + + def _assertion_to_condition(): + try: + assertion_predictor(**kwargs) + return True + except AssertionError: + return False + + try: + wait_for_condition( + _assertion_to_condition, + timeout=timeout, + retry_interval_ms=retry_interval_ms, + raise_exceptions=raise_exceptions, + **kwargs, + ) + except RuntimeError: + assertion_predictor(**kwargs) # Should fail assert + + +@dataclass +class MetricSamplePattern: + name: Optional[str] = None + value: Optional[str] = None + partial_label_match: Optional[Dict[str, str]] = None + + def matches(self, sample: Sample): + if self.name is not None: + if self.name != sample.name: + return False + + if self.value is not None: + if self.value != sample.value: + return False + + if self.partial_label_match is not None: + for label, value in self.partial_label_match.items(): + if sample.labels.get(label) != value: + return False + + return True + + +def get_metric_check_condition( + metrics_to_check: List[MetricSamplePattern], export_addr: Optional[str] = None +) -> Callable[[], bool]: + """A condition to check if a prometheus metrics reach a certain value. + + This is a blocking check that can be passed into a `wait_for_condition` + style function. + + Args: + metrics_to_check: A list of MetricSamplePattern. The fields that + aren't `None` will be matched. + export_addr: Optional address to export metrics to. + + Returns: + A function that returns True if all the metrics are emitted. + """ + node_info = ray.nodes()[0] + metrics_export_port = node_info["MetricsExportPort"] + addr = node_info["NodeManagerAddress"] + prom_addr = export_addr or f"{addr}:{metrics_export_port}" + + def f(): + for metric_pattern in metrics_to_check: + _, _, metric_samples = fetch_prometheus([prom_addr]) + for metric_sample in metric_samples: + if metric_pattern.matches(metric_sample): + break + else: + print( + f"Didn't find {metric_pattern}", + "all samples", + metric_samples, + ) + return False + return True + + return f + + +def wait_until_succeeded_without_exception( + func, exceptions, *args, timeout_ms=1000, retry_interval_ms=100, raise_last_ex=False +): + """A helper function that waits until a given function + completes without exceptions. + + Args: + func: A function to run. + exceptions: Exceptions that are supposed to occur. + args: arguments to pass for a given func + timeout_ms: Maximum timeout in milliseconds. + retry_interval_ms: Retry interval in milliseconds. + raise_last_ex: Raise the last exception when timeout. + + Return: + Whether exception occurs within a timeout. + """ + if isinstance(type(exceptions), tuple): + raise Exception("exceptions arguments should be given as a tuple") + + time_elapsed = 0 + start = time.time() + last_ex = None + while time_elapsed <= timeout_ms: + try: + func(*args) + return True + except exceptions as ex: + last_ex = ex + time_elapsed = (time.time() - start) * 1000 + time.sleep(retry_interval_ms / 1000.0) + if raise_last_ex: + ex_stack = ( + traceback.format_exception(type(last_ex), last_ex, last_ex.__traceback__) + if last_ex + else [] + ) + ex_stack = "".join(ex_stack) + raise Exception(f"Timed out while testing, {ex_stack}") + return False + + +def recursive_fnmatch(dirpath, pattern): + """Looks at a file directory subtree for a filename pattern. + + Similar to glob.glob(..., recursive=True) but also supports 2.7 + """ + matches = [] + for root, dirnames, filenames in os.walk(dirpath): + for filename in fnmatch.filter(filenames, pattern): + matches.append(os.path.join(root, filename)) + return matches + + +def generate_system_config_map(**kwargs): + ray_kwargs = { + "_system_config": kwargs, + } + return ray_kwargs + + +def same_elements(elems_a, elems_b): + """Checks if two iterables (such as lists) contain the same elements. Elements + do not have to be hashable (this allows us to compare sets of dicts for + example). This comparison is not necessarily efficient. + """ + a = list(elems_a) + b = list(elems_b) + + for x in a: + if x not in b: + return False + + for x in b: + if x not in a: + return False + + return True + + +@ray.remote +def _put(obj): + return obj + + +def put_object(obj, use_ray_put): + if use_ray_put: + return ray.put(obj) + else: + return _put.remote(obj) + + +def wait_until_server_available(address, timeout_ms=5000, retry_interval_ms=100): + ip_port = address.split(":") + ip = ip_port[0] + port = int(ip_port[1]) + time_elapsed = 0 + start = time.time() + while time_elapsed <= timeout_ms: + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.settimeout(1) + try: + s.connect((ip, port)) + except Exception: + time_elapsed = (time.time() - start) * 1000 + time.sleep(retry_interval_ms / 1000.0) + s.close() + continue + s.close() + return True + return False + + +def get_other_nodes(cluster, exclude_head=False): + """Get all nodes except the one that we're connected to.""" + return [ + node + for node in cluster.list_all_nodes() + if node._raylet_socket_name + != ray._private.worker._global_node._raylet_socket_name + and (exclude_head is False or node.head is False) + ] + + +def get_non_head_nodes(cluster): + """Get all non-head nodes.""" + return list(filter(lambda x: x.head is False, cluster.list_all_nodes())) + + +def init_error_pubsub(): + """Initialize error info pub/sub""" + s = ray._raylet.GcsErrorSubscriber( + address=ray._private.worker.global_worker.gcs_client.address + ) + s.subscribe() + return s + + +def get_error_message(subscriber, num=1e6, error_type=None, timeout=20): + """Gets errors from GCS subscriber. + + Returns maximum `num` error strings within `timeout`. + Only returns errors of `error_type` if specified. + """ + deadline = time.time() + timeout + msgs = [] + while time.time() < deadline and len(msgs) < num: + _, error_data = subscriber.poll(timeout=deadline - time.time()) + if not error_data: + # Timed out before any data is received. + break + if error_type is None or error_type == error_data["type"]: + msgs.append(error_data) + else: + time.sleep(0.01) + + return msgs + + +def init_log_pubsub(): + """Initialize log pub/sub""" + s = ray._raylet.GcsLogSubscriber( + address=ray._private.worker.global_worker.gcs_client.address + ) + s.subscribe() + return s + + +def get_log_data( + subscriber, + num: int = 1e6, + timeout: float = 20, + job_id: Optional[str] = None, + matcher=None, +) -> List[dict]: + deadline = time.time() + timeout + msgs = [] + while time.time() < deadline and len(msgs) < num: + logs_data = subscriber.poll(timeout=deadline - time.time()) + if not logs_data: + # Timed out before any data is received. + break + if job_id and job_id != logs_data["job"]: + continue + if matcher and all(not matcher(line) for line in logs_data["lines"]): + continue + msgs.append(logs_data) + return msgs + + +def get_log_message( + subscriber, + num: int = 1e6, + timeout: float = 20, + job_id: Optional[str] = None, + matcher=None, +) -> List[List[str]]: + """Gets log lines through GCS subscriber. + + Returns maximum `num` of log messages, within `timeout`. + + If `job_id` or `match` is specified, only returns log lines from `job_id` + or when `matcher` is true. + """ + msgs = get_log_data(subscriber, num, timeout, job_id, matcher) + return [msg["lines"] for msg in msgs] + + +def get_log_sources( + subscriber, + num: int = 1e6, + timeout: float = 20, + job_id: Optional[str] = None, + matcher=None, +): + """Get the source of all log messages""" + msgs = get_log_data(subscriber, num, timeout, job_id, matcher) + return {msg["pid"] for msg in msgs} + + +def get_log_batch( + subscriber, + num: int, + timeout: float = 20, + job_id: Optional[str] = None, + matcher=None, +) -> List[str]: + """Gets log batches through GCS subscriber. + + Returns maximum `num` batches of logs. Each batch is a dict that includes + metadata such as `pid`, `job_id`, and `lines` of log messages. + + If `job_id` or `match` is specified, only returns log batches from `job_id` + or when `matcher` is true. + """ + deadline = time.time() + timeout + batches = [] + while time.time() < deadline and len(batches) < num: + logs_data = subscriber.poll(timeout=deadline - time.time()) + if not logs_data: + # Timed out before any data is received. + break + if job_id and job_id != logs_data["job"]: + continue + if matcher and not matcher(logs_data): + continue + batches.append(logs_data) + + return batches + + +def format_web_url(url): + """Format web url.""" + url = url.replace("localhost", "http://127.0.0.1") + if not url.startswith("http://"): + return "http://" + url + return url + + +def client_test_enabled() -> bool: + return ray._private.client_mode_hook.is_client_mode_enabled + + +def object_memory_usage() -> bool: + """Returns the number of bytes used in the object store.""" + total = ray.cluster_resources().get("object_store_memory", 0) + avail = ray.available_resources().get("object_store_memory", 0) + return total - avail + + +def fetch_raw_prometheus(prom_addresses): + # Local import so minimal dependency tests can run without requests + import requests + + for address in prom_addresses: + try: + response = requests.get(f"http://{address}/metrics") + yield address, response.text + except requests.exceptions.ConnectionError: + continue + + +def fetch_prometheus(prom_addresses): + components_dict = {} + metric_descriptors = {} + metric_samples = [] + + for address in prom_addresses: + if address not in components_dict: + components_dict[address] = set() + + for address, response in fetch_raw_prometheus(prom_addresses): + for metric in text_string_to_metric_families(response): + for sample in metric.samples: + metric_descriptors[sample.name] = metric + metric_samples.append(sample) + if "Component" in sample.labels: + components_dict[address].add(sample.labels["Component"]) + return components_dict, metric_descriptors, metric_samples + + +def fetch_prometheus_metrics(prom_addresses: List[str]) -> Dict[str, List[Any]]: + """Return prometheus metrics from the given addresses. + + Args: + prom_addresses: List of metrics_agent addresses to collect metrics from. + + Returns: + Dict mapping from metric name to list of samples for the metric. + """ + _, _, samples = fetch_prometheus(prom_addresses) + samples_by_name = defaultdict(list) + for sample in samples: + samples_by_name[sample.name].append(sample) + return samples_by_name + + +def raw_metrics(info: RayContext) -> Dict[str, List[Any]]: + """Return prometheus metrics from a RayContext + + Args: + info: Ray context returned from ray.init() + + Returns: + Dict from metric name to a list of samples for the metrics + """ + metrics_page = "localhost:{}".format(info.address_info["metrics_export_port"]) + print("Fetch metrics from", metrics_page) + return fetch_prometheus_metrics([metrics_page]) + + +def get_test_config_path(config_file_name): + """Resolve the test config path from the config file dir""" + here = os.path.realpath(__file__) + path = pathlib.Path(here) + grandparent = path.parent.parent + return os.path.join(grandparent, "tests/test_cli_patterns", config_file_name) + + +def load_test_config(config_file_name): + """Loads a config yaml from tests/test_cli_patterns.""" + config_path = get_test_config_path(config_file_name) + config = yaml.safe_load(open(config_path).read()) + return config + + +def set_setup_func(): + import ray._private.runtime_env as runtime_env + + runtime_env.VAR = "hello world" + + +class BatchQueue(Queue): + def __init__(self, maxsize: int = 0, actor_options: Optional[Dict] = None) -> None: + actor_options = actor_options or {} + self.maxsize = maxsize + self.actor = ( + ray.remote(_BatchQueueActor).options(**actor_options).remote(self.maxsize) + ) + + def get_batch( + self, + batch_size: int = None, + total_timeout: Optional[float] = None, + first_timeout: Optional[float] = None, + ) -> List[Any]: + """Gets batch of items from the queue and returns them in a + list in order. + + Raises: + Empty: if the queue does not contain the desired number of items + """ + return ray.get( + self.actor.get_batch.remote(batch_size, total_timeout, first_timeout) + ) + + +class _BatchQueueActor(_QueueActor): + async def get_batch(self, batch_size=None, total_timeout=None, first_timeout=None): + start = timeit.default_timer() + try: + first = await asyncio.wait_for(self.queue.get(), first_timeout) + batch = [first] + if total_timeout: + end = timeit.default_timer() + total_timeout = max(total_timeout - (end - start), 0) + except asyncio.TimeoutError: + raise Empty + if batch_size is None: + if total_timeout is None: + total_timeout = 0 + while True: + try: + start = timeit.default_timer() + batch.append( + await asyncio.wait_for(self.queue.get(), total_timeout) + ) + if total_timeout: + end = timeit.default_timer() + total_timeout = max(total_timeout - (end - start), 0) + except asyncio.TimeoutError: + break + else: + for _ in range(batch_size - 1): + try: + start = timeit.default_timer() + batch.append( + await asyncio.wait_for(self.queue.get(), total_timeout) + ) + if total_timeout: + end = timeit.default_timer() + total_timeout = max(total_timeout - (end - start), 0) + except asyncio.TimeoutError: + break + return batch + + +def is_placement_group_removed(pg): + table = ray.util.placement_group_table(pg) + if "state" not in table: + return False + return table["state"] == "REMOVED" + + +def placement_group_assert_no_leak(pgs_created): + for pg in pgs_created: + ray.util.remove_placement_group(pg) + + def wait_for_pg_removed(): + for pg_entry in ray.util.placement_group_table().values(): + if pg_entry["state"] != "REMOVED": + return False + return True + + wait_for_condition(wait_for_pg_removed) + + cluster_resources = ray.cluster_resources() + cluster_resources.pop("memory") + cluster_resources.pop("object_store_memory") + + def wait_for_resource_recovered(): + for resource, val in ray.available_resources().items(): + if resource in cluster_resources and cluster_resources[resource] != val: + return False + if "_group_" in resource: + return False + return True + + wait_for_condition(wait_for_resource_recovered) + + +def monitor_memory_usage( + print_interval_s: int = 30, + record_interval_s: int = 5, + warning_threshold: float = 0.9, +): + """Run the memory monitor actor that prints the memory usage. + + The monitor will run on the same node as this function is called. + + Params: + interval_s: The interval memory usage information is printed + warning_threshold: The threshold where the + memory usage warning is printed. + + Returns: + The memory monitor actor. + """ + assert ray.is_initialized(), "The API is only available when Ray is initialized." + + @ray.remote(num_cpus=0) + class MemoryMonitorActor: + def __init__( + self, + print_interval_s: float = 20, + record_interval_s: float = 5, + warning_threshold: float = 0.9, + n: int = 10, + ): + """The actor that monitor the memory usage of the cluster. + + Params: + print_interval_s: The interval where + memory usage is printed. + record_interval_s: The interval where + memory usage is recorded. + warning_threshold: The threshold where + memory warning is printed + n: When memory usage is printed, + top n entries are printed. + """ + # -- Interval the monitor prints the memory usage information. -- + self.print_interval_s = print_interval_s + # -- Interval the monitor records the memory usage information. -- + self.record_interval_s = record_interval_s + # -- Whether or not the monitor is running. -- + self.is_running = False + # -- The used_gb/total_gb threshold where warning message omits. -- + self.warning_threshold = warning_threshold + # -- The monitor that calculates the memory usage of the node. -- + self.monitor = memory_monitor.MemoryMonitor() + # -- The top n memory usage of processes are printed. -- + self.n = n + # -- The peak memory usage in GB during lifetime of monitor. -- + self.peak_memory_usage = 0 + # -- The top n memory usage of processes + # during peak memory usage. -- + self.peak_top_n_memory_usage = "" + # -- The last time memory usage was printed -- + self._last_print_time = 0 + # -- logger. -- + logging.basicConfig(level=logging.INFO) + + def ready(self): + pass + + async def run(self): + """Run the monitor.""" + self.is_running = True + while self.is_running: + now = time.time() + used_gb, total_gb = self.monitor.get_memory_usage() + top_n_memory_usage = memory_monitor.get_top_n_memory_usage(n=self.n) + if used_gb > self.peak_memory_usage: + self.peak_memory_usage = used_gb + self.peak_top_n_memory_usage = top_n_memory_usage + + if used_gb > total_gb * self.warning_threshold: + logging.warning( + "The memory usage is high: " f"{used_gb / total_gb * 100}%" + ) + if now - self._last_print_time > self.print_interval_s: + logging.info(f"Memory usage: {used_gb} / {total_gb}") + logging.info(f"Top {self.n} process memory usage:") + logging.info(top_n_memory_usage) + self._last_print_time = now + await asyncio.sleep(self.record_interval_s) + + async def stop_run(self): + """Stop running the monitor. + + Returns: + True if the monitor is stopped. False otherwise. + """ + was_running = self.is_running + self.is_running = False + return was_running + + async def get_peak_memory_info(self): + """Return the tuple of the peak memory usage and the + top n process information during the peak memory usage. + """ + return self.peak_memory_usage, self.peak_top_n_memory_usage + + current_node_ip = ray._private.worker.global_worker.node_ip_address + # Schedule the actor on the current node. + memory_monitor_actor = MemoryMonitorActor.options( + resources={f"node:{current_node_ip}": 0.001} + ).remote( + print_interval_s=print_interval_s, + record_interval_s=record_interval_s, + warning_threshold=warning_threshold, + ) + print("Waiting for memory monitor actor to be ready...") + ray.get(memory_monitor_actor.ready.remote()) + print("Memory monitor actor is ready now.") + memory_monitor_actor.run.remote() + return memory_monitor_actor + + +def setup_tls(): + """Sets up required environment variables for tls""" + import pytest + + if sys.platform == "darwin": + pytest.skip("Cryptography doesn't install in Mac build pipeline") + cert, key = generate_self_signed_tls_certs() + temp_dir = tempfile.mkdtemp("ray-test-certs") + cert_filepath = os.path.join(temp_dir, "server.crt") + key_filepath = os.path.join(temp_dir, "server.key") + with open(cert_filepath, "w") as fh: + fh.write(cert) + with open(key_filepath, "w") as fh: + fh.write(key) + + os.environ["RAY_USE_TLS"] = "1" + os.environ["RAY_TLS_SERVER_CERT"] = cert_filepath + os.environ["RAY_TLS_SERVER_KEY"] = key_filepath + os.environ["RAY_TLS_CA_CERT"] = cert_filepath + + return key_filepath, cert_filepath, temp_dir + + +def teardown_tls(key_filepath, cert_filepath, temp_dir): + os.remove(key_filepath) + os.remove(cert_filepath) + os.removedirs(temp_dir) + del os.environ["RAY_USE_TLS"] + del os.environ["RAY_TLS_SERVER_CERT"] + del os.environ["RAY_TLS_SERVER_KEY"] + del os.environ["RAY_TLS_CA_CERT"] + + +class ResourceKillerActor: + """Abstract base class used to implement resource killers for chaos testing. + + Subclasses should implement _find_resource_to_kill, which should find a resource + to kill. This method should return the args to _kill_resource, which is another + abstract method that should kill the resource and add it to the `killed` set. + """ + + def __init__( + self, + head_node_id, + kill_interval_s: float = 60, + kill_delay_s: float = 0, + max_to_kill: int = 2, + batch_size_to_kill: int = 1, + kill_filter_fn: Optional[Callable] = None, + ): + self.kill_interval_s = kill_interval_s + self.kill_delay_s = kill_delay_s + self.is_running = False + self.head_node_id = head_node_id + self.killed = set() + self.done = get_or_create_event_loop().create_future() + self.max_to_kill = max_to_kill + self.batch_size_to_kill = batch_size_to_kill + self.kill_filter_fn = kill_filter_fn + self.kill_immediately_after_found = False + # -- logger. -- + logging.basicConfig(level=logging.INFO) + + def ready(self): + pass + + async def run(self): + self.is_running = True + + time.sleep(self.kill_delay_s) + + while self.is_running: + to_kills = await self._find_resources_to_kill() + + if not self.is_running: + break + + if self.kill_immediately_after_found: + sleep_interval = 0 + else: + sleep_interval = random.random() * self.kill_interval_s + time.sleep(sleep_interval) + + for to_kill in to_kills: + self._kill_resource(*to_kill) + if len(self.killed) >= self.max_to_kill: + break + await asyncio.sleep(self.kill_interval_s - sleep_interval) + + self.done.set_result(True) + await self.stop_run() + + async def _find_resources_to_kill(self): + raise NotImplementedError + + def _kill_resource(self, *args): + raise NotImplementedError + + async def stop_run(self): + was_running = self.is_running + if was_running: + self._cleanup() + + self.is_running = False + return was_running + + async def get_total_killed(self): + """Get the total number of killed resources""" + await self.done + return self.killed + + def _cleanup(self): + """Cleanup any resources created by the killer. + + Overriding this method is optional. + """ + pass + + +class NodeKillerBase(ResourceKillerActor): + async def _find_resources_to_kill(self): + nodes_to_kill = [] + while not nodes_to_kill and self.is_running: + worker_nodes = [ + node + for node in ray.nodes() + if node["Alive"] + and (node["NodeID"] != self.head_node_id) + and (node["NodeID"] not in self.killed) + ] + if self.kill_filter_fn: + candidates = list(filter(self.kill_filter_fn(), worker_nodes)) + else: + candidates = worker_nodes + + # Ensure at least one worker node remains alive. + if len(worker_nodes) < self.batch_size_to_kill + 1: + # Give the cluster some time to start. + await asyncio.sleep(1) + continue + + # Collect nodes to kill, limited by batch size. + for candidate in candidates[: self.batch_size_to_kill]: + nodes_to_kill.append( + ( + candidate["NodeID"], + candidate["NodeManagerAddress"], + candidate["NodeManagerPort"], + ) + ) + + return nodes_to_kill + + +@ray.remote(num_cpus=0) +class RayletKiller(NodeKillerBase): + def _kill_resource(self, node_id, node_to_kill_ip, node_to_kill_port): + if node_to_kill_port is not None: + try: + self._kill_raylet(node_to_kill_ip, node_to_kill_port, graceful=False) + except Exception: + pass + logging.info( + f"Killed node {node_id} at address: " + f"{node_to_kill_ip}, port: {node_to_kill_port}" + ) + self.killed.add(node_id) + + def _kill_raylet(self, ip, port, graceful=False): + import grpc + from grpc._channel import _InactiveRpcError + + from ray.core.generated import node_manager_pb2_grpc + + raylet_address = f"{ip}:{port}" + channel = grpc.insecure_channel(raylet_address) + stub = node_manager_pb2_grpc.NodeManagerServiceStub(channel) + try: + stub.ShutdownRaylet( + node_manager_pb2.ShutdownRayletRequest(graceful=graceful) + ) + except _InactiveRpcError: + assert not graceful + + +@ray.remote(num_cpus=0) +class EC2InstanceTerminator(NodeKillerBase): + def _kill_resource(self, node_id, node_to_kill_ip, _): + if node_to_kill_ip is not None: + try: + _terminate_ec2_instance(node_to_kill_ip) + except Exception: + pass + logging.info(f"Terminated instance, {node_id=}, address={node_to_kill_ip}") + self.killed.add(node_id) + + +@ray.remote(num_cpus=0) +class EC2InstanceTerminatorWithGracePeriod(NodeKillerBase): + def __init__(self, *args, grace_period_s: int = 30, **kwargs): + super().__init__(*args, **kwargs) + + self._grace_period_s = grace_period_s + self._kill_threads: Set[threading.Thread] = set() + + def _kill_resource(self, node_id, node_to_kill_ip, _): + assert node_id not in self.killed + + # Clean up any completed threads. + for thread in self._kill_threads.copy(): + if not thread.is_alive(): + thread.join() + self._kill_threads.remove(thread) + + def _kill_node_with_grace_period(node_id, node_to_kill_ip): + self._drain_node(node_id) + time.sleep(self._grace_period_s) + _terminate_ec2_instance(node_to_kill_ip) + + logger.info(f"Starting killing thread {node_id=}, {node_to_kill_ip=}") + thread = threading.Thread( + target=_kill_node_with_grace_period, + args=(node_id, node_to_kill_ip), + daemon=True, + ) + thread.start() + self._kill_threads.add(thread) + self.killed.add(node_id) + + def _drain_node(self, node_id: str) -> None: + # We need to lazily import this object. Otherwise, Ray can't serialize the + # class. + from ray.core.generated import autoscaler_pb2 + + assert ray.NodeID.from_hex(node_id) != ray.NodeID.nil() + + logging.info(f"Draining node {node_id=}") + address = services.canonicalize_bootstrap_address_or_die(addr="auto") + gcs_client = ray._raylet.GcsClient(address=address) + deadline_timestamp_ms = (time.time_ns() // 1e6) + (self._grace_period_s * 1e3) + + try: + is_accepted, _ = gcs_client.drain_node( + node_id, + autoscaler_pb2.DrainNodeReason.Value("DRAIN_NODE_REASON_PREEMPTION"), + "", + deadline_timestamp_ms, + ) + except ray.exceptions.RayError as e: + logger.error(f"Failed to drain node {node_id=}") + raise e + + assert is_accepted, "Drain node request was rejected" + + def _cleanup(self): + for thread in self._kill_threads.copy(): + thread.join() + self._kill_threads.remove(thread) + + assert not self._kill_threads + + +@ray.remote(num_cpus=0) +class WorkerKillerActor(ResourceKillerActor): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # Kill worker immediately so that the task does + # not finish successfully on its own. + self.kill_immediately_after_found = True + + from ray.util.state.api import StateApiClient + from ray.util.state.common import ListApiOptions + + self.client = StateApiClient() + self.task_options = ListApiOptions( + filters=[ + ("state", "=", "RUNNING"), + ("name", "!=", "WorkerKillActor.run"), + ] + ) + + async def _find_resources_to_kill(self): + from ray.util.state.common import StateResource + + process_to_kill_task_id = None + process_to_kill_pid = None + process_to_kill_node_id = None + while process_to_kill_pid is None and self.is_running: + tasks = self.client.list( + StateResource.TASKS, + options=self.task_options, + raise_on_missing_output=False, + ) + if self.kill_filter_fn is not None: + tasks = list(filter(self.kill_filter_fn(), tasks)) + + for task in tasks: + if task.worker_id is not None and task.node_id is not None: + process_to_kill_task_id = task.task_id + process_to_kill_pid = task.worker_pid + process_to_kill_node_id = task.node_id + break + + # Give the cluster some time to start. + await asyncio.sleep(0.1) + + return [(process_to_kill_task_id, process_to_kill_pid, process_to_kill_node_id)] + + def _kill_resource( + self, process_to_kill_task_id, process_to_kill_pid, process_to_kill_node_id + ): + if process_to_kill_pid is not None: + + @ray.remote + def kill_process(pid): + import psutil + + proc = psutil.Process(pid) + proc.kill() + + scheduling_strategy = ( + ray.util.scheduling_strategies.NodeAffinitySchedulingStrategy( + node_id=process_to_kill_node_id, + soft=False, + ) + ) + kill_process.options(scheduling_strategy=scheduling_strategy).remote( + process_to_kill_pid + ) + logging.info( + f"Killing pid {process_to_kill_pid} on node {process_to_kill_node_id}" + ) + # Store both task_id and pid because retried tasks have same task_id. + self.killed.add((process_to_kill_task_id, process_to_kill_pid)) + + +def get_and_run_resource_killer( + resource_killer_cls, + kill_interval_s, + namespace=None, + lifetime=None, + no_start=False, + max_to_kill=2, + batch_size_to_kill=1, + kill_delay_s=0, + kill_filter_fn=None, +): + assert ray.is_initialized(), "The API is only available when Ray is initialized." + + head_node_id = ray.get_runtime_context().get_node_id() + # Schedule the actor on the current node. + resource_killer = resource_killer_cls.options( + scheduling_strategy=NodeAffinitySchedulingStrategy( + node_id=head_node_id, soft=False + ), + namespace=namespace, + name="ResourceKiller", + lifetime=lifetime, + ).remote( + head_node_id, + kill_interval_s=kill_interval_s, + kill_delay_s=kill_delay_s, + max_to_kill=max_to_kill, + batch_size_to_kill=batch_size_to_kill, + kill_filter_fn=kill_filter_fn, + ) + print("Waiting for ResourceKiller to be ready...") + ray.get(resource_killer.ready.remote()) + print("ResourceKiller is ready now.") + if not no_start: + resource_killer.run.remote() + return resource_killer + + +def get_actor_node_id(actor_handle: "ray.actor.ActorHandle") -> str: + return ray.get( + actor_handle.__ray_call__.remote( + lambda self: ray.get_runtime_context().get_node_id() + ) + ) + + +@contextmanager +def chdir(d: str): + old_dir = os.getcwd() + os.chdir(d) + try: + yield + finally: + os.chdir(old_dir) + + +def test_get_directory_size_bytes(): + with tempfile.TemporaryDirectory() as tmp_dir, chdir(tmp_dir): + assert ray._private.utils.get_directory_size_bytes(tmp_dir) == 0 + with open("test_file", "wb") as f: + f.write(os.urandom(100)) + assert ray._private.utils.get_directory_size_bytes(tmp_dir) == 100 + with open("test_file_2", "wb") as f: + f.write(os.urandom(50)) + assert ray._private.utils.get_directory_size_bytes(tmp_dir) == 150 + os.mkdir("subdir") + with open("subdir/subdir_file", "wb") as f: + f.write(os.urandom(2)) + assert ray._private.utils.get_directory_size_bytes(tmp_dir) == 152 + + +def check_local_files_gced(cluster): + for node in cluster.list_all_nodes(): + for subdir in ["conda", "pip", "working_dir_files", "py_modules_files"]: + all_files = os.listdir( + os.path.join(node.get_runtime_env_dir_path(), subdir) + ) + # Check that there are no files remaining except for .lock files + # and generated requirements.txt files. + # Note: On Windows the top folder is not deleted as it is in use. + # TODO(architkulkarni): these files should get cleaned up too! + items = list(filter(lambda f: not f.endswith((".lock", ".txt")), all_files)) + if len(items) > 0: + print(f"runtime_env files not GC'd from subdir '{subdir}': {items}") + return False + return True + + +def generate_runtime_env_dict(field, spec_format, tmp_path, pip_list=None): + if pip_list is None: + pip_list = ["pip-install-test==0.5"] + if field == "conda": + conda_dict = {"dependencies": ["pip", {"pip": pip_list}]} + if spec_format == "file": + conda_file = tmp_path / f"environment-{hash(str(pip_list))}.yml" + conda_file.write_text(yaml.dump(conda_dict)) + conda = str(conda_file) + elif spec_format == "python_object": + conda = conda_dict + runtime_env = {"conda": conda} + elif field == "pip": + if spec_format == "file": + pip_file = tmp_path / f"requirements-{hash(str(pip_list))}.txt" + pip_file.write_text("\n".join(pip_list)) + pip = str(pip_file) + elif spec_format == "python_object": + pip = pip_list + runtime_env = {"pip": pip} + return runtime_env + + +def check_spilled_mb(address, spilled=None, restored=None, fallback=None): + def ok(): + s = memory_summary(address=address["address"], stats_only=True) + print(s) + if restored: + if "Restored {} MiB".format(restored) not in s: + return False + else: + if "Restored" in s: + return False + if spilled: + if not isinstance(spilled, list): + spilled_lst = [spilled] + else: + spilled_lst = spilled + found = False + for n in spilled_lst: + if "Spilled {} MiB".format(n) in s: + found = True + if not found: + return False + else: + if "Spilled" in s: + return False + if fallback: + if "Plasma filesystem mmap usage: {} MiB".format(fallback) not in s: + return False + else: + if "Plasma filesystem mmap usage:" in s: + return False + return True + + wait_for_condition(ok, timeout=3, retry_interval_ms=1000) + + +def no_resource_leaks_excluding_node_resources(): + cluster_resources = ray.cluster_resources() + available_resources = ray.available_resources() + for r in ray.cluster_resources(): + if "node" in r: + del cluster_resources[r] + del available_resources[r] + + return cluster_resources == available_resources + + +def job_hook(**kwargs): + """Function called by reflection by test_cli_integration.""" + cmd = " ".join(kwargs["entrypoint"]) + print(f"hook intercepted: {cmd}") + sys.exit(0) + + +def find_free_port() -> int: + sock = socket.socket() + sock.bind(("", 0)) + port = sock.getsockname()[1] + sock.close() + return port + + +def wandb_setup_api_key_hook(): + """ + Example external hook to set up W&B API key in + WandbIntegrationTest.testWandbLoggerConfig + """ + return "abcd" + + +# Get node stats from node manager. +def get_node_stats(raylet, num_retry=5, timeout=2): + import grpc + + from ray.core.generated import node_manager_pb2_grpc + + raylet_address = f'{raylet["NodeManagerAddress"]}:{raylet["NodeManagerPort"]}' + channel = ray._private.utils.init_grpc_channel(raylet_address) + stub = node_manager_pb2_grpc.NodeManagerServiceStub(channel) + for _ in range(num_retry): + try: + reply = stub.GetNodeStats( + node_manager_pb2.GetNodeStatsRequest(), timeout=timeout + ) + break + except grpc.RpcError: + continue + assert reply is not None + return reply + + +# Gets resource usage assuming gcs is local. +def get_resource_usage(gcs_address, timeout=10): + from ray.core.generated import gcs_service_pb2_grpc + + if not gcs_address: + gcs_address = ray.worker._global_node.gcs_address + + gcs_channel = ray._private.utils.init_grpc_channel( + gcs_address, ray_constants.GLOBAL_GRPC_OPTIONS, asynchronous=False + ) + + gcs_node_resources_stub = gcs_service_pb2_grpc.NodeResourceInfoGcsServiceStub( + gcs_channel + ) + + request = gcs_service_pb2.GetAllResourceUsageRequest() + response = gcs_node_resources_stub.GetAllResourceUsage(request, timeout=timeout) + resources_batch_data = response.resource_usage_data + + return resources_batch_data + + +# Gets the load metrics report assuming gcs is local. +def get_load_metrics_report(webui_url): + webui_url = format_web_url(webui_url) + response = requests.get(f"{webui_url}/api/cluster_status") + response.raise_for_status() + return response.json()["data"]["clusterStatus"]["loadMetricsReport"] + + +# Send a RPC to the raylet to have it self-destruct its process. +def kill_raylet(raylet, graceful=False): + import grpc + from grpc._channel import _InactiveRpcError + + from ray.core.generated import node_manager_pb2_grpc + + raylet_address = f'{raylet["NodeManagerAddress"]}:{raylet["NodeManagerPort"]}' + channel = grpc.insecure_channel(raylet_address) + stub = node_manager_pb2_grpc.NodeManagerServiceStub(channel) + try: + stub.ShutdownRaylet(node_manager_pb2.ShutdownRayletRequest(graceful=graceful)) + except _InactiveRpcError: + assert not graceful + + +def get_gcs_memory_used(): + import psutil + + m = { + proc.info["name"]: proc.info["memory_info"].rss + for proc in psutil.process_iter(["status", "name", "memory_info"]) + if ( + proc.info["status"] not in (psutil.STATUS_ZOMBIE, psutil.STATUS_DEAD) + and proc.info["name"] in ("gcs_server", "redis-server") + ) + } + assert "gcs_server" in m + return sum(m.values()) + + +def safe_write_to_results_json( + result: dict, + default_file_name: str = "/tmp/release_test_output.json", + env_var: Optional[str] = "TEST_OUTPUT_JSON", +): + """ + Safe (atomic) write to file to guard against malforming the json + if the job gets interrupted in the middle of writing. + """ + test_output_json = os.environ.get(env_var, default_file_name) + test_output_json_tmp = f"{test_output_json}.tmp.{str(uuid.uuid4())}" + with open(test_output_json_tmp, "wt") as f: + json.dump(result, f) + f.flush() + os.replace(test_output_json_tmp, test_output_json) + logger.info(f"Wrote results to {test_output_json}") + logger.info(json.dumps(result)) + + +def get_current_unused_port(): + """ + Returns a port number that is not currently in use. + + This is useful for testing when we need to bind to a port but don't + care which one. + + Returns: + A port number that is not currently in use. (Note that this port + might become used by the time you try to bind to it.) + """ + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + + # Bind the socket to a local address with a random port number + sock.bind(("localhost", 0)) + + port = sock.getsockname()[1] + sock.close() + return port + + +# Global counter to test different return values +# for external_ray_cluster_activity_hook1. +ray_cluster_activity_hook_counter = 0 +ray_cluster_activity_hook_5_counter = 0 + + +def external_ray_cluster_activity_hook1(): + """ + Example external hook for test_component_activities_hook. + Returns valid response and increments counter in `reason` + field on each call. + """ + global ray_cluster_activity_hook_counter + ray_cluster_activity_hook_counter += 1 + + from pydantic import BaseModel, Extra + + class TestRayActivityResponse(BaseModel, extra=Extra.allow): + """ + Redefinition of dashboard.modules.api.api_head.RayActivityResponse + used in test_component_activities_hook to mimic typical + usage of redefining or extending response type. + """ + + is_active: str + reason: Optional[str] = None + timestamp: float + + return { + "test_component1": TestRayActivityResponse( + is_active="ACTIVE", + reason=f"Counter: {ray_cluster_activity_hook_counter}", + timestamp=datetime.now().timestamp(), + ) + } + + +def external_ray_cluster_activity_hook2(): + """ + Example external hook for test_component_activities_hook. + Returns invalid output because the value of `test_component2` + should be of type RayActivityResponse. + """ + return {"test_component2": "bad_output"} + + +def external_ray_cluster_activity_hook3(): + """ + Example external hook for test_component_activities_hook. + Returns invalid output because return type is not + Dict[str, RayActivityResponse] + """ + return "bad_output" + + +def external_ray_cluster_activity_hook4(): + """ + Example external hook for test_component_activities_hook. + Errors during execution. + """ + raise Exception("Error in external cluster activity hook") + + +def external_ray_cluster_activity_hook5(): + """ + Example external hook for test_component_activities_hook. + Returns valid response and increments counter in `reason` + field on each call. + """ + global ray_cluster_activity_hook_5_counter + ray_cluster_activity_hook_5_counter += 1 + return { + "test_component5": { + "is_active": "ACTIVE", + "reason": f"Counter: {ray_cluster_activity_hook_5_counter}", + "timestamp": datetime.now().timestamp(), + } + } + + +# TODO(rickyx): We could remove this once we unify the autoscaler v1 and v2 +# code path for ray status +def reset_autoscaler_v2_enabled_cache(): + import ray.autoscaler.v2.utils as u + + u.cached_is_autoscaler_v2 = None + + +def _terminate_ec2_instance(ip): + logging.info(f"Terminating instance, {ip=}") + # This command uses IMDSv2 to get the host instance id and region. + # After that it terminates itself using aws cli. + multi_line_command = ( + 'TOKEN=$(curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600");' # noqa: E501 + 'instanceId=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/instance-id/);' # noqa: E501 + 'region=$(curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/placement/region);' # noqa: E501 + "aws ec2 terminate-instances --region $region --instance-ids $instanceId" # noqa: E501 + ) + # This is a feature on Anyscale platform that enables + # easy ssh access to worker nodes. + ssh_command = f"ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -p 2222 ray@{ip} '{multi_line_command}'" # noqa: E501 + + try: + subprocess.run( + ssh_command, shell=True, capture_output=True, text=True, check=True + ) + except subprocess.CalledProcessError as e: + print("Exit code:", e.returncode) + print("Stderr:", e.stderr) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/thirdparty/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/thirdparty/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/thirdparty/pynvml/__pycache__/pynvml.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/thirdparty/pynvml/__pycache__/pynvml.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e93b721c725b8a070dd72a0458d136d8d339fcde --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/thirdparty/pynvml/__pycache__/pynvml.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:feda719969c88f875bd51eedbd9620c93f1a167ed5964d2c812c6a3f8a9604d8 +size 147500 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/tls_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/tls_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..22b6f050ee604b977da184917e7b685145f69315 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/tls_utils.py @@ -0,0 +1,99 @@ +import datetime +import os +import socket + + +def generate_self_signed_tls_certs(): + """Create self-signed key/cert pair for testing. + + This method requires the library ``cryptography`` be installed. + """ + try: + from cryptography import x509 + from cryptography.hazmat.backends import default_backend + from cryptography.hazmat.primitives import hashes, serialization + from cryptography.hazmat.primitives.asymmetric import rsa + from cryptography.x509.oid import NameOID + except ImportError: + raise ImportError( + "Using `Security.temporary` requires `cryptography`, please " + "install it using either pip or conda" + ) + key = rsa.generate_private_key( + public_exponent=65537, key_size=2048, backend=default_backend() + ) + key_contents = key.private_bytes( + encoding=serialization.Encoding.PEM, + format=serialization.PrivateFormat.PKCS8, + encryption_algorithm=serialization.NoEncryption(), + ).decode() + + ray_interal = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "ray-internal")]) + # This is the same logic used by the GCS server to acquire a + # private/interal IP address to listen on. If we just use localhost + + # 127.0.0.1 then we won't be able to connect to the GCS and will get + # an error like "No match found for server name: 192.168.X.Y" + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect(("8.8.8.8", 80)) + private_ip_address = s.getsockname()[0] + s.close() + altnames = x509.SubjectAlternativeName( + [ + x509.DNSName( + socket.gethostbyname(socket.gethostname()) + ), # Probably 127.0.0.1 + x509.DNSName("127.0.0.1"), + x509.DNSName(private_ip_address), # 192.168.*.* + x509.DNSName("localhost"), + ] + ) + now = datetime.datetime.utcnow() + cert = ( + x509.CertificateBuilder() + .subject_name(ray_interal) + .issuer_name(ray_interal) + .add_extension(altnames, critical=False) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now) + .not_valid_after(now + datetime.timedelta(days=365)) + .sign(key, hashes.SHA256(), default_backend()) + ) + + cert_contents = cert.public_bytes(serialization.Encoding.PEM).decode() + + return cert_contents, key_contents + + +def add_port_to_grpc_server(server, address): + import grpc + + if os.environ.get("RAY_USE_TLS", "0").lower() in ("1", "true"): + server_cert_chain, private_key, ca_cert = load_certs_from_env() + credentials = grpc.ssl_server_credentials( + [(private_key, server_cert_chain)], + root_certificates=ca_cert, + require_client_auth=ca_cert is not None, + ) + return server.add_secure_port(address, credentials) + else: + return server.add_insecure_port(address) + + +def load_certs_from_env(): + tls_env_vars = ["RAY_TLS_SERVER_CERT", "RAY_TLS_SERVER_KEY", "RAY_TLS_CA_CERT"] + if any(v not in os.environ for v in tls_env_vars): + raise RuntimeError( + "If the environment variable RAY_USE_TLS is set to true " + "then RAY_TLS_SERVER_CERT, RAY_TLS_SERVER_KEY and " + "RAY_TLS_CA_CERT must also be set." + ) + + with open(os.environ["RAY_TLS_SERVER_CERT"], "rb") as f: + server_cert_chain = f.read() + with open(os.environ["RAY_TLS_SERVER_KEY"], "rb") as f: + private_key = f.read() + with open(os.environ["RAY_TLS_CA_CERT"], "rb") as f: + ca_cert = f.read() + + return server_cert_chain, private_key, ca_cert diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/usage_constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/usage_constants.py new file mode 100644 index 0000000000000000000000000000000000000000..2b5b97ad175e334aa963e2f02629329830c57ff8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/usage_constants.py @@ -0,0 +1,63 @@ +SCHEMA_VERSION = "0.1" + +# The key to store / obtain cluster metadata. +CLUSTER_METADATA_KEY = b"CLUSTER_METADATA" + +# The name of a json file where usage stats will be written. +USAGE_STATS_FILE = "usage_stats.json" + +USAGE_STATS_ENABLED_ENV_VAR = "RAY_USAGE_STATS_ENABLED" + +USAGE_STATS_SOURCE_ENV_VAR = "RAY_USAGE_STATS_SOURCE" + +USAGE_STATS_SOURCE_OSS = "OSS" + +USAGE_STATS_ENABLED_FOR_CLI_MESSAGE = ( + "Usage stats collection is enabled. To disable this, add `--disable-usage-stats` " + "to the command that starts the cluster, or run the following command:" + " `ray disable-usage-stats` before starting the cluster. " + "See https://docs.ray.io/en/master/cluster/usage-stats.html for more details." +) + +USAGE_STATS_ENABLED_FOR_RAY_INIT_MESSAGE = ( + "Usage stats collection is enabled. To disable this, run the following command:" + " `ray disable-usage-stats` before starting Ray. " + "See https://docs.ray.io/en/master/cluster/usage-stats.html for more details." +) + +USAGE_STATS_DISABLED_MESSAGE = "Usage stats collection is disabled." + +USAGE_STATS_ENABLED_BY_DEFAULT_FOR_CLI_MESSAGE = ( + "Usage stats collection is enabled by default without user confirmation " + "because this terminal is detected to be non-interactive. " + "To disable this, add `--disable-usage-stats` to the command that starts " + "the cluster, or run the following command:" + " `ray disable-usage-stats` before starting the cluster. " + "See https://docs.ray.io/en/master/cluster/usage-stats.html for more details." +) + +USAGE_STATS_ENABLED_BY_DEFAULT_FOR_RAY_INIT_MESSAGE = ( + "Usage stats collection is enabled by default for nightly wheels. " + "To disable this, run the following command:" + " `ray disable-usage-stats` before starting Ray. " + "See https://docs.ray.io/en/master/cluster/usage-stats.html for more details." +) + +USAGE_STATS_CONFIRMATION_MESSAGE = ( + "Enable usage stats collection? " + "This prompt will auto-proceed in 10 seconds to avoid blocking cluster startup." +) + +LIBRARY_USAGE_SET_NAME = "library_usage_" + +HARDWARE_USAGE_SET_NAME = "hardware_usage_" + +# Keep in-sync with the same constants defined in usage_stats_client.h +EXTRA_USAGE_TAG_PREFIX = "extra_usage_tag_" +USAGE_STATS_NAMESPACE = "usage_stats" + +KUBERNETES_SERVICE_HOST_ENV = "KUBERNETES_SERVICE_HOST" +KUBERAY_ENV = "RAY_USAGE_STATS_KUBERAY_IN_USE" + +PROVIDER_KUBERNETES_GENERIC = "kubernetes" +PROVIDER_KUBERAY = "kuberay" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/usage_lib.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/usage_lib.py new file mode 100644 index 0000000000000000000000000000000000000000..f548e5693417fc065c692303efaab311e4290f7e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/usage/usage_lib.py @@ -0,0 +1,1004 @@ +"""This is the module that is in charge of Ray usage report (telemetry) APIs. + +NOTE: Ray's usage report is currently "on by default". + One could opt-out, see details at https://docs.ray.io/en/master/cluster/usage-stats.html. # noqa + +Ray usage report follows the specification from +https://docs.ray.io/en/master/cluster/usage-stats.html#usage-stats-collection # noqa + +# Module + +The module consists of 2 parts. + +## Public API +It contains public APIs to obtain usage report information. +APIs will be added before the usage report becomes opt-in by default. + +## Internal APIs for usage processing/report +The telemetry report consists of 5 components. This module is in charge of the top 2 layers. + +Report -> usage_lib +--------------------- +Usage data processing -> usage_lib +--------------------- +Data storage -> Ray API server +--------------------- +Aggregation -> Ray API server (currently a dashboard server) +--------------------- +Usage data collection -> Various components (Ray agent, GCS, etc.) + usage_lib (cluster metadata). + +Usage report is currently "off by default". You can enable the report by setting an environment variable +RAY_USAGE_STATS_ENABLED=1. For example, `RAY_USAGE_STATS_ENABLED=1 ray start --head`. +Or `RAY_USAGE_STATS_ENABLED=1 python [drivers with ray.init()]`. + +"Ray API server (currently a dashboard server)" reports the usage data to https://usage-stats.ray.io/. + +Data is reported every hour by default. + +Note that it is also possible to configure the interval using the environment variable, +`RAY_USAGE_STATS_REPORT_INTERVAL_S`. + +To see collected/reported data, see `usage_stats.json` inside a temp +folder (e.g., /tmp/ray/session_[id]/*). +""" +import json +import logging +import os +import platform +import sys +import threading +import time +from dataclasses import asdict, dataclass +from enum import Enum, auto +from pathlib import Path +from typing import Dict, List, Optional, Set + +import requests +import yaml + +import ray +import ray._private.ray_constants as ray_constants +import ray._private.usage.usage_constants as usage_constant +from ray._raylet import GcsClient +from ray.core.generated import gcs_pb2, usage_pb2 +from ray.experimental.internal_kv import ( + _internal_kv_initialized, + _internal_kv_put, +) + +logger = logging.getLogger(__name__) +TagKey = usage_pb2.TagKey + +################# +# Internal APIs # +################# + + +@dataclass(init=True) +class ClusterConfigToReport: + cloud_provider: Optional[str] = None + min_workers: Optional[int] = None + max_workers: Optional[int] = None + head_node_instance_type: Optional[str] = None + worker_node_instance_types: Optional[List[str]] = None + + +@dataclass(init=True) +class ClusterStatusToReport: + total_num_cpus: Optional[int] = None + total_num_gpus: Optional[int] = None + total_memory_gb: Optional[float] = None + total_object_store_memory_gb: Optional[float] = None + + +@dataclass(init=True) +class UsageStatsToReport: + """Usage stats to report""" + + #: The schema version of the report. + schema_version: str + #: The source of the data (i.e. OSS). + source: str + #: When the data is collected and reported. + collect_timestamp_ms: int + #: The total number of successful reports for the lifetime of the cluster. + total_success: Optional[int] = None + #: The total number of failed reports for the lifetime of the cluster. + total_failed: Optional[int] = None + #: The sequence number of the report. + seq_number: Optional[int] = None + #: The Ray version in use. + ray_version: Optional[str] = None + #: The Python version in use. + python_version: Optional[str] = None + #: A random id of the cluster session. + session_id: Optional[str] = None + #: The git commit hash of Ray (i.e. ray.__commit__). + git_commit: Optional[str] = None + #: The operating system in use. + os: Optional[str] = None + #: When the cluster is started. + session_start_timestamp_ms: Optional[int] = None + #: The cloud provider found in the cluster.yaml file (e.g., aws). + cloud_provider: Optional[str] = None + #: The min_workers found in the cluster.yaml file. + min_workers: Optional[int] = None + #: The max_workers found in the cluster.yaml file. + max_workers: Optional[int] = None + #: The head node instance type found in the cluster.yaml file (e.g., i3.8xlarge). + head_node_instance_type: Optional[str] = None + #: The worker node instance types found in the cluster.yaml file (e.g., i3.8xlarge). + worker_node_instance_types: Optional[List[str]] = None + #: The total num of cpus in the cluster. + total_num_cpus: Optional[int] = None + #: The total num of gpus in the cluster. + total_num_gpus: Optional[int] = None + #: The total size of memory in the cluster. + total_memory_gb: Optional[float] = None + #: The total size of object store memory in the cluster. + total_object_store_memory_gb: Optional[float] = None + #: The Ray libraries that are used (e.g., rllib). + library_usages: Optional[List[str]] = None + #: The extra tags to report when specified by an + # environment variable RAY_USAGE_STATS_EXTRA_TAGS + extra_usage_tags: Optional[Dict[str, str]] = None + #: The number of alive nodes when the report is generated. + total_num_nodes: Optional[int] = None + #: The total number of running jobs excluding internal ones + # when the report is generated. + total_num_running_jobs: Optional[int] = None + #: The libc version in the OS. + libc_version: Optional[str] = None + #: The hardwares that are used (e.g. Intel Xeon). + hardware_usages: Optional[List[str]] = None + + +@dataclass(init=True) +class UsageStatsToWrite: + """Usage stats to write to `USAGE_STATS_FILE` + + We are writing extra metadata such as the status of report + to this file. + """ + + usage_stats: UsageStatsToReport + # Whether or not the last report succeeded. + success: bool + # The error message of the last report if it happens. + error: str + + +class UsageStatsEnabledness(Enum): + ENABLED_EXPLICITLY = auto() + DISABLED_EXPLICITLY = auto() + ENABLED_BY_DEFAULT = auto() + + +_recorded_library_usages = set() +_recorded_library_usages_lock = threading.Lock() +_recorded_extra_usage_tags = dict() +_recorded_extra_usage_tags_lock = threading.Lock() + + +def _add_to_usage_set(set_name: str, value: str): + assert _internal_kv_initialized() + try: + _internal_kv_put( + f"{set_name}{value}".encode(), + b"", + namespace=usage_constant.USAGE_STATS_NAMESPACE.encode(), + ) + except Exception as e: + logger.debug(f"Failed to add {value} to usage set {set_name}, {e}") + + +def _get_usage_set(gcs_client, set_name: str) -> Set[str]: + try: + result = set() + usages = gcs_client.internal_kv_keys( + set_name.encode(), + namespace=usage_constant.USAGE_STATS_NAMESPACE.encode(), + ) + for usage in usages: + usage = usage.decode("utf-8") + result.add(usage[len(set_name) :]) + + return result + except Exception as e: + logger.debug(f"Failed to get usage set {set_name}, {e}") + return set() + + +def _put_library_usage(library_usage: str): + _add_to_usage_set(usage_constant.LIBRARY_USAGE_SET_NAME, library_usage) + + +def _put_hardware_usage(hardware_usage: str): + _add_to_usage_set(usage_constant.HARDWARE_USAGE_SET_NAME, hardware_usage) + + +def record_extra_usage_tag( + key: TagKey, value: str, gcs_client: Optional[GcsClient] = None +): + """Record extra kv usage tag. + + If the key already exists, the value will be overwritten. + + To record an extra tag, first add the key to the TagKey enum and + then call this function. + It will make a synchronous call to the internal kv store if the tag is updated. + + Args: + key: The key of the tag. + value: The value of the tag. + gcs_client: The GCS client to perform KV operation PUT. Defaults to None. + When None, it will try to get the global client from the internal_kv. + """ + key = TagKey.Name(key).lower() + with _recorded_extra_usage_tags_lock: + if _recorded_extra_usage_tags.get(key) == value: + return + _recorded_extra_usage_tags[key] = value + + if not _internal_kv_initialized() and gcs_client is None: + # This happens if the record is before ray.init and + # no GCS client is used for recording explicitly. + return + + _put_extra_usage_tag(key, value, gcs_client) + + +def _put_extra_usage_tag(key: str, value: str, gcs_client: Optional[GcsClient] = None): + try: + key = f"{usage_constant.EXTRA_USAGE_TAG_PREFIX}{key}".encode() + val = value.encode() + namespace = usage_constant.USAGE_STATS_NAMESPACE.encode() + if gcs_client is not None: + # Use the GCS client. + gcs_client.internal_kv_put(key, val, namespace=namespace) + else: + # Use internal kv. + assert _internal_kv_initialized() + _internal_kv_put(key, val, namespace=namespace) + except Exception as e: + logger.debug(f"Failed to put extra usage tag, {e}") + + +def record_hardware_usage(hardware_usage: str): + """Record hardware usage (e.g. which CPU model is used)""" + assert _internal_kv_initialized() + _put_hardware_usage(hardware_usage) + + +def record_library_usage(library_usage: str): + """Record library usage (e.g. which library is used)""" + with _recorded_library_usages_lock: + if library_usage in _recorded_library_usages: + return + _recorded_library_usages.add(library_usage) + + if not _internal_kv_initialized(): + # This happens if the library is imported before ray.init + return + + # Only report lib usage for driver / ray client / workers. Otherwise, + # it can be reported if the library is imported from + # e.g., API server. + if ( + ray._private.worker.global_worker.mode == ray.SCRIPT_MODE + or ray._private.worker.global_worker.mode == ray.WORKER_MODE + or ray.util.client.ray.is_connected() + ): + _put_library_usage(library_usage) + + +def _put_pre_init_library_usages(): + assert _internal_kv_initialized() + # NOTE: When the lib is imported from a worker, ray should + # always be initialized, so there's no need to register the + # pre init hook. + if not ( + ray._private.worker.global_worker.mode == ray.SCRIPT_MODE + or ray.util.client.ray.is_connected() + ): + return + + for library_usage in _recorded_library_usages: + _put_library_usage(library_usage) + + +def _put_pre_init_extra_usage_tags(): + assert _internal_kv_initialized() + for k, v in _recorded_extra_usage_tags.items(): + _put_extra_usage_tag(k, v) + + +def put_pre_init_usage_stats(): + _put_pre_init_library_usages() + _put_pre_init_extra_usage_tags() + + +def reset_global_state(): + global _recorded_library_usages, _recorded_extra_usage_tags + + with _recorded_library_usages_lock: + _recorded_library_usages = set() + with _recorded_extra_usage_tags_lock: + _recorded_extra_usage_tags = dict() + + +ray._private.worker._post_init_hooks.append(put_pre_init_usage_stats) + + +def _usage_stats_report_url(): + # The usage collection server URL. + # The environment variable is testing-purpose only. + return os.getenv("RAY_USAGE_STATS_REPORT_URL", "https://usage-stats.ray.io/") + + +def _usage_stats_report_interval_s(): + return int(os.getenv("RAY_USAGE_STATS_REPORT_INTERVAL_S", 3600)) + + +def _usage_stats_config_path(): + return os.getenv( + "RAY_USAGE_STATS_CONFIG_PATH", os.path.expanduser("~/.ray/config.json") + ) + + +def _usage_stats_enabledness() -> UsageStatsEnabledness: + # Env var has higher priority than config file. + usage_stats_enabled_env_var = os.getenv(usage_constant.USAGE_STATS_ENABLED_ENV_VAR) + if usage_stats_enabled_env_var == "0": + return UsageStatsEnabledness.DISABLED_EXPLICITLY + elif usage_stats_enabled_env_var == "1": + return UsageStatsEnabledness.ENABLED_EXPLICITLY + elif usage_stats_enabled_env_var is not None: + raise ValueError( + f"Valid value for {usage_constant.USAGE_STATS_ENABLED_ENV_VAR} " + f"env var is 0 or 1, but got {usage_stats_enabled_env_var}" + ) + + usage_stats_enabled_config_var = None + try: + with open(_usage_stats_config_path()) as f: + config = json.load(f) + usage_stats_enabled_config_var = config.get("usage_stats") + except FileNotFoundError: + pass + except Exception as e: + logger.debug(f"Failed to load usage stats config {e}") + + if usage_stats_enabled_config_var is False: + return UsageStatsEnabledness.DISABLED_EXPLICITLY + elif usage_stats_enabled_config_var is True: + return UsageStatsEnabledness.ENABLED_EXPLICITLY + elif usage_stats_enabled_config_var is not None: + raise ValueError( + f"Valid value for 'usage_stats' in {_usage_stats_config_path()}" + f" is true or false, but got {usage_stats_enabled_config_var}" + ) + + # Usage stats is enabled by default. + return UsageStatsEnabledness.ENABLED_BY_DEFAULT + + +def is_nightly_wheel() -> bool: + return ray.__commit__ != "{{RAY_COMMIT_SHA}}" and "dev" in ray.__version__ + + +def usage_stats_enabled() -> bool: + return _usage_stats_enabledness() is not UsageStatsEnabledness.DISABLED_EXPLICITLY + + +def usage_stats_prompt_enabled(): + return int(os.getenv("RAY_USAGE_STATS_PROMPT_ENABLED", "1")) == 1 + + +def _generate_cluster_metadata(*, ray_init_cluster: bool): + """Return a dictionary of cluster metadata. + + Params: + ray_init_cluster: Whether the cluster is started by ray.init() + """ + ray_version, python_version = ray._private.utils.compute_version_info() + # These two metadata is necessary although usage report is not enabled + # to check version compatibility. + metadata = { + "ray_version": ray_version, + "python_version": python_version, + "ray_init_cluster": ray_init_cluster, + } + # Additional metadata is recorded only when usage stats are enabled. + if usage_stats_enabled(): + metadata.update( + { + "git_commit": ray.__commit__, + "os": sys.platform, + "session_start_timestamp_ms": int(time.time() * 1000), + } + ) + if sys.platform == "linux": + # Record llibc version + (lib, ver) = platform.libc_ver() + if not lib: + metadata.update({"libc_version": "NA"}) + else: + metadata.update({"libc_version": f"{lib}:{ver}"}) + return metadata + + +def show_usage_stats_prompt(cli: bool) -> None: + if not usage_stats_prompt_enabled(): + return + + from ray.autoscaler._private.cli_logger import cli_logger + + prompt_print = cli_logger.print if cli else print + + usage_stats_enabledness = _usage_stats_enabledness() + if usage_stats_enabledness is UsageStatsEnabledness.DISABLED_EXPLICITLY: + prompt_print(usage_constant.USAGE_STATS_DISABLED_MESSAGE) + elif usage_stats_enabledness is UsageStatsEnabledness.ENABLED_BY_DEFAULT: + if not cli: + prompt_print( + usage_constant.USAGE_STATS_ENABLED_BY_DEFAULT_FOR_RAY_INIT_MESSAGE + ) + elif cli_logger.interactive: + enabled = cli_logger.confirm( + False, + usage_constant.USAGE_STATS_CONFIRMATION_MESSAGE, + _default=True, + _timeout_s=10, + ) + set_usage_stats_enabled_via_env_var(enabled) + # Remember user's choice. + try: + set_usage_stats_enabled_via_config(enabled) + except Exception as e: + logger.debug( + f"Failed to persist usage stats choice for future clusters: {e}" + ) + if enabled: + prompt_print(usage_constant.USAGE_STATS_ENABLED_FOR_CLI_MESSAGE) + else: + prompt_print(usage_constant.USAGE_STATS_DISABLED_MESSAGE) + else: + prompt_print( + usage_constant.USAGE_STATS_ENABLED_BY_DEFAULT_FOR_CLI_MESSAGE, + ) + else: + assert usage_stats_enabledness is UsageStatsEnabledness.ENABLED_EXPLICITLY + prompt_print( + usage_constant.USAGE_STATS_ENABLED_FOR_CLI_MESSAGE + if cli + else usage_constant.USAGE_STATS_ENABLED_FOR_RAY_INIT_MESSAGE + ) + + +def set_usage_stats_enabled_via_config(enabled) -> None: + config = {} + try: + with open(_usage_stats_config_path()) as f: + config = json.load(f) + if not isinstance(config, dict): + logger.debug( + f"Invalid ray config file, should be a json dict but got {type(config)}" + ) + config = {} + except FileNotFoundError: + pass + except Exception as e: + logger.debug(f"Failed to load ray config file {e}") + + config["usage_stats"] = enabled + + try: + os.makedirs(os.path.dirname(_usage_stats_config_path()), exist_ok=True) + with open(_usage_stats_config_path(), "w") as f: + json.dump(config, f) + except Exception as e: + raise Exception( + "Failed to " + f'{"enable" if enabled else "disable"}' + ' usage stats by writing {"usage_stats": ' + f'{"true" if enabled else "false"}' + "} to " + f"{_usage_stats_config_path()}" + ) from e + + +def set_usage_stats_enabled_via_env_var(enabled) -> None: + os.environ[usage_constant.USAGE_STATS_ENABLED_ENV_VAR] = "1" if enabled else "0" + + +def put_cluster_metadata(gcs_client, *, ray_init_cluster) -> None: + """Generate the cluster metadata and store it to GCS. + + It is a blocking API. + + Params: + gcs_client: The GCS client to perform KV operation PUT. + ray_init_cluster: Whether the cluster is started by ray.init() + + Raises: + gRPC exceptions: If PUT fails. + """ + metadata = _generate_cluster_metadata(ray_init_cluster=ray_init_cluster) + gcs_client.internal_kv_put( + usage_constant.CLUSTER_METADATA_KEY, + json.dumps(metadata).encode(), + overwrite=True, + namespace=ray_constants.KV_NAMESPACE_CLUSTER, + ) + return metadata + + +def get_total_num_running_jobs_to_report(gcs_client) -> Optional[int]: + """Return the total number of running jobs in the cluster excluding internal ones""" + try: + result = gcs_client.get_all_job_info( + skip_submission_job_info_field=True, skip_is_running_tasks_field=True + ) + total_num_running_jobs = 0 + for job_info in result.values(): + if not job_info.is_dead and not job_info.config.ray_namespace.startswith( + "_ray_internal" + ): + total_num_running_jobs += 1 + return total_num_running_jobs + except Exception as e: + logger.info(f"Failed to query number of running jobs in the cluster: {e}") + return None + + +def get_total_num_nodes_to_report(gcs_client, timeout=None) -> Optional[int]: + """Return the total number of alive nodes in the cluster""" + try: + result = gcs_client.get_all_node_info(timeout=timeout) + total_num_nodes = 0 + for node_id, node_info in result.items(): + if node_info.state == gcs_pb2.GcsNodeInfo.GcsNodeState.ALIVE: + total_num_nodes += 1 + return total_num_nodes + except Exception as e: + logger.info(f"Failed to query number of nodes in the cluster: {e}") + return None + + +def get_library_usages_to_report(gcs_client) -> List[str]: + return list(_get_usage_set(gcs_client, usage_constant.LIBRARY_USAGE_SET_NAME)) + + +def get_hardware_usages_to_report(gcs_client) -> List[str]: + return list(_get_usage_set(gcs_client, usage_constant.HARDWARE_USAGE_SET_NAME)) + + +def get_extra_usage_tags_to_report(gcs_client) -> Dict[str, str]: + """Get the extra usage tags from env var and gcs kv store. + + The env var should be given this way; key=value;key=value. + If parsing is failed, it will return the empty data. + + Returns: + Extra usage tags as kv pairs. + """ + extra_usage_tags = dict() + + extra_usage_tags_env_var = os.getenv("RAY_USAGE_STATS_EXTRA_TAGS", None) + if extra_usage_tags_env_var: + try: + kvs = extra_usage_tags_env_var.strip(";").split(";") + for kv in kvs: + k, v = kv.split("=") + extra_usage_tags[k] = v + except Exception as e: + logger.info(f"Failed to parse extra usage tags env var: {e}") + + valid_tag_keys = [tag_key.lower() for tag_key in TagKey.keys()] + try: + keys = gcs_client.internal_kv_keys( + usage_constant.EXTRA_USAGE_TAG_PREFIX.encode(), + namespace=usage_constant.USAGE_STATS_NAMESPACE.encode(), + ) + kv = gcs_client.internal_kv_multi_get( + keys, namespace=usage_constant.USAGE_STATS_NAMESPACE.encode() + ) + for key, value in kv.items(): + key = key.decode("utf-8") + key = key[len(usage_constant.EXTRA_USAGE_TAG_PREFIX) :] + assert key in valid_tag_keys + extra_usage_tags[key] = value.decode("utf-8") + except Exception as e: + logger.info(f"Failed to get extra usage tags from kv store: {e}") + return extra_usage_tags + + +def _get_cluster_status_to_report_v2(gcs_client) -> ClusterStatusToReport: + """ + Get the current status of this cluster. A temporary proxy for the + autoscaler v2 API. + + It is a blocking API. + + Params: + gcs_client: The GCS client. + + Returns: + The current cluster status or empty ClusterStatusToReport + if it fails to get that information. + """ + from ray.autoscaler.v2.sdk import get_cluster_status + + result = ClusterStatusToReport() + try: + cluster_status = get_cluster_status(gcs_client.address) + total_resources = cluster_status.total_resources() + result.total_num_cpus = int(total_resources.get("CPU", 0)) + result.total_num_gpus = int(total_resources.get("GPU", 0)) + + to_GiB = 1 / 2**30 + result.total_memory_gb = total_resources.get("memory", 0) * to_GiB + result.total_object_store_memory_gb = ( + total_resources.get("object_store_memory", 0) * to_GiB + ) + except Exception as e: + logger.info(f"Failed to get cluster status to report {e}") + finally: + return result + + +def get_cluster_status_to_report(gcs_client) -> ClusterStatusToReport: + """Get the current status of this cluster. + + It is a blocking API. + + Params: + gcs_client: The GCS client to perform KV operation GET. + + Returns: + The current cluster status or empty if it fails to get that information. + """ + try: + + from ray.autoscaler.v2.utils import is_autoscaler_v2 + + if is_autoscaler_v2(): + return _get_cluster_status_to_report_v2(gcs_client) + + cluster_status = gcs_client.internal_kv_get( + ray._private.ray_constants.DEBUG_AUTOSCALING_STATUS.encode(), + namespace=None, + ) + if not cluster_status: + return ClusterStatusToReport() + + result = ClusterStatusToReport() + to_GiB = 1 / 2**30 + cluster_status = json.loads(cluster_status.decode("utf-8")) + if ( + "load_metrics_report" not in cluster_status + or "usage" not in cluster_status["load_metrics_report"] + ): + return ClusterStatusToReport() + + usage = cluster_status["load_metrics_report"]["usage"] + # usage is a map from resource to (used, total) pair + if "CPU" in usage: + result.total_num_cpus = int(usage["CPU"][1]) + if "GPU" in usage: + result.total_num_gpus = int(usage["GPU"][1]) + if "memory" in usage: + result.total_memory_gb = usage["memory"][1] * to_GiB + if "object_store_memory" in usage: + result.total_object_store_memory_gb = ( + usage["object_store_memory"][1] * to_GiB + ) + return result + except Exception as e: + logger.info(f"Failed to get cluster status to report {e}") + return ClusterStatusToReport() + + +def get_cloud_from_metadata_requests() -> str: + def cloud_metadata_request(url: str, headers: Optional[Dict[str, str]]) -> bool: + try: + res = requests.get(url, headers=headers, timeout=1) + # The requests may be rejected based on pod configuration but if + # it's a machine on the cloud provider it should at least be reachable. + if res.status_code != 404: + return True + # ConnectionError is a superclass of ConnectTimeout + except requests.exceptions.ConnectionError: + pass + except Exception as e: + logger.info( + f"Unexpected exception when making cloud provider metadata request: {e}" + ) + return False + + # Make internal metadata requests to all 3 clouds + if cloud_metadata_request( + "http://metadata.google.internal/computeMetadata/v1", + {"Metadata-Flavor": "Google"}, + ): + return "gcp" + elif cloud_metadata_request("http://169.254.169.254/latest/meta-data/", None): + return "aws" + elif cloud_metadata_request( + "http://169.254.169.254/metadata/instance?api-version=2021-02-01", + {"Metadata": "true"}, + ): + return "azure" + else: + return "unknown" + + +def get_cluster_config_to_report( + cluster_config_file_path: str, +) -> ClusterConfigToReport: + """Get the static cluster (autoscaler) config used to launch this cluster. + + Params: + cluster_config_file_path: The file path to the cluster config file. + + Returns: + The cluster (autoscaler) config or empty if it fails to get that information. + """ + + def get_instance_type(node_config): + if not node_config: + return None + if "InstanceType" in node_config: + # aws + return node_config["InstanceType"] + if "machineType" in node_config: + # gcp + return node_config["machineType"] + if ( + "azure_arm_parameters" in node_config + and "vmSize" in node_config["azure_arm_parameters"] + ): + return node_config["azure_arm_parameters"]["vmSize"] + return None + + try: + with open(cluster_config_file_path) as f: + config = yaml.safe_load(f) + result = ClusterConfigToReport() + if "min_workers" in config: + result.min_workers = config["min_workers"] + if "max_workers" in config: + result.max_workers = config["max_workers"] + + if "provider" in config and "type" in config["provider"]: + result.cloud_provider = config["provider"]["type"] + + if "head_node_type" not in config: + return result + if "available_node_types" not in config: + return result + head_node_type = config["head_node_type"] + available_node_types = config["available_node_types"] + for available_node_type in available_node_types: + if available_node_type == head_node_type: + head_node_instance_type = get_instance_type( + available_node_types[available_node_type].get("node_config") + ) + if head_node_instance_type: + result.head_node_instance_type = head_node_instance_type + else: + worker_node_instance_type = get_instance_type( + available_node_types[available_node_type].get("node_config") + ) + if worker_node_instance_type: + result.worker_node_instance_types = ( + result.worker_node_instance_types or set() + ) + result.worker_node_instance_types.add(worker_node_instance_type) + if result.worker_node_instance_types: + result.worker_node_instance_types = list( + result.worker_node_instance_types + ) + return result + except FileNotFoundError: + # It's a manually started cluster or k8s cluster + result = ClusterConfigToReport() + + # Check if we're on Kubernetes + if usage_constant.KUBERNETES_SERVICE_HOST_ENV in os.environ: + # Check if we're using KubeRay >= 0.4.0. + if usage_constant.KUBERAY_ENV in os.environ: + result.cloud_provider = usage_constant.PROVIDER_KUBERAY + # Else, we're on Kubernetes but not in either of the above categories. + else: + result.cloud_provider = usage_constant.PROVIDER_KUBERNETES_GENERIC + + # if kubernetes was not set as cloud_provider vs. was set before + if result.cloud_provider is None: + result.cloud_provider = get_cloud_from_metadata_requests() + else: + result.cloud_provider += f"_${get_cloud_from_metadata_requests()}" + + return result + except Exception as e: + logger.info(f"Failed to get cluster config to report {e}") + return ClusterConfigToReport() + + +def get_cluster_metadata(gcs_client) -> dict: + """Get the cluster metadata from GCS. + + It is a blocking API. + + This will return None if `put_cluster_metadata` was never called. + + Params: + gcs_client: The GCS client to perform KV operation GET. + + Returns: + The cluster metadata in a dictinoary. + + Raises: + RuntimeError: If it fails to obtain cluster metadata from GCS. + """ + return json.loads( + gcs_client.internal_kv_get( + usage_constant.CLUSTER_METADATA_KEY, + namespace=ray_constants.KV_NAMESPACE_CLUSTER, + ).decode("utf-8") + ) + + +def is_ray_init_cluster(gcs_client: ray._raylet.GcsClient) -> bool: + """Return whether the cluster is started by ray.init()""" + cluster_metadata = get_cluster_metadata(gcs_client) + return cluster_metadata["ray_init_cluster"] + + +def generate_disabled_report_data() -> UsageStatsToReport: + """Generate the report data indicating usage stats is disabled""" + data = UsageStatsToReport( + schema_version=usage_constant.SCHEMA_VERSION, + source=os.getenv( + usage_constant.USAGE_STATS_SOURCE_ENV_VAR, + usage_constant.USAGE_STATS_SOURCE_OSS, + ), + collect_timestamp_ms=int(time.time() * 1000), + ) + return data + + +def generate_report_data( + cluster_config_to_report: ClusterConfigToReport, + total_success: int, + total_failed: int, + seq_number: int, + gcs_address: str, + cluster_id: str, +) -> UsageStatsToReport: + """Generate the report data. + + Params: + cluster_config_to_report: The cluster (autoscaler) + config generated by `get_cluster_config_to_report`. + total_success: The total number of successful report + for the lifetime of the cluster. + total_failed: The total number of failed report + for the lifetime of the cluster. + seq_number: The sequence number that's incremented whenever + a new report is sent. + gcs_address: the address of gcs to get data to report. + cluster_id: hex id of the cluster. + + Returns: + UsageStats + """ + assert cluster_id + + gcs_client = ray._raylet.GcsClient(address=gcs_address, cluster_id=cluster_id) + + cluster_metadata = get_cluster_metadata(gcs_client) + cluster_status_to_report = get_cluster_status_to_report(gcs_client) + + data = UsageStatsToReport( + schema_version=usage_constant.SCHEMA_VERSION, + source=os.getenv( + usage_constant.USAGE_STATS_SOURCE_ENV_VAR, + usage_constant.USAGE_STATS_SOURCE_OSS, + ), + collect_timestamp_ms=int(time.time() * 1000), + total_success=total_success, + total_failed=total_failed, + seq_number=seq_number, + ray_version=cluster_metadata["ray_version"], + python_version=cluster_metadata["python_version"], + session_id=cluster_id, + git_commit=cluster_metadata["git_commit"], + os=cluster_metadata["os"], + session_start_timestamp_ms=cluster_metadata["session_start_timestamp_ms"], + cloud_provider=cluster_config_to_report.cloud_provider, + min_workers=cluster_config_to_report.min_workers, + max_workers=cluster_config_to_report.max_workers, + head_node_instance_type=cluster_config_to_report.head_node_instance_type, + worker_node_instance_types=cluster_config_to_report.worker_node_instance_types, + total_num_cpus=cluster_status_to_report.total_num_cpus, + total_num_gpus=cluster_status_to_report.total_num_gpus, + total_memory_gb=cluster_status_to_report.total_memory_gb, + total_object_store_memory_gb=cluster_status_to_report.total_object_store_memory_gb, # noqa: E501 + library_usages=get_library_usages_to_report(gcs_client), + extra_usage_tags=get_extra_usage_tags_to_report(gcs_client), + total_num_nodes=get_total_num_nodes_to_report(gcs_client), + total_num_running_jobs=get_total_num_running_jobs_to_report(gcs_client), + libc_version=cluster_metadata.get("libc_version"), + hardware_usages=get_hardware_usages_to_report(gcs_client), + ) + return data + + +def generate_write_data( + usage_stats: UsageStatsToReport, + error: str, +) -> UsageStatsToWrite: + """Generate the report data. + + Params: + usage_stats: The usage stats that were reported. + error: The error message of failed reports. + + Returns: + UsageStatsToWrite + """ + data = UsageStatsToWrite( + usage_stats=usage_stats, + success=error is None, + error=error, + ) + return data + + +class UsageReportClient: + """The client implementation for usage report. + + It is in charge of writing usage stats to the directory + and report usage stats. + """ + + def write_usage_data(self, data: UsageStatsToWrite, dir_path: str) -> None: + """Write the usage data to the directory. + + Params: + data: Data to report + dir_path: The path to the directory to write usage data. + """ + # Atomically update the file. + dir_path = Path(dir_path) + destination = dir_path / usage_constant.USAGE_STATS_FILE + temp = dir_path / f"{usage_constant.USAGE_STATS_FILE}.tmp" + with temp.open(mode="w") as json_file: + json_file.write(json.dumps(asdict(data))) + if sys.platform == "win32": + # Windows 32 doesn't support atomic renaming, so we should delete + # the file first. + destination.unlink(missing_ok=True) + temp.rename(destination) + + def report_usage_data(self, url: str, data: UsageStatsToReport) -> None: + """Report the usage data to the usage server. + + Params: + url: The URL to update resource usage. + data: Data to report. + + Raises: + requests.HTTPError: If requests fails. + """ + r = requests.request( + "POST", + url, + headers={"Content-Type": "application/json"}, + json=asdict(data), + timeout=10, + ) + r.raise_for_status() + return r diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b838b4cdc09cf478a3e29ede44912ffefce9ccf5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/utils.py @@ -0,0 +1,1626 @@ +import contextlib +import importlib +import json +import logging +import multiprocessing +import os +import platform +import re +import signal +import subprocess +import sys +import threading +import time +from collections import defaultdict +from pathlib import Path +from subprocess import list2cmdline +from typing import ( + TYPE_CHECKING, + Any, + Dict, + List, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +from google.protobuf import json_format + +import ray +import ray._private.ray_constants as ray_constants +from ray._common.utils import ( + PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME, + get_ray_address_file, + get_system_memory, +) +from ray.core.generated.runtime_env_common_pb2 import ( + RuntimeEnvInfo as ProtoRuntimeEnvInfo, +) + +# Import psutil after ray so the packaged version is used. +import psutil + +if TYPE_CHECKING: + from ray.runtime_env import RuntimeEnv + + +INT32_MAX = (2**31) - 1 + + +pwd = None +if sys.platform != "win32": + import pwd + +logger = logging.getLogger(__name__) + +# Linux can bind child processes' lifetimes to that of their parents via prctl. +# prctl support is detected dynamically once, and assumed thereafter. +linux_prctl = None + +# Windows can bind processes' lifetimes to that of kernel-level "job objects". +# We keep a global job object to tie its lifetime to that of our own process. +win32_job = None +win32_AssignProcessToJobObject = None + +ENV_DISABLE_DOCKER_CPU_WARNING = "RAY_DISABLE_DOCKER_CPU_WARNING" in os.environ + +# This global variable is used for testing only +_CALLED_FREQ = defaultdict(lambda: 0) +_CALLED_FREQ_LOCK = threading.Lock() + +PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN = re.compile( + r"(.+)_group_(\d+)_([0-9a-zA-Z]+)" +) +PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN = re.compile(r"(.+)_group_([0-9a-zA-Z]+)") + + +def write_ray_address(ray_address: str, temp_dir: Optional[str] = None): + address_file = get_ray_address_file(temp_dir) + if os.path.exists(address_file): + with open(address_file, "r") as f: + prev_address = f.read() + if prev_address == ray_address: + return + + logger.info( + f"Overwriting previous Ray address ({prev_address}). " + "Running ray.init() on this node will now connect to the new " + f"instance at {ray_address}. To override this behavior, pass " + f"address={prev_address} to ray.init()." + ) + + with open(address_file, "w+") as f: + f.write(ray_address) + + +def read_ray_address(temp_dir: Optional[str] = None) -> str: + address_file = get_ray_address_file(temp_dir) + if not os.path.exists(address_file): + return None + with open(address_file, "r") as f: + return f.read().strip() + + +def format_error_message(exception_message: str, task_exception: bool = False): + """Improve the formatting of an exception thrown by a remote function. + + This method takes a traceback from an exception and makes it nicer by + removing a few uninformative lines and adding some space to indent the + remaining lines nicely. + + Args: + exception_message: A message generated by traceback.format_exc(). + + Returns: + A string of the formatted exception message. + """ + lines = exception_message.split("\n") + if task_exception: + # For errors that occur inside of tasks, remove lines 1 and 2 which are + # always the same, they just contain information about the worker code. + lines = lines[0:1] + lines[3:] + pass + return "\n".join(lines) + + +def push_error_to_driver( + worker, error_type: str, message: str, job_id: Optional[str] = None +): + """Push an error message to the driver to be printed in the background. + + Args: + worker: The worker to use. + error_type: The type of the error. + message: The message that will be printed in the background + on the driver. + job_id: The ID of the driver to push the error message to. If this + is None, then the message will be pushed to all drivers. + """ + if job_id is None: + job_id = ray.JobID.nil() + assert isinstance(job_id, ray.JobID) + worker.core_worker.push_error(job_id, error_type, message, time.time()) + + +def publish_error_to_driver( + error_type: str, + message: str, + gcs_client, + job_id=None, +): + """Push an error message to the driver to be printed in the background. + + Normally the push_error_to_driver function should be used. However, in some + instances, the raylet client is not available, e.g., because the + error happens in Python before the driver or worker has connected to the + backend processes. + + Args: + error_type: The type of the error. + message: The message that will be printed in the background + on the driver. + gcs_client: The GCS client to use. + job_id: The ID of the driver to push the error message to. If this + is None, then the message will be pushed to all drivers. + """ + if job_id is None: + job_id = ray.JobID.nil() + assert isinstance(job_id, ray.JobID) + try: + gcs_client.publish_error(job_id.hex().encode(), error_type, message, job_id, 60) + except Exception: + logger.exception(f"Failed to publish error: {message} [type {error_type}]") + + +def ensure_str(s, encoding="utf-8", errors="strict"): + """Coerce *s* to `str`. + + - `str` -> `str` + - `bytes` -> decoded to `str` + """ + if isinstance(s, str): + return s + else: + assert isinstance(s, bytes), f"Expected str or bytes, got {type(s)}" + return s.decode(encoding, errors) + + +def binary_to_object_ref(binary_object_ref): + return ray.ObjectRef(binary_object_ref) + + +def binary_to_task_id(binary_task_id): + return ray.TaskID(binary_task_id) + + +# TODO(qwang): Remove these hepler functions +# once we separate `WorkerID` from `UniqueID`. +def compute_job_id_from_driver(driver_id): + assert isinstance(driver_id, ray.WorkerID) + return ray.JobID(driver_id.binary()[0 : ray.JobID.size()]) + + +def compute_driver_id_from_job(job_id): + assert isinstance(job_id, ray.JobID) + rest_length = ray_constants.ID_SIZE - job_id.size() + driver_id_str = job_id.binary() + (rest_length * b"\xff") + return ray.WorkerID(driver_id_str) + + +def get_visible_accelerator_ids() -> Mapping[str, Optional[List[str]]]: + """Get the mapping from accelerator resource name + to the visible ids.""" + + from ray._private.accelerators import ( + get_accelerator_manager_for_resource, + get_all_accelerator_resource_names, + ) + + return { + accelerator_resource_name: get_accelerator_manager_for_resource( + accelerator_resource_name + ).get_current_process_visible_accelerator_ids() + for accelerator_resource_name in get_all_accelerator_resource_names() + } + + +def set_omp_num_threads_if_unset() -> bool: + """Set the OMP_NUM_THREADS to default to num cpus assigned to the worker + + This function sets the environment variable OMP_NUM_THREADS for the worker, + if the env is not previously set and it's running in worker (WORKER_MODE). + + Returns True if OMP_NUM_THREADS is set in this function. + + """ + num_threads_from_env = os.environ.get("OMP_NUM_THREADS") + if num_threads_from_env is not None: + # No ops if it's set + return False + + # If unset, try setting the correct CPU count assigned. + runtime_ctx = ray.get_runtime_context() + if runtime_ctx.worker.mode != ray._private.worker.WORKER_MODE: + # Non worker mode, no ops. + return False + + num_assigned_cpus = runtime_ctx.get_assigned_resources().get("CPU") + + if num_assigned_cpus is None: + # This is an actor task w/o any num_cpus specified, set it to 1 + logger.debug( + "[ray] Forcing OMP_NUM_THREADS=1 to avoid performance " + "degradation with many workers (issue #6998). You can override this " + "by explicitly setting OMP_NUM_THREADS, or changing num_cpus." + ) + num_assigned_cpus = 1 + + import math + + # For num_cpu < 1: Set to 1. + # For num_cpus >= 1: Set to the floor of the actual assigned cpus. + omp_num_threads = max(math.floor(num_assigned_cpus), 1) + os.environ["OMP_NUM_THREADS"] = str(omp_num_threads) + return True + + +def set_visible_accelerator_ids() -> None: + """Set (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, HIP_VISIBLE_DEVICES, + NEURON_RT_VISIBLE_CORES, TPU_VISIBLE_CHIPS , HABANA_VISIBLE_MODULES ,...) + environment variables based on the accelerator runtime. + """ + for resource_name, accelerator_ids in ( + ray.get_runtime_context().get_accelerator_ids().items() + ): + ray._private.accelerators.get_accelerator_manager_for_resource( + resource_name + ).set_current_process_visible_accelerator_ids(accelerator_ids) + + +class Unbuffered(object): + """There's no "built-in" solution to programatically disabling buffering of + text files. Ray expects stdout/err to be text files, so creating an + unbuffered binary file is unacceptable. + + See + https://mail.python.org/pipermail/tutor/2003-November/026645.html. + https://docs.python.org/3/library/functions.html#open + + """ + + def __init__(self, stream): + self.stream = stream + + def write(self, data): + self.stream.write(data) + self.stream.flush() + + def writelines(self, datas): + self.stream.writelines(datas) + self.stream.flush() + + def __getattr__(self, attr): + return getattr(self.stream, attr) + + +def open_log(path, unbuffered=False, **kwargs): + """ + Opens the log file at `path`, with the provided kwargs being given to + `open`. + """ + # Disable buffering, see test_advanced_3.py::test_logging_to_driver + kwargs.setdefault("buffering", 1) + kwargs.setdefault("mode", "a") + kwargs.setdefault("encoding", "utf-8") + stream = open(path, **kwargs) + if unbuffered: + return Unbuffered(stream) + else: + return stream + + +def _get_docker_cpus( + cpu_quota_file_name="/sys/fs/cgroup/cpu/cpu.cfs_quota_us", + cpu_period_file_name="/sys/fs/cgroup/cpu/cpu.cfs_period_us", + cpuset_file_name="/sys/fs/cgroup/cpuset/cpuset.cpus", + cpu_max_file_name="/sys/fs/cgroup/cpu.max", +) -> Optional[float]: + # TODO (Alex): Don't implement this logic oursleves. + # Docker has 2 underyling ways of implementing CPU limits: + # https://docs.docker.com/config/containers/resource_constraints/#configure-the-default-cfs-scheduler + # 1. --cpuset-cpus 2. --cpus or --cpu-quota/--cpu-period (--cpu-shares is a + # soft limit so we don't worry about it). For Ray's purposes, if we use + # docker, the number of vCPUs on a machine is whichever is set (ties broken + # by smaller value). + + cpu_quota = None + # See: https://bugs.openjdk.java.net/browse/JDK-8146115 + if os.path.exists(cpu_quota_file_name) and os.path.exists(cpu_period_file_name): + try: + with open(cpu_quota_file_name, "r") as quota_file, open( + cpu_period_file_name, "r" + ) as period_file: + cpu_quota = float(quota_file.read()) / float(period_file.read()) + except Exception: + logger.exception("Unexpected error calculating docker cpu quota.") + # Look at cpu.max for cgroups v2 + elif os.path.exists(cpu_max_file_name): + try: + max_file = open(cpu_max_file_name).read() + quota_str, period_str = max_file.split() + if quota_str.isnumeric() and period_str.isnumeric(): + cpu_quota = float(quota_str) / float(period_str) + else: + # quota_str is "max" meaning the cpu quota is unset + cpu_quota = None + except Exception: + logger.exception("Unexpected error calculating docker cpu quota.") + if (cpu_quota is not None) and (cpu_quota < 0): + cpu_quota = None + elif cpu_quota == 0: + # Round up in case the cpu limit is less than 1. + cpu_quota = 1 + + cpuset_num = None + if os.path.exists(cpuset_file_name): + try: + with open(cpuset_file_name) as cpuset_file: + ranges_as_string = cpuset_file.read() + ranges = ranges_as_string.split(",") + cpu_ids = [] + for num_or_range in ranges: + if "-" in num_or_range: + start, end = num_or_range.split("-") + cpu_ids.extend(list(range(int(start), int(end) + 1))) + else: + cpu_ids.append(int(num_or_range)) + cpuset_num = len(cpu_ids) + except Exception: + logger.exception("Unexpected error calculating docker cpuset ids.") + # Possible to-do: Parse cgroups v2's cpuset.cpus.effective for the number + # of accessible CPUs. + + if cpu_quota and cpuset_num: + return min(cpu_quota, cpuset_num) + return cpu_quota or cpuset_num + + +def get_num_cpus( + override_docker_cpu_warning: bool = ENV_DISABLE_DOCKER_CPU_WARNING, +) -> int: + """ + Get the number of CPUs available on this node. + Depending on the situation, use multiprocessing.cpu_count() or cgroups. + + Args: + override_docker_cpu_warning: An extra flag to explicitly turn off the Docker + warning. Setting this flag True has the same effect as setting the env + RAY_DISABLE_DOCKER_CPU_WARNING. By default, whether or not to log + the warning is determined by the env variable + RAY_DISABLE_DOCKER_CPU_WARNING. + """ + cpu_count = multiprocessing.cpu_count() + if os.environ.get("RAY_USE_MULTIPROCESSING_CPU_COUNT"): + logger.info( + "Detected RAY_USE_MULTIPROCESSING_CPU_COUNT=1: Using " + "multiprocessing.cpu_count() to detect the number of CPUs. " + "This may be inconsistent when used inside docker. " + "To correctly detect CPUs, unset the env var: " + "`RAY_USE_MULTIPROCESSING_CPU_COUNT`." + ) + return cpu_count + try: + # Not easy to get cpu count in docker, see: + # https://bugs.python.org/issue36054 + docker_count = _get_docker_cpus() + if docker_count is not None and docker_count != cpu_count: + # Don't log this warning if we're on K8s or if the warning is + # explicitly disabled. + if ( + "KUBERNETES_SERVICE_HOST" not in os.environ + and not ENV_DISABLE_DOCKER_CPU_WARNING + and not override_docker_cpu_warning + ): + logger.warning( + "Detecting docker specified CPUs. In " + "previous versions of Ray, CPU detection in containers " + "was incorrect. Please ensure that Ray has enough CPUs " + "allocated. As a temporary workaround to revert to the " + "prior behavior, set " + "`RAY_USE_MULTIPROCESSING_CPU_COUNT=1` as an env var " + "before starting Ray. Set the env var: " + "`RAY_DISABLE_DOCKER_CPU_WARNING=1` to mute this warning." + ) + # TODO (Alex): We should probably add support for fractional cpus. + if int(docker_count) != float(docker_count): + logger.warning( + f"Ray currently does not support initializing Ray " + f"with fractional cpus. Your num_cpus will be " + f"truncated from {docker_count} to " + f"{int(docker_count)}." + ) + docker_count = int(docker_count) + cpu_count = docker_count + + except Exception: + # `nproc` and cgroup are linux-only. If docker only works on linux + # (will run in a linux VM on other platforms), so this is fine. + pass + + return cpu_count + + +# TODO(clarng): merge code with c++ +def get_cgroup_used_memory( + memory_stat_filename: str, + memory_usage_filename: str, + inactive_file_key: str, + active_file_key: str, +): + """ + The calculation logic is the same with `GetCGroupMemoryUsedBytes` + in `memory_monitor.cc` file. + """ + inactive_file_bytes = -1 + active_file_bytes = -1 + with open(memory_stat_filename, "r") as f: + lines = f.readlines() + for line in lines: + if f"{inactive_file_key} " in line: + inactive_file_bytes = int(line.split()[1]) + elif f"{active_file_key} " in line: + active_file_bytes = int(line.split()[1]) + + with open(memory_usage_filename, "r") as f: + lines = f.readlines() + cgroup_usage_in_bytes = int(lines[0].strip()) + + if ( + inactive_file_bytes == -1 + or cgroup_usage_in_bytes == -1 + or active_file_bytes == -1 + ): + return None + + return cgroup_usage_in_bytes - inactive_file_bytes - active_file_bytes + + +def get_used_memory(): + """Return the currently used system memory in bytes + + Returns: + The total amount of used memory + """ + # Try to accurately figure out the memory usage if we are in a docker + # container. + docker_usage = None + # For cgroups v1: + memory_usage_filename_v1 = "/sys/fs/cgroup/memory/memory.usage_in_bytes" + memory_stat_filename_v1 = "/sys/fs/cgroup/memory/memory.stat" + # For cgroups v2: + memory_usage_filename_v2 = "/sys/fs/cgroup/memory.current" + memory_stat_filename_v2 = "/sys/fs/cgroup/memory.stat" + if os.path.exists(memory_usage_filename_v1) and os.path.exists( + memory_stat_filename_v1 + ): + docker_usage = get_cgroup_used_memory( + memory_stat_filename_v1, + memory_usage_filename_v1, + "total_inactive_file", + "total_active_file", + ) + elif os.path.exists(memory_usage_filename_v2) and os.path.exists( + memory_stat_filename_v2 + ): + docker_usage = get_cgroup_used_memory( + memory_stat_filename_v2, + memory_usage_filename_v2, + "inactive_file", + "active_file", + ) + + if docker_usage is not None: + return docker_usage + return psutil.virtual_memory().used + + +def estimate_available_memory(): + """Return the currently available amount of system memory in bytes. + + Returns: + The total amount of available memory in bytes. Based on the used + and total memory. + + """ + return get_system_memory() - get_used_memory() + + +def get_shared_memory_bytes(): + """Get the size of the shared memory file system. + + Returns: + The size of the shared memory file system in bytes. + """ + # Make sure this is only called on Linux. + assert sys.platform == "linux" or sys.platform == "linux2" + + shm_fd = os.open("/dev/shm", os.O_RDONLY) + try: + shm_fs_stats = os.fstatvfs(shm_fd) + # The value shm_fs_stats.f_bsize is the block size and the + # value shm_fs_stats.f_bavail is the number of available + # blocks. + shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail + finally: + os.close(shm_fd) + + return shm_avail + + +def check_oversized_function( + pickled: bytes, name: str, obj_type: str, worker: "ray.Worker" +) -> None: + """Send a warning message if the pickled function is too large. + + Args: + pickled: the pickled function. + name: name of the pickled object. + obj_type: type of the pickled object, can be 'function', + 'remote function', or 'actor'. + worker: the worker used to send warning message. message will be logged + locally if None. + """ + length = len(pickled) + if length <= ray_constants.FUNCTION_SIZE_WARN_THRESHOLD: + return + elif length < ray_constants.FUNCTION_SIZE_ERROR_THRESHOLD: + warning_message = ( + "The {} {} is very large ({} MiB). " + "Check that its definition is not implicitly capturing a large " + "array or other object in scope. Tip: use ray.put() to put large " + "objects in the Ray object store." + ).format(obj_type, name, length // (1024 * 1024)) + if worker: + push_error_to_driver( + worker, + ray_constants.PICKLING_LARGE_OBJECT_PUSH_ERROR, + "Warning: " + warning_message, + job_id=worker.current_job_id, + ) + else: + error = ( + "The {} {} is too large ({} MiB > FUNCTION_SIZE_ERROR_THRESHOLD={}" + " MiB). Check that its definition is not implicitly capturing a " + "large array or other object in scope. Tip: use ray.put() to " + "put large objects in the Ray object store." + ).format( + obj_type, + name, + length // (1024 * 1024), + ray_constants.FUNCTION_SIZE_ERROR_THRESHOLD // (1024 * 1024), + ) + raise ValueError(error) + + +def is_main_thread(): + return threading.current_thread().getName() == "MainThread" + + +def detect_fate_sharing_support_win32(): + global win32_job, win32_AssignProcessToJobObject + if win32_job is None and sys.platform == "win32": + import ctypes + + try: + from ctypes.wintypes import BOOL, DWORD, HANDLE, LPCWSTR, LPVOID + + kernel32 = ctypes.WinDLL("kernel32") + kernel32.CreateJobObjectW.argtypes = (LPVOID, LPCWSTR) + kernel32.CreateJobObjectW.restype = HANDLE + sijo_argtypes = (HANDLE, ctypes.c_int, LPVOID, DWORD) + kernel32.SetInformationJobObject.argtypes = sijo_argtypes + kernel32.SetInformationJobObject.restype = BOOL + kernel32.AssignProcessToJobObject.argtypes = (HANDLE, HANDLE) + kernel32.AssignProcessToJobObject.restype = BOOL + kernel32.IsDebuggerPresent.argtypes = () + kernel32.IsDebuggerPresent.restype = BOOL + except (AttributeError, TypeError, ImportError): + kernel32 = None + job = kernel32.CreateJobObjectW(None, None) if kernel32 else None + job = subprocess.Handle(job) if job else job + if job: + from ctypes.wintypes import DWORD, LARGE_INTEGER, ULARGE_INTEGER + + class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure): + _fields_ = [ + ("PerProcessUserTimeLimit", LARGE_INTEGER), + ("PerJobUserTimeLimit", LARGE_INTEGER), + ("LimitFlags", DWORD), + ("MinimumWorkingSetSize", ctypes.c_size_t), + ("MaximumWorkingSetSize", ctypes.c_size_t), + ("ActiveProcessLimit", DWORD), + ("Affinity", ctypes.c_size_t), + ("PriorityClass", DWORD), + ("SchedulingClass", DWORD), + ] + + class IO_COUNTERS(ctypes.Structure): + _fields_ = [ + ("ReadOperationCount", ULARGE_INTEGER), + ("WriteOperationCount", ULARGE_INTEGER), + ("OtherOperationCount", ULARGE_INTEGER), + ("ReadTransferCount", ULARGE_INTEGER), + ("WriteTransferCount", ULARGE_INTEGER), + ("OtherTransferCount", ULARGE_INTEGER), + ] + + class JOBOBJECT_EXTENDED_LIMIT_INFORMATION(ctypes.Structure): + _fields_ = [ + ("BasicLimitInformation", JOBOBJECT_BASIC_LIMIT_INFORMATION), + ("IoInfo", IO_COUNTERS), + ("ProcessMemoryLimit", ctypes.c_size_t), + ("JobMemoryLimit", ctypes.c_size_t), + ("PeakProcessMemoryUsed", ctypes.c_size_t), + ("PeakJobMemoryUsed", ctypes.c_size_t), + ] + + debug = kernel32.IsDebuggerPresent() + + # Defined in ; also available here: + # https://docs.microsoft.com/en-us/windows/win32/api/jobapi2/nf-jobapi2-setinformationjobobject + JobObjectExtendedLimitInformation = 9 + JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800 + JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION = 0x00000400 + JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000 + buf = JOBOBJECT_EXTENDED_LIMIT_INFORMATION() + buf.BasicLimitInformation.LimitFlags = ( + (0 if debug else JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) + | JOB_OBJECT_LIMIT_DIE_ON_UNHANDLED_EXCEPTION + | JOB_OBJECT_LIMIT_BREAKAWAY_OK + ) + infoclass = JobObjectExtendedLimitInformation + if not kernel32.SetInformationJobObject( + job, infoclass, ctypes.byref(buf), ctypes.sizeof(buf) + ): + job = None + win32_AssignProcessToJobObject = ( + kernel32.AssignProcessToJobObject if kernel32 is not None else False + ) + win32_job = job if job else False + return bool(win32_job) + + +def detect_fate_sharing_support_linux(): + global linux_prctl + if linux_prctl is None and sys.platform.startswith("linux"): + try: + from ctypes import CDLL, c_int, c_ulong + + prctl = CDLL(None).prctl + prctl.restype = c_int + prctl.argtypes = [c_int, c_ulong, c_ulong, c_ulong, c_ulong] + except (AttributeError, TypeError): + prctl = None + linux_prctl = prctl if prctl else False + return bool(linux_prctl) + + +def detect_fate_sharing_support(): + result = None + if sys.platform == "win32": + result = detect_fate_sharing_support_win32() + elif sys.platform.startswith("linux"): + result = detect_fate_sharing_support_linux() + return result + + +def set_kill_on_parent_death_linux(): + """Ensures this process dies if its parent dies (fate-sharing). + + Linux-only. Must be called in preexec_fn (i.e. by the child). + """ + if detect_fate_sharing_support_linux(): + import signal + + PR_SET_PDEATHSIG = 1 + if linux_prctl(PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0) != 0: + import ctypes + + raise OSError(ctypes.get_errno(), "prctl(PR_SET_PDEATHSIG) failed") + else: + assert False, "PR_SET_PDEATHSIG used despite being unavailable" + + +def set_kill_child_on_death_win32(child_proc): + """Ensures the child process dies if this process dies (fate-sharing). + + Windows-only. Must be called by the parent, after spawning the child. + + Args: + child_proc: The subprocess.Popen or subprocess.Handle object. + """ + + if isinstance(child_proc, subprocess.Popen): + child_proc = child_proc._handle + assert isinstance(child_proc, subprocess.Handle) + + if detect_fate_sharing_support_win32(): + if not win32_AssignProcessToJobObject(win32_job, int(child_proc)): + import ctypes + + raise OSError(ctypes.get_last_error(), "AssignProcessToJobObject() failed") + else: + assert False, "AssignProcessToJobObject used despite being unavailable" + + +def set_sigterm_handler(sigterm_handler): + """Registers a handler for SIGTERM in a platform-compatible manner.""" + if sys.platform == "win32": + # Note that these signal handlers only work for console applications. + # TODO(mehrdadn): implement graceful process termination mechanism + # SIGINT is Ctrl+C, SIGBREAK is Ctrl+Break. + signal.signal(signal.SIGBREAK, sigterm_handler) + else: + signal.signal(signal.SIGTERM, sigterm_handler) + + +def try_to_symlink(symlink_path, target_path): + """Attempt to create a symlink. + + If the symlink path exists and isn't a symlink, the symlink will not be + created. If a symlink exists in the path, it will be attempted to be + removed and replaced. + + Args: + symlink_path: The path at which to create the symlink. + target_path: The path the symlink should point to. + """ + symlink_path = os.path.expanduser(symlink_path) + target_path = os.path.expanduser(target_path) + + if os.path.exists(symlink_path): + if os.path.islink(symlink_path): + # Try to remove existing symlink. + try: + os.remove(symlink_path) + except OSError: + return + else: + # There's an existing non-symlink file, don't overwrite it. + return + + try: + os.symlink(target_path, symlink_path) + except OSError: + return + + +def get_user(): + if pwd is None: + return "" + try: + return pwd.getpwuid(os.getuid()).pw_name + except Exception: + return "" + + +def get_conda_bin_executable(executable_name): + """ + Return path to the specified executable, assumed to be discoverable within + the 'bin' subdirectory of a conda installation. Adapted from + https://github.com/mlflow/mlflow. + """ + + # Use CONDA_EXE as per https://github.com/conda/conda/issues/7126 + if "CONDA_EXE" in os.environ: + conda_bin_dir = os.path.dirname(os.environ["CONDA_EXE"]) + return os.path.join(conda_bin_dir, executable_name) + return executable_name + + +def get_conda_env_dir(env_name): + """Find and validate the conda directory for a given conda environment. + + For example, given the environment name `tf1`, this function checks + the existence of the corresponding conda directory, e.g. + `/Users/scaly/anaconda3/envs/tf1`, and returns it. + """ + conda_prefix = os.environ.get("CONDA_PREFIX") + if conda_prefix is None: + # The caller is neither in a conda env or in (base) env. This is rare + # because by default, new terminals start in (base), but we can still + # support this case. + conda_exe = os.environ.get("CONDA_EXE") + if conda_exe is None: + raise ValueError( + "Cannot find environment variables set by conda. " + "Please verify conda is installed." + ) + # Example: CONDA_EXE=$HOME/anaconda3/bin/python + # Strip out /bin/python by going up two parent directories. + conda_prefix = str(Path(conda_exe).parent.parent) + + # There are two cases: + # 1. We are in a conda (base) env: CONDA_DEFAULT_ENV=base and + # CONDA_PREFIX=$HOME/anaconda3 + # 2. We are in a user-created conda env: CONDA_DEFAULT_ENV=$env_name and + # CONDA_PREFIX=$HOME/anaconda3/envs/$current_env_name + if os.environ.get("CONDA_DEFAULT_ENV") == "base": + # Caller's curent environment is (base). + # Not recommended by conda, but we can still support it. + if env_name == "base": + # Desired environment is (base), located at e.g. $HOME/anaconda3 + env_dir = conda_prefix + else: + # Desired environment is user-created, e.g. + # $HOME/anaconda3/envs/$env_name + env_dir = os.path.join(conda_prefix, "envs", env_name) + else: + # Now `conda_prefix` should be something like + # $HOME/anaconda3/envs/$current_env_name + # We want to replace the last component with the desired env name. + conda_envs_dir = os.path.split(conda_prefix)[0] + env_dir = os.path.join(conda_envs_dir, env_name) + if not os.path.isdir(env_dir): + raise ValueError( + "conda env " + + env_name + + " not found in conda envs directory. Run `conda env list` to " + + "verify the name is correct." + ) + return env_dir + + +def get_ray_doc_version(): + """Get the docs.ray.io version corresponding to the ray.__version__.""" + # The ray.__version__ can be official Ray release (such as 1.12.0), or + # dev (3.0.0dev0) or release candidate (2.0.0rc0). For the later we map + # to the master doc version at docs.ray.io. + if re.match(r"^\d+\.\d+\.\d+$", ray.__version__) is None: + return "master" + # For the former (official Ray release), we have corresponding doc version + # released as well. + return f"releases-{ray.__version__}" + + +# Used to only print a deprecation warning once for a given function if we +# don't wish to spam the caller. +def get_wheel_filename( + sys_platform: str = sys.platform, + ray_version: str = ray.__version__, + py_version: Tuple[int, int] = (sys.version_info.major, sys.version_info.minor), + architecture: Optional[str] = None, +) -> str: + """Returns the filename used for the nightly Ray wheel. + + Args: + sys_platform: The platform as returned by sys.platform. Examples: + "darwin", "linux", "win32" + ray_version: The Ray version as returned by ray.__version__ or + `ray --version`. Examples: "3.0.0.dev0" + py_version: The Python version as returned by sys.version_info. A + tuple of (major, minor). Examples: (3, 8) + architecture: Architecture, e.g. ``x86_64`` or ``aarch64``. If None, will + be determined by calling ``platform.processor()``. + + Returns: + The wheel file name. Examples: + ray-3.0.0.dev0-cp38-cp38-manylinux2014_x86_64.whl + """ + assert py_version in ray_constants.RUNTIME_ENV_CONDA_PY_VERSIONS, py_version + + py_version_str = "".join(map(str, py_version)) + + architecture = architecture or platform.processor() + + if py_version_str in ["311", "310", "39", "38"] and architecture == "arm64": + darwin_os_string = "macosx_12_0_arm64" + else: + darwin_os_string = "macosx_12_0_x86_64" + + if architecture == "aarch64": + linux_os_string = "manylinux2014_aarch64" + else: + linux_os_string = "manylinux2014_x86_64" + + os_strings = { + "darwin": darwin_os_string, + "linux": linux_os_string, + "win32": "win_amd64", + } + + assert sys_platform in os_strings, sys_platform + + wheel_filename = ( + f"ray-{ray_version}-cp{py_version_str}-" + f"cp{py_version_str}{'m' if py_version_str in ['37'] else ''}" + f"-{os_strings[sys_platform]}.whl" + ) + + return wheel_filename + + +def get_master_wheel_url( + ray_commit: str = ray.__commit__, + sys_platform: str = sys.platform, + ray_version: str = ray.__version__, + py_version: Tuple[int, int] = sys.version_info[:2], +) -> str: + """Return the URL for the wheel from a specific commit.""" + filename = get_wheel_filename( + sys_platform=sys_platform, ray_version=ray_version, py_version=py_version + ) + return ( + f"https://s3-us-west-2.amazonaws.com/ray-wheels/master/" + f"{ray_commit}/{filename}" + ) + + +def get_release_wheel_url( + ray_commit: str = ray.__commit__, + sys_platform: str = sys.platform, + ray_version: str = ray.__version__, + py_version: Tuple[int, int] = sys.version_info[:2], +) -> str: + """Return the URL for the wheel for a specific release.""" + filename = get_wheel_filename( + sys_platform=sys_platform, ray_version=ray_version, py_version=py_version + ) + return ( + f"https://ray-wheels.s3-us-west-2.amazonaws.com/releases/" + f"{ray_version}/{ray_commit}/{filename}" + ) + # e.g. https://ray-wheels.s3-us-west-2.amazonaws.com/releases/1.4.0rc1/e7c7 + # f6371a69eb727fa469e4cd6f4fbefd143b4c/ray-1.4.0rc1-cp36-cp36m-manylinux201 + # 4_x86_64.whl + + +def validate_namespace(namespace: str): + if not isinstance(namespace, str): + raise TypeError("namespace must be None or a string.") + elif namespace == "": + raise ValueError( + '"" is not a valid namespace. ' "Pass None to not specify a namespace." + ) + + +def init_grpc_channel( + address: str, + options: Optional[Sequence[Tuple[str, Any]]] = None, + asynchronous: bool = False, +): + import grpc + from grpc import aio as aiogrpc + + from ray._private.tls_utils import load_certs_from_env + + grpc_module = aiogrpc if asynchronous else grpc + + options = options or [] + options_dict = dict(options) + options_dict["grpc.keepalive_time_ms"] = options_dict.get( + "grpc.keepalive_time_ms", ray._config.grpc_client_keepalive_time_ms() + ) + options_dict["grpc.keepalive_timeout_ms"] = options_dict.get( + "grpc.keepalive_timeout_ms", ray._config.grpc_client_keepalive_timeout_ms() + ) + options = options_dict.items() + + if os.environ.get("RAY_USE_TLS", "0").lower() in ("1", "true"): + server_cert_chain, private_key, ca_cert = load_certs_from_env() + credentials = grpc.ssl_channel_credentials( + certificate_chain=server_cert_chain, + private_key=private_key, + root_certificates=ca_cert, + ) + channel = grpc_module.secure_channel(address, credentials, options=options) + else: + channel = grpc_module.insecure_channel(address, options=options) + + return channel + + +def check_dashboard_dependencies_installed() -> bool: + """Returns True if Ray Dashboard dependencies are installed. + + Checks to see if we should start the dashboard agent or not based on the + Ray installation version the user has installed (ray vs. ray[default]). + Unfortunately there doesn't seem to be a cleaner way to detect this other + than just blindly importing the relevant packages. + + """ + try: + import ray.dashboard.optional_deps # noqa: F401 + + return True + except ImportError: + return False + + +def check_ray_client_dependencies_installed() -> bool: + """Returns True if Ray Client dependencies are installed. + + See documents for check_dashboard_dependencies_installed. + """ + try: + import grpc # noqa: F401 + + return True + except ImportError: + return False + + +connect_error = ( + "Unable to connect to GCS (ray head) at {}. " + "Check that (1) Ray with matching version started " + "successfully at the specified address, (2) this " + "node can reach the specified address, and (3) there is " + "no firewall setting preventing access." +) + + +def internal_kv_list_with_retry(gcs_client, prefix, namespace, num_retries=20): + result = None + if isinstance(prefix, str): + prefix = prefix.encode() + if isinstance(namespace, str): + namespace = namespace.encode() + for _ in range(num_retries): + try: + result = gcs_client.internal_kv_keys(prefix, namespace) + except Exception as e: + if isinstance(e, ray.exceptions.RpcError) and e.rpc_code in ( + ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE, + ray._raylet.GRPC_STATUS_CODE_UNKNOWN, + ): + logger.warning(connect_error.format(gcs_client.address)) + else: + logger.exception("Internal KV List failed") + result = None + + if result is not None: + break + else: + logger.debug(f"Fetched {prefix}=None from KV. Retrying.") + time.sleep(2) + if result is None: + raise ConnectionError( + f"Could not list '{prefix}' from GCS. Did GCS start successfully?" + ) + return result + + +def internal_kv_get_with_retry(gcs_client, key, namespace, num_retries=20): + result = None + if isinstance(key, str): + key = key.encode() + for _ in range(num_retries): + try: + result = gcs_client.internal_kv_get(key, namespace) + except Exception as e: + if isinstance(e, ray.exceptions.RpcError) and e.rpc_code in ( + ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE, + ray._raylet.GRPC_STATUS_CODE_UNKNOWN, + ): + logger.warning(connect_error.format(gcs_client.address)) + else: + logger.exception("Internal KV Get failed") + result = None + + if result is not None: + break + else: + logger.debug(f"Fetched {key}=None from KV. Retrying.") + time.sleep(2) + if not result: + raise ConnectionError( + f"Could not read '{key.decode()}' from GCS. Did GCS start successfully?" + ) + return result + + +def parse_resources_json( + resources: str, cli_logger, cf, command_arg="--resources" +) -> Dict[str, float]: + try: + resources = json.loads(resources) + if not isinstance(resources, dict): + raise ValueError("The format after deserialization is not a dict") + except Exception as e: + cli_logger.error( + "`{}` is not a valid JSON string, detail error:{}", + cf.bold(f"{command_arg}={resources}"), + str(e), + ) + cli_logger.abort( + "Valid values look like this: `{}`", + cf.bold( + f'{command_arg}=\'{{"CustomResource3": 1, "CustomResource2": 2}}\'' + ), + ) + return resources + + +def parse_metadata_json( + metadata: str, cli_logger, cf, command_arg="--metadata-json" +) -> Dict[str, str]: + try: + metadata = json.loads(metadata) + if not isinstance(metadata, dict): + raise ValueError("The format after deserialization is not a dict") + except Exception as e: + cli_logger.error( + "`{}` is not a valid JSON string, detail error:{}", + cf.bold(f"{command_arg}={metadata}"), + str(e), + ) + cli_logger.abort( + "Valid values look like this: `{}`", + cf.bold(f'{command_arg}=\'{{"key1": "value1", "key2": "value2"}}\''), + ) + return metadata + + +def internal_kv_put_with_retry(gcs_client, key, value, namespace, num_retries=20): + if isinstance(key, str): + key = key.encode() + if isinstance(value, str): + value = value.encode() + if isinstance(namespace, str): + namespace = namespace.encode() + error = None + for _ in range(num_retries): + try: + return gcs_client.internal_kv_put( + key, value, overwrite=True, namespace=namespace + ) + except ray.exceptions.RpcError as e: + if e.rpc_code in ( + ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE, + ray._raylet.GRPC_STATUS_CODE_UNKNOWN, + ): + logger.warning(connect_error.format(gcs_client.address)) + else: + logger.exception("Internal KV Put failed") + time.sleep(2) + error = e + # Reraise the last error. + raise error + + +def compute_version_info(): + """Compute the versions of Python, and Ray. + + Returns: + A tuple containing the version information. + """ + ray_version = ray.__version__ + python_version = ".".join(map(str, sys.version_info[:3])) + return ray_version, python_version + + +def get_directory_size_bytes(path: Union[str, Path] = ".") -> int: + """Get the total size of a directory in bytes, including subdirectories.""" + total_size_bytes = 0 + for dirpath, dirnames, filenames in os.walk(path): + for f in filenames: + fp = os.path.join(dirpath, f) + # skip if it is a symbolic link or a .pyc file + if not os.path.islink(fp) and not f.endswith(".pyc"): + total_size_bytes += os.path.getsize(fp) + + return total_size_bytes + + +def check_version_info( + cluster_metadata, + this_process_address, + raise_on_mismatch=True, + python_version_match_level="patch", +): + """Check if the Python and Ray versions stored in GCS matches this process. + Args: + cluster_metadata: Ray cluster metadata from GCS. + this_process_address: Informational only. The address of this process. + e.g. "node address:port" or "Ray Client". + raise_on_mismatch: Raise an exception on True, log a warning otherwise. + python_version_match_level: "minor" or "patch". To which python version level we + try to match. Note if "minor" and the patch is different, we will still log + a warning. + + Behavior: + - We raise or log a warning, based on raise_on_mismatch, if: + - Ray versions do not match; OR + - Python (major, minor) versions do not match, + if python_version_match_level == 'minor'; OR + - Python (major, minor, patch) versions do not match, + if python_version_match_level == 'patch'. + - We also log a warning if: + - Python (major, minor) versions match, AND + - Python patch versions do not match, AND + - python_version_match_level == 'minor' AND + - raise_on_mismatch == False. + Raises: + Exception: An exception is raised if there is a version mismatch. + """ + cluster_version_info = ( + cluster_metadata["ray_version"], + cluster_metadata["python_version"], + ) + my_version_info = compute_version_info() + + # Calculate: ray_matches, python_matches, python_full_matches + ray_matches = cluster_version_info[0] == my_version_info[0] + python_full_matches = cluster_version_info[1] == my_version_info[1] + if python_version_match_level == "patch": + python_matches = cluster_version_info[1] == my_version_info[1] + elif python_version_match_level == "minor": + my_python_versions = my_version_info[1].split(".") + cluster_python_versions = cluster_version_info[1].split(".") + python_matches = my_python_versions[:2] == cluster_python_versions[:2] + else: + raise ValueError( + f"Invalid python_version_match_level: {python_version_match_level}, " + "want: 'minor' or 'patch'" + ) + + mismatch_msg = ( + "The cluster was started with:\n" + f" Ray: {cluster_version_info[0]}\n" + f" Python: {cluster_version_info[1]}\n" + f"This process on {this_process_address} was started with:\n" + f" Ray: {my_version_info[0]}\n" + f" Python: {my_version_info[1]}\n" + ) + + if ray_matches and python_matches: + if not python_full_matches: + logger.warning(f"Python patch version mismatch: {mismatch_msg}") + else: + error_message = f"Version mismatch: {mismatch_msg}" + if raise_on_mismatch: + raise RuntimeError(error_message) + else: + logger.warning(error_message) + + +def get_runtime_env_info( + runtime_env: "RuntimeEnv", + *, + is_job_runtime_env: bool = False, + serialize: bool = False, +): + """Create runtime env info from runtime env. + + In the user interface, the argument `runtime_env` contains some fields + which not contained in `ProtoRuntimeEnv` but in `ProtoRuntimeEnvInfo`, + such as `eager_install`. This function will extract those fields from + `RuntimeEnv` and create a new `ProtoRuntimeEnvInfo`, and serialize it + into json format. + """ + from ray.runtime_env import RuntimeEnvConfig + + proto_runtime_env_info = ProtoRuntimeEnvInfo() + + if runtime_env.working_dir_uri(): + proto_runtime_env_info.uris.working_dir_uri = runtime_env.working_dir_uri() + if len(runtime_env.py_modules_uris()) > 0: + proto_runtime_env_info.uris.py_modules_uris[:] = runtime_env.py_modules_uris() + + # TODO(Catch-Bull): overload `__setitem__` for `RuntimeEnv`, change the + # runtime_env of all internal code from dict to RuntimeEnv. + + runtime_env_config = runtime_env.get("config") + if runtime_env_config is None: + runtime_env_config = RuntimeEnvConfig.default_config() + else: + runtime_env_config = RuntimeEnvConfig.parse_and_validate_runtime_env_config( + runtime_env_config + ) + + proto_runtime_env_info.runtime_env_config.CopyFrom( + runtime_env_config.build_proto_runtime_env_config() + ) + + # Normally, `RuntimeEnv` should guarantee the accuracy of field eager_install, + # but so far, the internal code has not completely prohibited direct + # modification of fields in RuntimeEnv, so we should check it for insurance. + eager_install = ( + runtime_env_config.get("eager_install") + if runtime_env_config is not None + else None + ) + if is_job_runtime_env or eager_install is not None: + if eager_install is None: + eager_install = True + elif not isinstance(eager_install, bool): + raise TypeError( + f"eager_install must be a boolean. got {type(eager_install)}" + ) + proto_runtime_env_info.runtime_env_config.eager_install = eager_install + + proto_runtime_env_info.serialized_runtime_env = runtime_env.serialize() + + if not serialize: + return proto_runtime_env_info + + return json_format.MessageToJson(proto_runtime_env_info) + + +def parse_runtime_env_for_task_or_actor( + runtime_env: Optional[Union[Dict, "RuntimeEnv"]] +): + from ray.runtime_env import RuntimeEnv + from ray.runtime_env.runtime_env import _validate_no_local_paths + + # Parse local pip/conda config files here. If we instead did it in + # .remote(), it would get run in the Ray Client server, which runs on + # a remote node where the files aren't available. + if runtime_env: + if isinstance(runtime_env, dict): + runtime_env = RuntimeEnv(**(runtime_env or {})) + _validate_no_local_paths(runtime_env) + return runtime_env + raise TypeError( + "runtime_env must be dict or RuntimeEnv, ", + f"but got: {type(runtime_env)}", + ) + else: + # Keep the new_runtime_env as None. In .remote(), we need to know + # if runtime_env is None to know whether or not to fall back to the + # runtime_env specified in the @ray.remote decorator. + return None + + +def split_address(address: str) -> Tuple[str, str]: + """Splits address into a module string (scheme) and an inner_address. + + We use a custom splitting function instead of urllib because + PEP allows "underscores" in a module names, while URL schemes do not + allow them. + + Args: + address: The address to split. + + Returns: + A tuple of (scheme, inner_address). + + Raises: + ValueError: If the address does not contain '://'. + + Examples: + >>> split_address("ray://my_cluster") + ('ray', 'my_cluster') + """ + if "://" not in address: + raise ValueError("Address must contain '://'") + + module_string, inner_address = address.split("://", maxsplit=1) + return (module_string, inner_address) + + +def get_entrypoint_name(): + """Get the entrypoint of the current script.""" + prefix = "" + try: + curr = psutil.Process() + # Prepend `interactive_shell` for interactive shell scripts. + # https://stackoverflow.com/questions/2356399/tell-if-python-is-in-interactive-mode # noqa + if hasattr(sys, "ps1"): + prefix = "(interactive_shell) " + + return prefix + list2cmdline(curr.cmdline()) + except Exception: + return "unknown" + + +class DeferSigint(contextlib.AbstractContextManager): + """Context manager that defers SIGINT signals until the context is left.""" + + # This is used by Ray's task cancellation to defer cancellation interrupts during + # problematic areas, e.g. task argument deserialization. + def __init__(self): + # Whether a SIGINT signal was received during the context. + self.signal_received = False + # The overridden SIGINT handler + self.overridden_sigint_handler = None + # The original signal method. + self.orig_signal = None + + @classmethod + def create_if_main_thread(cls) -> contextlib.AbstractContextManager: + """Creates a DeferSigint context manager if running on the main thread, + returns a no-op context manager otherwise. + """ + if threading.current_thread() == threading.main_thread(): + return cls() + else: + return contextlib.nullcontext() + + def _set_signal_received(self, signum, frame): + """SIGINT handler that defers the signal.""" + self.signal_received = True + + def _signal_monkey_patch(self, signum, handler): + """Monkey patch for signal.signal that defers the setting of new signal + handler after the DeferSigint context exits.""" + # Only handle it in the main thread because if setting a handler in a non-main + # thread, signal.signal will raise an error because Python doesn't allow it. + if ( + threading.current_thread() == threading.main_thread() + and signum == signal.SIGINT + ): + orig_sigint_handler = self.overridden_sigint_handler + self.overridden_sigint_handler = handler + return orig_sigint_handler + return self.orig_signal(signum, handler) + + def __enter__(self): + # Save original SIGINT handler for later restoration. + self.overridden_sigint_handler = signal.getsignal(signal.SIGINT) + # Set SIGINT signal handler that defers the signal. + signal.signal(signal.SIGINT, self._set_signal_received) + # Monkey patch signal.signal to raise an error if a SIGINT handler is registered + # within the context. + self.orig_signal = signal.signal + signal.signal = self._signal_monkey_patch + return self + + def __exit__(self, exc_type, exc, exc_tb): + assert self.overridden_sigint_handler is not None + assert self.orig_signal is not None + # Restore original signal.signal function. + signal.signal = self.orig_signal + # Restore overridden SIGINT handler. + signal.signal(signal.SIGINT, self.overridden_sigint_handler) + if exc_type is None and self.signal_received: + # No exception raised in context, call the original SIGINT handler. + # By default, this means raising KeyboardInterrupt. + self.overridden_sigint_handler(signal.SIGINT, None) + else: + # If exception was raised in context, returning False will cause it to be + # reraised. + return False + + +def try_import_each_module(module_names_to_import: List[str]) -> None: + """ + Make a best-effort attempt to import each named Python module. + This is used by the Python default_worker.py to preload modules. + """ + for module_to_preload in module_names_to_import: + try: + importlib.import_module(module_to_preload) + except ImportError: + logger.exception(f'Failed to preload the module "{module_to_preload}"') + + +def remove_ray_internal_flags_from_env(env: dict): + """ + Remove Ray internal flags from `env`. + Defined in ray/common/ray_internal_flag_def.h + """ + for flag in ray_constants.RAY_INTERNAL_FLAGS: + env.pop(flag, None) + + +def update_envs(env_vars: Dict[str, str]): + """ + When updating the environment variable, if there is ${X}, + it will be replaced with the current environment variable. + """ + if not env_vars: + return + + for key, value in env_vars.items(): + expanded = os.path.expandvars(value) + # Replace non-existant env vars with an empty string. + result = re.sub(r"\$\{[A-Z0-9_]+\}", "", expanded) + os.environ[key] = result + + +def parse_pg_formatted_resources_to_original( + pg_formatted_resources: Dict[str, float] +) -> Dict[str, float]: + original_resources = {} + + for key, value in pg_formatted_resources.items(): + result = PLACEMENT_GROUP_INDEXED_BUNDLED_RESOURCE_PATTERN.match(key) + if result and len(result.groups()) == 3: + # Filter out resources that have bundle_group_[pg_id] since + # it is an implementation detail. + # This resource is automatically added to the resource + # request for all tasks that require placement groups. + if result.group(1) == PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME: + continue + + original_resources[result.group(1)] = value + continue + + result = PLACEMENT_GROUP_WILDCARD_RESOURCE_PATTERN.match(key) + if result and len(result.groups()) == 2: + if result.group(1) == "bundle": + continue + + original_resources[result.group(1)] = value + continue + original_resources[key] = value + + return original_resources + + +def validate_actor_state_name(actor_state_name): + if actor_state_name is None: + return + actor_state_names = [ + "DEPENDENCIES_UNREADY", + "PENDING_CREATION", + "ALIVE", + "RESTARTING", + "DEAD", + ] + if actor_state_name not in actor_state_names: + raise ValueError( + f'"{actor_state_name}" is not a valid actor state name, ' + 'it must be one of the following: "DEPENDENCIES_UNREADY", ' + '"PENDING_CREATION", "ALIVE", "RESTARTING", or "DEAD"' + ) + + +def get_current_node_cpu_model_name() -> Optional[str]: + if not sys.platform.startswith("linux"): + return None + + try: + """ + /proc/cpuinfo content example: + + processor : 0 + vendor_id : GenuineIntel + cpu family : 6 + model : 85 + model name : Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz + stepping : 7 + """ + with open("/proc/cpuinfo", "r") as f: + for line in f: + if line.startswith("model name"): + return line.split(":")[1].strip() + return None + except Exception: + logger.debug("Failed to get CPU model name", exc_info=True) + return None + + +def validate_socket_filepath(filepath: str): + """ + Validate the provided filename is a valid Unix socket filename. + """ + # Don't check for Windows as it doesn't support Unix sockets. + if sys.platform == "win32": + return + is_mac = sys.platform.startswith("darwin") + maxlen = (104 if is_mac else 108) - 1 + if len(filepath.encode("utf-8")) > maxlen: + raise OSError( + f"validate_socket_filename failed: AF_UNIX path length cannot exceed {maxlen} bytes: {filepath}" + ) + + +# Whether we're currently running in a test, either local or CI. +in_test = None + + +def is_in_test(): + global in_test + + if in_test is None: + in_test = any( + env_var in os.environ + # These environment variables are always set by pytest and Buildkite, + # respectively. + for env_var in ("PYTEST_CURRENT_TEST", "BUILDKITE") + ) + return in_test diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/worker.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/worker.py new file mode 100644 index 0000000000000000000000000000000000000000..08e5f33098a113a387ebab8214456fbebe27252d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/worker.py @@ -0,0 +1,3665 @@ +import atexit +import faulthandler +import functools +import inspect +import io +import json +import logging +import os +import sys +import threading +import time +import traceback +import urllib +import warnings +from abc import ABCMeta, abstractmethod +from collections.abc import Mapping +from contextlib import contextmanager +from dataclasses import dataclass +from typing import ( + TYPE_CHECKING, + Any, + AnyStr, + Callable, + Dict, + Generic, + Iterator, + List, + Literal, + Optional, + Protocol, + Sequence, + Tuple, + Type, + TypeVar, + Union, + overload, +) +from urllib.parse import urlparse + +import colorama + +import ray +import ray._private.node +import ray._private.parameter +import ray._private.profiling as profiling +import ray._private.ray_constants as ray_constants +import ray._private.serialization as serialization +import ray._private.services as services +import ray._private.state +import ray._private.worker + +# Ray modules +import ray.actor +import ray.cloudpickle as pickle # noqa +import ray.job_config +import ray.remote_function +from ray import ActorID, JobID, Language, ObjectRef +from ray._common.utils import load_class +from ray._private import ray_option_utils +from ray._private.client_mode_hook import client_mode_hook +from ray._private.function_manager import FunctionActorManager +from ray._private.inspect_util import is_cython +from ray._private.ray_logging import ( + global_worker_stdstream_dispatcher, + setup_logger, + stderr_deduplicator, + stdout_deduplicator, +) +from ray._private.ray_logging.logging_config import LoggingConfig +from ray._private.resource_isolation_config import ResourceIsolationConfig +from ray._private.runtime_env.constants import RAY_JOB_CONFIG_JSON_ENV_VAR +from ray._private.runtime_env.py_modules import upload_py_modules_if_needed +from ray._private.runtime_env.setup_hook import ( + upload_worker_process_setup_hook_if_needed, +) +from ray._private.runtime_env.working_dir import upload_working_dir_if_needed +from ray._private.utils import get_ray_doc_version +from ray._raylet import ( + ObjectRefGenerator, + TaskID, + raise_sys_exit_with_custom_error_message, +) +from ray.actor import ActorClass +from ray.exceptions import ObjectStoreFullError, RayError, RaySystemError, RayTaskError +from ray.experimental import tqdm_ray +from ray.experimental.compiled_dag_ref import CompiledDAGRef +from ray.experimental.internal_kv import ( + _initialize_internal_kv, + _internal_kv_get, + _internal_kv_initialized, + _internal_kv_reset, +) +from ray.experimental.tqdm_ray import RAY_TQDM_MAGIC +from ray.runtime_env.runtime_env import _merge_runtime_env +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI +from ray.util.debug import log_once +from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy +from ray.util.tracing.tracing_helper import _import_from_string +from ray.widgets import Template +from ray.widgets.util import repr_with_fallback + +if TYPE_CHECKING: + pass + +SCRIPT_MODE = 0 +WORKER_MODE = 1 +LOCAL_MODE = 2 +SPILL_WORKER_MODE = 3 +RESTORE_WORKER_MODE = 4 + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) + + +T = TypeVar("T") +T0 = TypeVar("T0") +T1 = TypeVar("T1") +T2 = TypeVar("T2") +T3 = TypeVar("T3") +T4 = TypeVar("T4") +T5 = TypeVar("T5") +T6 = TypeVar("T6") +T7 = TypeVar("T7") +T8 = TypeVar("T8") +T9 = TypeVar("T9") +R = TypeVar("R") + +DAGNode = TypeVar("DAGNode") + + +# Only used for type annotations as a placeholder +Undefined: Any = object() + + +# TypeVar for self-referential generics in `RemoteFunction[N]`. +RF = TypeVar("RF", bound="HasOptions") + + +class HasOptions(Protocol): + def options(self: RF, **task_options) -> RF: + ... + + +class RemoteFunctionNoArgs(HasOptions, Generic[R]): + def __init__(self, function: Callable[[], R]) -> None: + pass + + def remote( + self, + ) -> "ObjectRef[R]": + ... + + def bind( + self, + ) -> "DAGNode[R]": + ... + + +class RemoteFunction0(HasOptions, Generic[R, T0]): + def __init__(self, function: Callable[[T0], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction1(HasOptions, Generic[R, T0, T1]): + def __init__(self, function: Callable[[T0, T1], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction2(HasOptions, Generic[R, T0, T1, T2]): + def __init__(self, function: Callable[[T0, T1, T2], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction3(HasOptions, Generic[R, T0, T1, T2, T3]): + def __init__(self, function: Callable[[T0, T1, T2, T3], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + __arg3: "Union[T3, ObjectRef[T3]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + __arg3: "Union[T3, DAGNode[T3]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction4(HasOptions, Generic[R, T0, T1, T2, T3, T4]): + def __init__(self, function: Callable[[T0, T1, T2, T3, T4], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + __arg3: "Union[T3, ObjectRef[T3]]", + __arg4: "Union[T4, ObjectRef[T4]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + __arg3: "Union[T3, DAGNode[T3]]", + __arg4: "Union[T4, DAGNode[T4]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction5(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5]): + def __init__(self, function: Callable[[T0, T1, T2, T3, T4, T5], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + __arg3: "Union[T3, ObjectRef[T3]]", + __arg4: "Union[T4, ObjectRef[T4]]", + __arg5: "Union[T5, ObjectRef[T5]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + __arg3: "Union[T3, DAGNode[T3]]", + __arg4: "Union[T4, DAGNode[T4]]", + __arg5: "Union[T5, DAGNode[T5]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction6(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5, T6]): + def __init__(self, function: Callable[[T0, T1, T2, T3, T4, T5, T6], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + __arg3: "Union[T3, ObjectRef[T3]]", + __arg4: "Union[T4, ObjectRef[T4]]", + __arg5: "Union[T5, ObjectRef[T5]]", + __arg6: "Union[T6, ObjectRef[T6]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + __arg3: "Union[T3, DAGNode[T3]]", + __arg4: "Union[T4, DAGNode[T4]]", + __arg5: "Union[T5, DAGNode[T5]]", + __arg6: "Union[T6, DAGNode[T6]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction7(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5, T6, T7]): + def __init__(self, function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7], R]) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + __arg3: "Union[T3, ObjectRef[T3]]", + __arg4: "Union[T4, ObjectRef[T4]]", + __arg5: "Union[T5, ObjectRef[T5]]", + __arg6: "Union[T6, ObjectRef[T6]]", + __arg7: "Union[T7, ObjectRef[T7]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + __arg3: "Union[T3, DAGNode[T3]]", + __arg4: "Union[T4, DAGNode[T4]]", + __arg5: "Union[T5, DAGNode[T5]]", + __arg6: "Union[T6, DAGNode[T6]]", + __arg7: "Union[T7, DAGNode[T7]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction8(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5, T6, T7, T8]): + def __init__( + self, function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8], R] + ) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + __arg3: "Union[T3, ObjectRef[T3]]", + __arg4: "Union[T4, ObjectRef[T4]]", + __arg5: "Union[T5, ObjectRef[T5]]", + __arg6: "Union[T6, ObjectRef[T6]]", + __arg7: "Union[T7, ObjectRef[T7]]", + __arg8: "Union[T8, ObjectRef[T8]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + __arg3: "Union[T3, DAGNode[T3]]", + __arg4: "Union[T4, DAGNode[T4]]", + __arg5: "Union[T5, DAGNode[T5]]", + __arg6: "Union[T6, DAGNode[T6]]", + __arg7: "Union[T7, DAGNode[T7]]", + __arg8: "Union[T8, DAGNode[T8]]", + ) -> "DAGNode[R]": + ... + + +class RemoteFunction9(HasOptions, Generic[R, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]): + def __init__( + self, function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9], R] + ) -> None: + pass + + def remote( + self, + __arg0: "Union[T0, ObjectRef[T0]]", + __arg1: "Union[T1, ObjectRef[T1]]", + __arg2: "Union[T2, ObjectRef[T2]]", + __arg3: "Union[T3, ObjectRef[T3]]", + __arg4: "Union[T4, ObjectRef[T4]]", + __arg5: "Union[T5, ObjectRef[T5]]", + __arg6: "Union[T6, ObjectRef[T6]]", + __arg7: "Union[T7, ObjectRef[T7]]", + __arg8: "Union[T8, ObjectRef[T8]]", + __arg9: "Union[T9, ObjectRef[T9]]", + ) -> "ObjectRef[R]": + ... + + def bind( + self, + __arg0: "Union[T0, DAGNode[T0]]", + __arg1: "Union[T1, DAGNode[T1]]", + __arg2: "Union[T2, DAGNode[T2]]", + __arg3: "Union[T3, DAGNode[T3]]", + __arg4: "Union[T4, DAGNode[T4]]", + __arg5: "Union[T5, DAGNode[T5]]", + __arg6: "Union[T6, DAGNode[T6]]", + __arg7: "Union[T7, DAGNode[T7]]", + __arg8: "Union[T8, DAGNode[T8]]", + __arg9: "Union[T9, DAGNode[T9]]", + ) -> "DAGNode[R]": + ... + + +# Visible for testing. +def _unhandled_error_handler(e: Exception): + logger.error( + f"Unhandled error (suppress with 'RAY_IGNORE_UNHANDLED_ERRORS=1'): {e}" + ) + + +class Worker: + """A class used to define the control flow of a worker process. + + Note: + The methods in this class are considered unexposed to the user. The + functions outside of this class are considered exposed. + + Attributes: + node (ray._private.node.Node): The node this worker is attached to. + mode: The mode of the worker. One of SCRIPT_MODE, LOCAL_MODE, and + WORKER_MODE. + """ + + def __init__(self): + """Initialize a Worker object.""" + self.node = None + self.mode = None + self.actors = {} + # GPU object manager to manage GPU object lifecycles, including coordinating out-of-band + # tensor transfers between actors, storing and retrieving GPU objects, and garbage collection. + # We create the GPU object manager lazily, if a user specifies a + # non-default tensor_transport, to avoid circular import and because it + # imports third-party dependencies like PyTorch. + self._gpu_object_manager = None + # When the worker is constructed. Record the original value of the + # (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, HIP_VISIBLE_DEVICES, + # NEURON_RT_VISIBLE_CORES, TPU_VISIBLE_CHIPS, ..) environment variables. + self.original_visible_accelerator_ids = ( + ray._private.utils.get_visible_accelerator_ids() + ) + # A dictionary that maps from driver id to SerializationContext + # TODO: clean up the SerializationContext once the job finished. + self.serialization_context_map = {} + self.function_actor_manager = FunctionActorManager(self) + # This event is checked regularly by all of the threads so that they + # know when to exit. + self.threads_stopped = threading.Event() + # If this is set, the next .remote call should drop into the + # debugger, at the specified breakpoint ID. + self.debugger_breakpoint = b"" + # If this is set, ray.get calls invoked on the object ID returned + # by the worker should drop into the debugger at the specified + # breakpoint ID. + self.debugger_get_breakpoint = b"" + # If True, make the debugger external to the node this worker is + # running on. + self.ray_debugger_external = False + self._load_code_from_local = False + # Opened file descriptor to stdout/stderr for this python worker. + self._enable_record_actor_task_log = ( + ray_constants.RAY_ENABLE_RECORD_ACTOR_TASK_LOGGING + ) + # Whether rotation is enabled for out file and err file, task log position report will be skipped if rotation enabled, since the position cannot be accurate. + self._file_rotation_enabled = False + self._out_filepath = None + self._err_filepath = None + # Create the lock here because the serializer will use it before + # initializing Ray. + self.lock = threading.RLock() + # By default, don't show logs from other drivers. This is set to true by Serve + # in order to stream logs from the controller and replica actors across + # different drivers that connect to the same Serve instance. + # See https://github.com/ray-project/ray/pull/35070. + self._filter_logs_by_job = True + # the debugger port for this worker + self._debugger_port = None + # Cache the job id from initialize_job_config() to optimize lookups. + # This is on the critical path of ray.get()/put() calls. + self._cached_job_id = None + # Indicates whether the worker is connected to the Ray cluster. + # It should be set to True in `connect` and False in `disconnect`. + self._is_connected: bool = False + + @property + def gpu_object_manager(self) -> "ray.experimental.GPUObjectManager": + if self._gpu_object_manager is None: + # We create the GPU object manager lazily, if a user specifies a + # non-default tensor_transport, to avoid circular import and because it + # imports third-party dependencies like PyTorch. + from ray.experimental import GPUObjectManager + + self._gpu_object_manager = GPUObjectManager() + return self._gpu_object_manager + + @property + def connected(self): + """bool: True if Ray has been started and False otherwise.""" + return self._is_connected + + def set_is_connected(self, is_connected: bool): + self._is_connected = is_connected + + @property + def node_ip_address(self): + self.check_connected() + return self.node.node_ip_address + + @property + def load_code_from_local(self): + self.check_connected() + return self._load_code_from_local + + @property + def current_job_id(self): + if self._cached_job_id is not None: + return self._cached_job_id + elif hasattr(self, "core_worker"): + return self.core_worker.get_current_job_id() + return JobID.nil() + + @property + def actor_id(self): + if hasattr(self, "core_worker"): + return self.core_worker.get_actor_id() + return ActorID.nil() + + @property + def actor_name(self): + if hasattr(self, "core_worker"): + return self.core_worker.get_actor_name().decode("utf-8") + return None + + @property + def current_task_id(self): + return self.core_worker.get_current_task_id() + + @property + def current_task_name(self): + return self.core_worker.get_current_task_name() + + @property + def current_task_function_name(self): + return self.core_worker.get_current_task_function_name() + + @property + def current_node_id(self): + return self.core_worker.get_current_node_id() + + @property + def task_depth(self): + return self.core_worker.get_task_depth() + + @property + def namespace(self): + return self.core_worker.get_job_config().ray_namespace + + @property + def placement_group_id(self): + return self.core_worker.get_placement_group_id() + + @property + def worker_id(self): + return self.core_worker.get_worker_id().binary() + + @property + def should_capture_child_tasks_in_placement_group(self): + return self.core_worker.should_capture_child_tasks_in_placement_group() + + @property + def current_cluster_and_job(self): + """Get the current session index and job id as pair.""" + assert isinstance(self.node.cluster_id, ray.ClusterID) + assert isinstance(self.current_job_id, ray.JobID) + return self.node.cluster_id, self.current_job_id + + @property + def runtime_env(self): + """Get the runtime env in json format""" + return self.core_worker.get_current_runtime_env() + + @property + def debugger_port(self): + """Get the debugger port for this worker""" + worker_id = self.core_worker.get_worker_id() + return ray._private.state.get_worker_debugger_port(worker_id) + + @property + def job_logging_config(self): + """Get the job's logging config for this worker""" + if not hasattr(self, "core_worker"): + return None + job_config = self.core_worker.get_job_config() + if not job_config.serialized_py_logging_config: + return None + logging_config = pickle.loads(job_config.serialized_py_logging_config) + return logging_config + + @property + def current_node_labels(self): + # Return the node labels of this worker's current node. + return self.node.node_labels + + def set_debugger_port(self, port): + worker_id = self.core_worker.get_worker_id() + ray._private.state.update_worker_debugger_port(worker_id, port) + + def set_cached_job_id(self, job_id): + """Set the cached job id to speed `current_job_id()`.""" + self._cached_job_id = job_id + + @contextmanager + def task_paused_by_debugger(self): + """Use while the task is paused by debugger""" + try: + self.core_worker.update_task_is_debugger_paused( + ray.get_runtime_context()._get_current_task_id(), True + ) + yield + finally: + self.core_worker.update_task_is_debugger_paused( + ray.get_runtime_context()._get_current_task_id(), False + ) + + @contextmanager + def worker_paused_by_debugger(self): + """ + Updates the worker num paused threads when the worker is paused by debugger + """ + try: + worker_id = self.core_worker.get_worker_id() + ray._private.state.update_worker_num_paused_threads(worker_id, 1) + yield + finally: + ray._private.state.update_worker_num_paused_threads(worker_id, -1) + + def set_file_rotation_enabled(self, rotation_enabled: bool) -> None: + """Set whether rotation is enabled for outfile and errfile.""" + self._file_rotation_enabled = rotation_enabled + + def set_err_file(self, err_filepath=Optional[AnyStr]) -> None: + """Set the worker's err file where stderr is redirected to""" + self._err_filepath = err_filepath + + def set_out_file(self, out_filepath=Optional[AnyStr]) -> None: + """Set the worker's out file where stdout is redirected to""" + self._out_filepath = out_filepath + + def record_task_log_start(self, task_id: TaskID, attempt_number: int): + """Record the task log info when task starts executing for + non concurrent actor tasks.""" + if not self._enable_record_actor_task_log and not self.actor_id.is_nil(): + # We are not recording actor task log if not enabled explicitly. + # Recording actor task log is expensive and should be enabled only + # when needed. + # https://github.com/ray-project/ray/issues/35598 + return + + if not hasattr(self, "core_worker"): + return + if self._file_rotation_enabled: + return + + self.core_worker.record_task_log_start( + task_id, + attempt_number, + self.get_out_file_path(), + self.get_err_file_path(), + self.get_current_out_offset(), + self.get_current_err_offset(), + ) + + def record_task_log_end(self, task_id: TaskID, attempt_number: int): + """Record the task log info when task finishes executing for + non concurrent actor tasks.""" + if not self._enable_record_actor_task_log and not self.actor_id.is_nil(): + # We are not recording actor task log if not enabled explicitly. + # Recording actor task log is expensive and should be enabled only + # when needed. + # https://github.com/ray-project/ray/issues/35598 + return + + if not hasattr(self, "core_worker"): + return + + # Disable file offset fetch if rotation enabled (since file offset doesn't make sense for rotated files). + if self._file_rotation_enabled: + return + + self.core_worker.record_task_log_end( + task_id, + attempt_number, + self.get_current_out_offset(), + self.get_current_err_offset(), + ) + + def get_out_file_path(self) -> str: + """Get the out log file path""" + return self._out_filepath if self._out_filepath is not None else "" + + def get_err_file_path(self) -> str: + """Get the err log file path""" + return self._err_filepath if self._err_filepath is not None else "" + + def get_current_out_offset(self) -> int: + """Get the current offset of the out file if seekable, else 0""" + if self._out_filepath is not None: + return os.path.getsize(self._out_filepath) + return 0 + + def get_current_err_offset(self) -> int: + """Get the current offset of the err file if seekable, else 0""" + if self._err_filepath is not None: + return os.path.getsize(self._err_filepath) + return 0 + + def get_serialization_context(self): + """Get the SerializationContext of the job that this worker is processing. + + Returns: + The serialization context of the given job. + """ + # This function needs to be protected by a lock, because it will be + # called by`register_class_for_serialization`, as well as the import + # thread, from different threads. Also, this function will recursively + # call itself, so we use RLock here. + job_id = self.current_job_id + context_map = self.serialization_context_map + with self.lock: + if job_id not in context_map: + # The job ID is nil before initializing Ray. + if JobID.nil() in context_map: + # Transfer the serializer context used before initializing Ray. + context_map[job_id] = context_map.pop(JobID.nil()) + else: + context_map[job_id] = serialization.SerializationContext(self) + return context_map[job_id] + + def check_connected(self): + """Check if the worker is connected. + + Raises: + Exception: An exception is raised if the worker is not connected. + """ + if not self.connected: + raise RaySystemError( + "Ray has not been started yet. You can start Ray with 'ray.init()'." + ) + + def set_mode(self, mode): + """Set the mode of the worker. + + The mode SCRIPT_MODE should be used if this Worker is a driver that is + being run as a Python script or interactively in a shell. It will print + information about task failures. + + The mode WORKER_MODE should be used if this Worker is not a driver. It + will not print information about tasks. + + The mode LOCAL_MODE should be used if this Worker is a driver and if + you want to run the driver in a manner equivalent to serial Python for + debugging purposes. It will not send remote function calls to the + scheduler and will instead execute them in a blocking fashion. + + Args: + mode: One of SCRIPT_MODE, WORKER_MODE, and LOCAL_MODE. + """ + self.mode = mode + + def set_load_code_from_local(self, load_code_from_local): + self._load_code_from_local = load_code_from_local + + def put_object( + self, + value: Any, + object_ref: Optional["ray.ObjectRef"] = None, + owner_address: Optional[str] = None, + _is_experimental_channel: bool = False, + ): + """Put value in the local object store with object reference `object_ref`. + + This assumes that the value for `object_ref` has not yet been placed in + the local object store. If the plasma store is full, the worker will + automatically retry up to DEFAULT_PUT_OBJECT_RETRIES times. Each + retry will delay for an exponentially doubling amount of time, + starting with DEFAULT_PUT_OBJECT_DELAY. After this, exception + will be raised. + + Args: + value: The value to put in the object store. + object_ref: The object ref of the value to be + put. If None, one will be generated. + owner_address: The serialized address of object's owner. + _is_experimental_channel: An experimental flag for mutable + objects. If True, then the returned object will not have a + valid value. The object must be written to using the + ray.experimental.channel API before readers can read. + + Returns: + ObjectRef: The object ref the object was put under. + + Raises: + ray.exceptions.ObjectStoreFullError: This is raised if the attempt + to store the object fails because the object store is full even + after multiple retries. + """ + # Make sure that the value is not an object ref. + if isinstance(value, ObjectRef): + raise TypeError( + "Calling 'put' on an ray.ObjectRef is not allowed. " + "If you really want to do this, you can wrap the " + "ray.ObjectRef in a list and call 'put' on it." + ) + + if self.mode == LOCAL_MODE: + assert ( + object_ref is None + ), "Local Mode does not support inserting with an ObjectRef" + + try: + serialized_value = self.get_serialization_context().serialize(value) + except TypeError as e: + sio = io.StringIO() + ray.util.inspect_serializability(value, print_file=sio) + msg = ( + "Could not serialize the put value " + f"{repr(value)}:\n" + f"{sio.getvalue()}" + ) + raise TypeError(msg) from e + + # If the object is mutable, then the raylet should never read the + # object. Instead, clients will keep the object pinned. + pin_object = not _is_experimental_channel + + # This *must* be the first place that we construct this python + # ObjectRef because an entry with 0 local references is created when + # the object is Put() in the core worker, expecting that this python + # reference will be created. If another reference is created and + # removed before this one, it will corrupt the state in the + # reference counter. + return ray.ObjectRef( + self.core_worker.put_serialized_object_and_increment_local_ref( + serialized_value, + object_ref=object_ref, + pin_object=pin_object, + owner_address=owner_address, + _is_experimental_channel=_is_experimental_channel, + ), + # The initial local reference is already acquired internally. + skip_adding_local_ref=True, + ) + + def raise_errors(self, serialized_objects, object_refs): + out = self.deserialize_objects(serialized_objects, object_refs) + if "RAY_IGNORE_UNHANDLED_ERRORS" in os.environ: + return + for e in out: + _unhandled_error_handler(e) + + def deserialize_objects(self, serialized_objects, object_refs): + # Function actor manager or the import thread may call pickle.loads + # at the same time which can lead to failed imports + # TODO: We may be better off locking on all imports or injecting a lock + # into pickle.loads (https://github.com/ray-project/ray/issues/16304) + with self.function_actor_manager.lock: + context = self.get_serialization_context() + return context.deserialize_objects(serialized_objects, object_refs) + + def get_objects( + self, + object_refs: list, + timeout: Optional[float] = None, + return_exceptions: bool = False, + skip_deserialization: bool = False, + ) -> Tuple[List[serialization.SerializedRayObject], bytes]: + """Get the values in the object store associated with the IDs. + + Return the values from the local object store for object_refs. This + will block until all the values for object_refs have been written to + the local object store. + + Args: + object_refs: A list of the object refs + whose values should be retrieved. + timeout: The maximum amount of time in + seconds to wait before returning. + return_exceptions: If any of the objects deserialize to an + Exception object, whether to return them as values in the + returned list. If False, then the first found exception will be + raised. + skip_deserialization: If true, only the buffer will be released and + the object associated with the buffer will not be deserialized. + Returns: + list: List of deserialized objects or None if skip_deserialization is True. + bytes: UUID of the debugger breakpoint we should drop + into or b"" if there is no breakpoint. + """ + # Make sure that the values are object refs. + for object_ref in object_refs: + if not isinstance(object_ref, ObjectRef): + raise TypeError( + f"Attempting to call `get` on the value {object_ref}, " + "which is not an ray.ObjectRef." + ) + + timeout_ms = ( + int(timeout * 1000) if timeout is not None and timeout != -1 else -1 + ) + serialized_objects: List[ + serialization.SerializedRayObject + ] = self.core_worker.get_objects( + object_refs, + timeout_ms, + ) + + debugger_breakpoint = b"" + for data, metadata, _ in serialized_objects: + if metadata: + metadata_fields = metadata.split(b",") + if len(metadata_fields) >= 2 and metadata_fields[1].startswith( + ray_constants.OBJECT_METADATA_DEBUG_PREFIX + ): + debugger_breakpoint = metadata_fields[1][ + len(ray_constants.OBJECT_METADATA_DEBUG_PREFIX) : + ] + if skip_deserialization: + return None, debugger_breakpoint + + values = self.deserialize_objects(serialized_objects, object_refs) + if not return_exceptions: + # Raise exceptions instead of returning them to the user. + for i, value in enumerate(values): + if isinstance(value, RayError): + if isinstance(value, ray.exceptions.ObjectLostError): + global_worker.core_worker.dump_object_store_memory_usage() + if isinstance(value, RayTaskError): + raise value.as_instanceof_cause() + else: + raise value + + return values, debugger_breakpoint + + def main_loop(self): + """The main loop a worker runs to receive and execute tasks.""" + + def sigterm_handler(signum, frame): + raise_sys_exit_with_custom_error_message( + "The process receives a SIGTERM.", exit_code=1 + ) + # Note: shutdown() function is called from atexit handler. + + ray._private.utils.set_sigterm_handler(sigterm_handler) + self.core_worker.run_task_loop() + sys.exit(0) + + def print_logs(self): + """Prints log messages from workers on all nodes in the same job.""" + subscriber = self.gcs_log_subscriber + subscriber.subscribe() + exception_type = ray.exceptions.RpcError + localhost = services.get_node_ip_address() + try: + # Number of messages received from the last polling. When the batch + # size exceeds 100 and keeps increasing, the worker and the user + # probably will not be able to consume the log messages as rapidly + # as they are coming in. + # This is meaningful only for GCS subscriber. + last_polling_batch_size = 0 + job_id_hex = self.current_job_id.hex() + while True: + # Exit if we received a signal that we should stop. + if self.threads_stopped.is_set(): + return + + data = subscriber.poll() + # GCS subscriber only returns None on unavailability. + if data is None: + last_polling_batch_size = 0 + continue + + if ( + self._filter_logs_by_job + and data["job"] + and data["job"] != job_id_hex + ): + last_polling_batch_size = 0 + continue + + data["localhost"] = localhost + global_worker_stdstream_dispatcher.emit(data) + + lagging = 100 <= last_polling_batch_size < subscriber.last_batch_size + if lagging: + logger.warning( + "The driver may not be able to keep up with the " + "stdout/stderr of the workers. To avoid forwarding " + "logs to the driver, use " + "'ray.init(log_to_driver=False)'." + ) + + last_polling_batch_size = subscriber.last_batch_size + + except (OSError, exception_type) as e: + logger.error(f"print_logs: {e}") + finally: + # Close the pubsub client to avoid leaking file descriptors. + subscriber.close() + + def get_accelerator_ids_for_accelerator_resource( + self, resource_name: str, resource_regex: str + ) -> Union[List[str], List[int]]: + """Get the accelerator IDs that are assigned to the given accelerator resource. + + Args: + resource_name: The name of the resource. + resource_regex: The regex of the resource. + + Returns: + (List[str]) The IDs that are assigned to the given resource pre-configured. + (List[int]) The IDs that are assigned to the given resource. + """ + resource_ids = self.core_worker.resource_ids() + assigned_ids = set() + # Handle both normal and placement group accelerator resources. + # Note: We should only get the accelerator ids from the placement + # group resource that does not contain the bundle index! + import re + + for resource, assignment in resource_ids.items(): + if resource == resource_name or re.match(resource_regex, resource): + for resource_id, _ in assignment: + assigned_ids.add(resource_id) + + # If the user had already set the environment variables + # (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, NEURON_RT_VISIBLE_CORES, + # TPU_VISIBLE_CHIPS, ..) then respect that in the sense that only IDs + # that appear in (CUDA_VISIBLE_DEVICES, ONEAPI_DEVICE_SELECTOR, + # HIP_VISIBLE_DEVICES, NEURON_RT_VISIBLE_CORES, TPU_VISIBLE_CHIPS, ..) + # should be returned. + if self.original_visible_accelerator_ids.get(resource_name, None) is not None: + original_ids = self.original_visible_accelerator_ids[resource_name] + assigned_ids = {str(original_ids[i]) for i in assigned_ids} + # Give all accelerator ids in local_mode. + if self.mode == LOCAL_MODE: + if resource_name == ray_constants.GPU: + max_accelerators = self.node.get_resource_spec().num_gpus + else: + max_accelerators = self.node.get_resource_spec().resources.get( + resource_name, None + ) + if max_accelerators: + assigned_ids = original_ids[:max_accelerators] + return list(assigned_ids) + + +@PublicAPI +@client_mode_hook +def get_gpu_ids() -> Union[List[int], List[str]]: + """Get the IDs of the GPUs that are available to the worker. + + This method should only be called inside of a task or actor, and not a driver. + + If the CUDA_VISIBLE_DEVICES environment variable was set when the worker + started up, then the IDs returned by this method will be a subset of the + IDs in CUDA_VISIBLE_DEVICES. If not, the IDs will fall in the range + [0, NUM_GPUS - 1], where NUM_GPUS is the number of GPUs that the node has. + + Returns: + A list of GPU IDs. + """ + worker = global_worker + worker.check_connected() + return worker.get_accelerator_ids_for_accelerator_resource( + ray_constants.GPU, f"^{ray_constants.GPU}_group_[0-9A-Za-z]+$" + ) + + +@Deprecated( + message="Use ray.get_runtime_context().get_assigned_resources() instead.", + warning=True, +) +def get_resource_ids(): + """Get the IDs of the resources that are available to the worker. + + Returns: + A dictionary mapping the name of a resource to a list of pairs, where + each pair consists of the ID of a resource and the fraction of that + resource reserved for this worker. + """ + worker = global_worker + worker.check_connected() + + if _mode() == LOCAL_MODE: + raise RuntimeError( + "ray._private.worker.get_resource_ids() does not work in local_mode." + ) + + return global_worker.core_worker.resource_ids() + + +@Deprecated(message="Use ray.init().address_info['webui_url'] instead.") +def get_dashboard_url(): + """Get the URL to access the Ray dashboard. + + Note that the URL does not specify which node the dashboard is on. + + Returns: + The URL of the dashboard as a string. + """ + if ray_constants.RAY_OVERRIDE_DASHBOARD_URL in os.environ: + return _remove_protocol_from_url( + os.environ.get(ray_constants.RAY_OVERRIDE_DASHBOARD_URL) + ) + else: + worker = global_worker + worker.check_connected() + return _global_node.webui_url + + +def _remove_protocol_from_url(url: Optional[str]) -> str: + """ + Helper function to remove protocol from URL if it exists. + """ + if not url: + return url + parsed_url = urllib.parse.urlparse(url) + if parsed_url.scheme: + # Construct URL without protocol + scheme = f"{parsed_url.scheme}://" + return parsed_url.geturl().replace(scheme, "", 1) + return url + + +class BaseContext(metaclass=ABCMeta): + """ + Base class for RayContext and ClientContext + """ + + dashboard_url: Optional[str] + python_version: str + ray_version: str + + @abstractmethod + def disconnect(self): + """ + If this context is for directly attaching to a cluster, disconnect + will call ray.shutdown(). Otherwise, if the context is for a ray + client connection, the client will be disconnected. + """ + pass + + @abstractmethod + def __enter__(self): + pass + + @abstractmethod + def __exit__(self): + pass + + def _context_table_template(self): + if self.dashboard_url: + dashboard_row = Template("context_dashrow.html.j2").render( + dashboard_url="http://" + self.dashboard_url + ) + else: + dashboard_row = None + + return Template("context_table.html.j2").render( + python_version=self.python_version, + ray_version=self.ray_version, + dashboard_row=dashboard_row, + ) + + def _repr_html_(self): + return Template("context.html.j2").render( + context_logo=Template("context_logo.html.j2").render(), + context_table=self._context_table_template(), + ) + + @repr_with_fallback(["ipywidgets", "8"]) + def _get_widget_bundle(self, **kwargs) -> Dict[str, Any]: + """Get the mimebundle for the widget representation of the context. + + Args: + **kwargs: Passed to the _repr_mimebundle_() function for the widget + + Returns: + Dictionary ("mimebundle") of the widget representation of the context. + """ + import ipywidgets + + disconnect_button = ipywidgets.Button( + description="Disconnect", + disabled=False, + button_style="", + tooltip="Disconnect from the Ray cluster", + layout=ipywidgets.Layout(margin="auto 0px 0px 0px"), + ) + + def disconnect_callback(button): + button.disabled = True + button.description = "Disconnecting..." + self.disconnect() + button.description = "Disconnected" + + disconnect_button.on_click(disconnect_callback) + left_content = ipywidgets.VBox( + [ + ipywidgets.HTML(Template("context_logo.html.j2").render()), + disconnect_button, + ], + layout=ipywidgets.Layout(), + ) + right_content = ipywidgets.HTML(self._context_table_template()) + widget = ipywidgets.HBox( + [left_content, right_content], layout=ipywidgets.Layout(width="100%") + ) + return widget._repr_mimebundle_(**kwargs) + + def _repr_mimebundle_(self, **kwargs): + bundle = self._get_widget_bundle(**kwargs) + + # Overwrite the widget html repr and default repr with those of the BaseContext + bundle.update({"text/html": self._repr_html_(), "text/plain": repr(self)}) + return bundle + + +@dataclass +class RayContext(BaseContext, Mapping): + """ + Context manager for attached drivers. + """ + + dashboard_url: Optional[str] + python_version: str + ray_version: str + ray_commit: str + + def __init__(self, address_info: Dict[str, Optional[str]]): + super().__init__() + self.dashboard_url = get_dashboard_url() + self.python_version = "{}.{}.{}".format(*sys.version_info[:3]) + self.ray_version = ray.__version__ + self.ray_commit = ray.__commit__ + self.address_info = address_info + + def __getitem__(self, key): + if log_once("ray_context_getitem"): + warnings.warn( + f'Accessing values through ctx["{key}"] is deprecated. ' + f'Use ctx.address_info["{key}"] instead.', + DeprecationWarning, + stacklevel=2, + ) + return self.address_info[key] + + def __len__(self): + if log_once("ray_context_len"): + warnings.warn("len(ctx) is deprecated. Use len(ctx.address_info) instead.") + return len(self.address_info) + + def __iter__(self): + if log_once("ray_context_len"): + warnings.warn( + "iter(ctx) is deprecated. Use iter(ctx.address_info) instead." + ) + return iter(self.address_info) + + def __enter__(self) -> "RayContext": + return self + + def __exit__(self, *exc): + ray.shutdown() + + def disconnect(self): + # Include disconnect() to stay consistent with ClientContext + ray.shutdown() + + +global_worker = Worker() +"""Worker: The global Worker object for this worker process. + +We use a global Worker object to ensure that there is a single worker object +per worker process. +""" + +_global_node = None +"""ray._private.node.Node: The global node object that is created by ray.init().""" + + +def _maybe_modify_runtime_env( + runtime_env: Optional[Dict[str, Any]], _skip_env_hook: bool +) -> Dict[str, Any]: + """ + If you set RAY_ENABLE_UV_RUN_RUNTIME_ENV, which is the default, and run the driver with `uv run`, + this function sets up a runtime environment that replicates the driver's environment to the + workers. Otherwise, if a runtime environment hook is present it will modify the runtime environment. + """ + + if ray_constants.RAY_ENABLE_UV_RUN_RUNTIME_ENV: + from ray._private.runtime_env.uv_runtime_env_hook import ( + _get_uv_run_cmdline, + hook, + ) + + cmdline = _get_uv_run_cmdline() + if cmdline: + # This means the current driver is running in `uv run`, in which case we want + # to propagate the uv environment to the workers. + return hook(runtime_env) + + if ray_constants.RAY_RUNTIME_ENV_HOOK in os.environ and not _skip_env_hook: + return load_class(os.environ[ray_constants.RAY_RUNTIME_ENV_HOOK])(runtime_env) + + return runtime_env + + +@PublicAPI +@client_mode_hook +def init( + address: Optional[str] = None, + *, + num_cpus: Optional[int] = None, + num_gpus: Optional[int] = None, + resources: Optional[Dict[str, float]] = None, + labels: Optional[Dict[str, str]] = None, + object_store_memory: Optional[int] = None, + local_mode: bool = False, + ignore_reinit_error: bool = False, + include_dashboard: Optional[bool] = None, + dashboard_host: str = ray_constants.DEFAULT_DASHBOARD_IP, + dashboard_port: Optional[int] = None, + job_config: "ray.job_config.JobConfig" = None, + configure_logging: bool = True, + logging_level: int = ray_constants.LOGGER_LEVEL, + logging_format: Optional[str] = None, + logging_config: Optional[LoggingConfig] = None, + log_to_driver: Optional[bool] = None, + namespace: Optional[str] = None, + runtime_env: Optional[Union[Dict[str, Any], "RuntimeEnv"]] = None, # noqa: F821 + enable_resource_isolation: bool = False, + system_reserved_cpu: Optional[float] = None, + system_reserved_memory: Optional[int] = None, + **kwargs, +) -> BaseContext: + """ + Connect to an existing Ray cluster or start one and connect to it. + + This method handles two cases; either a Ray cluster already exists and we + just attach this driver to it or we start all of the processes associated + with a Ray cluster and attach to the newly started cluster. + Note: This method overwrite sigterm handler of the driver process. + + In most cases, it is enough to just call this method with no arguments. + This will autodetect an existing Ray cluster or start a new Ray instance if + no existing cluster is found: + + .. testcode:: + + ray.init() + + To explicitly connect to an existing local cluster, use this as follows. A + ConnectionError will be thrown if no existing local cluster is found. + + .. testcode:: + :skipif: True + + ray.init(address="auto") + + To connect to an existing remote cluster, use this as follows (substituting + in the appropriate address). Note the addition of "ray://" at the beginning + of the address. This requires `ray[client]`. + + .. testcode:: + :skipif: True + + ray.init(address="ray://123.45.67.89:10001") + + More details for starting and connecting to a remote cluster can be found + here: https://docs.ray.io/en/master/cluster/getting-started.html + + You can also define an environment variable called `RAY_ADDRESS` in + the same format as the `address` parameter to connect to an existing + cluster with ray.init() or ray.init(address="auto"). + + Args: + address: The address of the Ray cluster to connect to. The provided + address is resolved as follows: + 1. If a concrete address (e.g., localhost:) is provided, try to + connect to it. Concrete addresses can be prefixed with "ray://" to + connect to a remote cluster. For example, passing in the address + "ray://123.45.67.89:50005" will connect to the cluster at the given + address. + 2. If no address is provided, try to find an existing Ray instance + to connect to. This is done by first checking the environment + variable `RAY_ADDRESS`. If this is not defined, check the address + of the latest cluster started (found in + /tmp/ray/ray_current_cluster) if available. If this is also empty, + then start a new local Ray instance. + 3. If the provided address is "auto", then follow the same process + as above. However, if there is no existing cluster found, this will + throw a ConnectionError instead of starting a new local Ray + instance. + 4. If the provided address is "local", start a new local Ray + instance, even if there is already an existing local Ray instance. + num_cpus: Number of CPUs the user wishes to assign to each + raylet. By default, this is set based on virtual cores. + num_gpus: Number of GPUs the user wishes to assign to each + raylet. By default, this is set based on detected GPUs. + resources: A dictionary mapping the names of custom resources to the + quantities for them available. + labels: [Experimental] The key-value labels of the node. + object_store_memory: The amount of memory (in bytes) to start the + object store with. + By default, this is 30% of available system memory capped by + the shm size and 200G but can be set higher. + local_mode: Deprecated: consider using the Ray Debugger instead. + ignore_reinit_error: If true, Ray suppresses errors from calling + ray.init() a second time. Ray won't be restarted. + include_dashboard: Boolean flag indicating whether or not to start the + Ray dashboard, which displays the status of the Ray + cluster. If this argument is None, then the UI will be started if + the relevant dependencies are present. + dashboard_host: The host to bind the dashboard server to. Can either be + localhost (127.0.0.1) or 0.0.0.0 (available from all interfaces). + By default, this is set to localhost to prevent access from + external machines. + dashboard_port(int, None): The port to bind the dashboard server to. + Defaults to 8265 and Ray will automatically find a free port if + 8265 is not available. + job_config (ray.job_config.JobConfig): The job configuration. + configure_logging: True (default) if configuration of logging is + allowed here. Otherwise, the user may want to configure it + separately. + logging_level: Logging level for the "ray" logger of the driver process, + defaults to logging.INFO. Ignored unless "configure_logging" is true. + logging_format: Logging format for the "ray" logger of the driver process, + defaults to a string containing a timestamp, filename, line number, and + message. See the source file ray_constants.py for details. Ignored unless + "configure_logging" is true. + logging_config: [Experimental] Logging configuration will be applied to the + root loggers for both the driver process and all worker processes belonging + to the current job. See :class:`~ray.LoggingConfig` for details. + log_to_driver: If true, the output from all of the worker + processes on all nodes will be directed to the driver. + namespace: A namespace is a logical grouping of jobs and named actors. + runtime_env: The runtime environment to use + for this job (see :ref:`runtime-environments` for details). + object_spilling_directory: The path to spill objects to. The same path will + be used as the object store fallback directory as well. + enable_resource_isolation: Enable resource isolation through cgroupv2 by reserving + memory and cpu resources for ray system processes. To use, only cgroupv2 (not cgroupv1) + must be enabled with read and write permissions for the raylet. Cgroup memory and + cpu controllers must also be enabled. + system_reserved_cpu: The amount of cpu cores to reserve for ray system processes. Cores can be + fractional i.e. 0.5 means half a cpu core. + By default, the min of 20% and 1 core will be reserved. + Must be >= 0.5 cores and < total number of available cores. + Cannot be less than 0.5 cores. + This option only works if enable_resource_isolation is True. + system_reserved_memory: The amount of memory (in bytes) to reserve for ray system processes. + By default, the min of 10% and 25GB plus object_store_memory will be reserved. + Must be >= 100MB and system_reserved_memory + object_store_bytes < total available memory. + This option only works if enable_resource_isolation is True. + _cgroup_path: The path for the cgroup the raylet should use to enforce resource isolation. + By default, the cgroup used for resource isolation will be /sys/fs/cgroup. + The raylet must have read/write permissions to this path. + Cgroup memory and cpu controllers be enabled for this cgroup. + This option only works if enable_resource_isolation is True. + _enable_object_reconstruction: If True, when an object stored in + the distributed plasma store is lost due to node failure, Ray will + attempt to reconstruct the object by re-executing the task that + created the object. Arguments to the task will be recursively + reconstructed. If False, then ray.ObjectLostError will be + thrown. + _plasma_directory: Override the plasma mmap file directory. + _node_ip_address: The IP address of the node that we are on. + _driver_object_store_memory: Deprecated. + _memory: Amount of reservable memory resource in bytes rounded + down to the nearest integer. + _redis_username: Prevents external clients without the username + from connecting to Redis if provided. + _redis_password: Prevents external clients without the password + from connecting to Redis if provided. + _temp_dir: If provided, specifies the root temporary + directory for the Ray process. Must be an absolute path. Defaults to an + OS-specific conventional location, e.g., "/tmp/ray". + _metrics_export_port: Port number Ray exposes system metrics + through a Prometheus endpoint. It is currently under active + development, and the API is subject to change. + _system_config: Configuration for overriding + RayConfig defaults. For testing purposes ONLY. + _tracing_startup_hook: If provided, turns on and sets up tracing + for Ray. Must be the name of a function that takes no arguments and + sets up a Tracer Provider, Remote Span Processors, and + (optional) additional instruments. See more at + docs.ray.io/tracing.html. It is currently under active development, + and the API is subject to change. + _node_name: User-provided node name or identifier. Defaults to + the node IP address. + + Returns: + If the provided address includes a protocol, for example by prepending + "ray://" to the address to get "ray://1.2.3.4:10001", then a + ClientContext is returned with information such as settings, server + versions for ray and python, and the dashboard_url. Otherwise, + a RayContext is returned with ray and python versions, and address + information about the started processes. + + Raises: + Exception: An exception is raised if an inappropriate combination of + arguments is passed in. + """ + if log_to_driver is None: + log_to_driver = ray_constants.RAY_LOG_TO_DRIVER + + # Configure the "ray" logger for the driver process. + if configure_logging: + setup_logger(logging_level, logging_format or ray_constants.LOGGER_FORMAT) + else: + logging.getLogger("ray").handlers.clear() + + # Configure the logging settings for the driver process. + if logging_config or ray_constants.RAY_LOGGING_CONFIG_ENCODING: + logging_config = logging_config or LoggingConfig( + encoding=ray_constants.RAY_LOGGING_CONFIG_ENCODING + ) + logging_config._apply() + + # Parse the hidden options + _cgroup_path: str = kwargs.pop("_cgroup_path", None) + + _enable_object_reconstruction: bool = kwargs.pop( + "_enable_object_reconstruction", False + ) + _plasma_directory: Optional[str] = kwargs.pop("_plasma_directory", None) + _object_spilling_directory: Optional[str] = kwargs.pop( + "object_spilling_directory", None + ) + _node_ip_address: str = kwargs.pop("_node_ip_address", None) + _driver_object_store_memory: Optional[int] = kwargs.pop( + "_driver_object_store_memory", None + ) + _memory: Optional[int] = kwargs.pop("_memory", None) + _redis_username: str = kwargs.pop( + "_redis_username", ray_constants.REDIS_DEFAULT_USERNAME + ) + _redis_password: str = kwargs.pop( + "_redis_password", ray_constants.REDIS_DEFAULT_PASSWORD + ) + _temp_dir: Optional[str] = kwargs.pop("_temp_dir", None) + _metrics_export_port: Optional[int] = kwargs.pop("_metrics_export_port", None) + _system_config: Optional[Dict[str, str]] = kwargs.pop("_system_config", None) + _tracing_startup_hook: Optional[Callable] = kwargs.pop( + "_tracing_startup_hook", None + ) + _node_name: str = kwargs.pop("_node_name", None) + # Fix for https://github.com/ray-project/ray/issues/26729 + _skip_env_hook: bool = kwargs.pop("_skip_env_hook", False) + + resource_isolation_config = ResourceIsolationConfig( + enable_resource_isolation=enable_resource_isolation, + cgroup_path=_cgroup_path, + system_reserved_cpu=system_reserved_cpu, + system_reserved_memory=system_reserved_memory, + ) + + # terminate any signal before connecting driver + def sigterm_handler(signum, frame): + sys.exit(signum) + + if threading.current_thread() is threading.main_thread(): + ray._private.utils.set_sigterm_handler(sigterm_handler) + else: + logger.warning( + "SIGTERM handler is not set because current thread " + "is not the main thread." + ) + + # If available, use RAY_ADDRESS to override if the address was left + # unspecified, or set to "auto" in the call to init + address_env_var = os.environ.get(ray_constants.RAY_ADDRESS_ENVIRONMENT_VARIABLE) + if address_env_var and (address is None or address == "auto"): + address = address_env_var + logger.info( + f"Using address {address_env_var} set in the environment " + f"variable {ray_constants.RAY_ADDRESS_ENVIRONMENT_VARIABLE}" + ) + + if address is not None and "://" in address: + # Address specified a protocol, use ray client + builder = ray.client(address, _deprecation_warn_enabled=False) + + # Forward any keyword arguments that were changed from their default + # values to the builder + init_sig = inspect.signature(init) + passed_kwargs = {} + for argument_name, param_obj in init_sig.parameters.items(): + if argument_name in {"kwargs", "address"}: + # kwargs and address are handled separately + continue + default_value = param_obj.default + passed_value = locals()[argument_name] + if passed_value != default_value: + # passed value is different than default, pass to the client + # builder + passed_kwargs[argument_name] = passed_value + passed_kwargs.update(kwargs) + builder._init_args(**passed_kwargs) + ctx = builder.connect() + from ray._private.usage import usage_lib + + if passed_kwargs.get("allow_multiple") is True: + with ctx: + usage_lib.put_pre_init_usage_stats() + else: + usage_lib.put_pre_init_usage_stats() + + usage_lib.record_library_usage("client") + return ctx + + if kwargs.get("allow_multiple"): + raise RuntimeError( + "`allow_multiple` argument is passed to `ray.init` when the " + "ray client is not used (" + f"https://docs.ray.io/en/{get_ray_doc_version()}/cluster" + "/running-applications/job-submission" + "/ray-client.html#connect-to-multiple-ray-clusters-experimental). " + "Do not pass the `allow_multiple` to `ray.init` to fix the issue." + ) + + if kwargs.get("storage"): + raise RuntimeError( + "Cluster-wide storage configuration has been removed. " + "The last Ray version supporting the `storage` argument is `ray==2.47`." + ) + + if kwargs: + # User passed in extra keyword arguments but isn't connecting through + # ray client. Raise an error, since most likely a typo in keyword + unknown = ", ".join(kwargs) + raise RuntimeError(f"Unknown keyword argument(s): {unknown}") + + # Try to increase the file descriptor limit, which is too low by + # default for Ray: https://github.com/ray-project/ray/issues/11239 + try: + import resource + + soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE) + if soft < hard: + # https://github.com/ray-project/ray/issues/12059 + soft = max(soft, min(hard, 65536)) + logger.debug( + f"Automatically increasing RLIMIT_NOFILE to max value of {hard}" + ) + try: + resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard)) + except ValueError: + logger.debug("Failed to raise limit.") + soft, _ = resource.getrlimit(resource.RLIMIT_NOFILE) + if soft < 4096: + logger.warning( + "File descriptor limit {} is too low for production " + "servers and may result in connection errors. " + "At least 8192 is recommended. --- " + "Fix with 'ulimit -n 8192'".format(soft) + ) + except ImportError: + logger.debug("Could not import resource module (on Windows)") + pass + + if job_config is None: + job_config = ray.job_config.JobConfig() + + if RAY_JOB_CONFIG_JSON_ENV_VAR in os.environ: + injected_job_config_json = json.loads( + os.environ.get(RAY_JOB_CONFIG_JSON_ENV_VAR) + ) + injected_job_config: ray.job_config.JobConfig = ( + ray.job_config.JobConfig.from_json(injected_job_config_json) + ) + driver_runtime_env = runtime_env + runtime_env = _merge_runtime_env( + injected_job_config.runtime_env, + driver_runtime_env, + override=os.getenv("RAY_OVERRIDE_JOB_RUNTIME_ENV") == "1", + ) + if runtime_env is None: + # None means there was a conflict. + raise ValueError( + "Failed to merge the Job's runtime env " + f"{injected_job_config.runtime_env} with " + f"a ray.init's runtime env {driver_runtime_env} because " + "of a conflict. Specifying the same runtime_env fields " + "or the same environment variable keys is not allowed. " + "Use RAY_OVERRIDE_JOB_RUNTIME_ENV=1 to instruct Ray to " + "combine Job and Driver's runtime environment in the event of " + "a conflict." + ) + + runtime_env = _maybe_modify_runtime_env(runtime_env, _skip_env_hook) + + job_config.set_runtime_env(runtime_env) + # Similarly, we prefer metadata provided via job submission API + for key, value in injected_job_config.metadata.items(): + job_config.set_metadata(key, value) + + # RAY_JOB_CONFIG_JSON_ENV_VAR is only set at ray job manager level and has + # higher priority in case user also provided runtime_env for ray.init() + else: + runtime_env = _maybe_modify_runtime_env(runtime_env, _skip_env_hook) + + if runtime_env: + # Set runtime_env in job_config if passed in as part of ray.init() + job_config.set_runtime_env(runtime_env) + + # Pass the logging_config to job_config to configure loggers of all worker + # processes belonging to the job. + if logging_config is not None: + job_config.set_py_logging_config(logging_config) + + redis_address, gcs_address = None, None + bootstrap_address = services.canonicalize_bootstrap_address(address, _temp_dir) + if bootstrap_address is not None: + gcs_address = bootstrap_address + logger.info("Connecting to existing Ray cluster at address: %s...", gcs_address) + + if local_mode: + driver_mode = LOCAL_MODE + warnings.warn( + "DeprecationWarning: local mode is an experimental feature that is no " + "longer maintained and will be removed in the future." + "For debugging consider using Ray debugger. ", + DeprecationWarning, + stacklevel=2, + ) + else: + driver_mode = SCRIPT_MODE + + global _global_node + + if global_worker.connected: + if ignore_reinit_error: + logger.info("Calling ray.init() again after it has already been called.") + node_id = global_worker.core_worker.get_current_node_id() + return RayContext(dict(_global_node.address_info, node_id=node_id.hex())) + else: + raise RuntimeError( + "Maybe you called ray.init twice by accident? " + "This error can be suppressed by passing in " + "'ignore_reinit_error=True' or by calling " + "'ray.shutdown()' prior to 'ray.init()'." + ) + + _system_config = _system_config or {} + if not isinstance(_system_config, dict): + raise TypeError("The _system_config must be a dict.") + + if bootstrap_address is None: + # In this case, we need to start a new cluster. + + # Don't collect usage stats in ray.init() unless it's a nightly wheel. + from ray._private.usage import usage_lib + + if usage_lib.is_nightly_wheel(): + usage_lib.show_usage_stats_prompt(cli=False) + else: + usage_lib.set_usage_stats_enabled_via_env_var(False) + + # Use a random port by not specifying Redis port / GCS server port. + ray_params = ray._private.parameter.RayParams( + node_ip_address=_node_ip_address, + driver_mode=driver_mode, + redirect_output=None, + num_cpus=num_cpus, + num_gpus=num_gpus, + resources=resources, + labels=labels, + num_redis_shards=None, + redis_max_clients=None, + redis_username=_redis_username, + redis_password=_redis_password, + plasma_directory=_plasma_directory, + object_spilling_directory=_object_spilling_directory, + huge_pages=None, + include_dashboard=include_dashboard, + dashboard_host=dashboard_host, + dashboard_port=dashboard_port, + memory=_memory, + object_store_memory=object_store_memory, + plasma_store_socket_name=None, + temp_dir=_temp_dir, + _system_config=_system_config, + enable_object_reconstruction=_enable_object_reconstruction, + metrics_export_port=_metrics_export_port, + tracing_startup_hook=_tracing_startup_hook, + node_name=_node_name, + resource_isolation_config=resource_isolation_config, + ) + # Start the Ray processes. We set shutdown_at_exit=False because we + # shutdown the node in the ray.shutdown call that happens in the atexit + # handler. We still spawn a reaper process in case the atexit handler + # isn't called. + _global_node = ray._private.node.Node( + ray_params=ray_params, + head=True, + shutdown_at_exit=False, + spawn_reaper=True, + ray_init_cluster=True, + ) + else: + # In this case, we are connecting to an existing cluster. + if num_cpus is not None or num_gpus is not None: + raise ValueError( + "When connecting to an existing cluster, num_cpus " + "and num_gpus must not be provided." + ) + if resources is not None: + raise ValueError( + "When connecting to an existing cluster, " + "resources must not be provided." + ) + if labels is not None: + raise ValueError( + "When connecting to an existing cluster, " + "labels must not be provided." + ) + if object_store_memory is not None: + raise ValueError( + "When connecting to an existing cluster, " + "object_store_memory must not be provided." + ) + if _system_config is not None and len(_system_config) != 0: + raise ValueError( + "When connecting to an existing cluster, " + "_system_config must not be provided." + ) + if _enable_object_reconstruction: + raise ValueError( + "When connecting to an existing cluster, " + "_enable_object_reconstruction must not be provided." + ) + if _node_name is not None: + raise ValueError( + "_node_name cannot be configured when connecting to " + "an existing cluster." + ) + + # In this case, we only need to connect the node. + ray_params = ray._private.parameter.RayParams( + node_ip_address=_node_ip_address, + gcs_address=gcs_address, + redis_address=redis_address, + redis_username=_redis_username, + redis_password=_redis_password, + temp_dir=_temp_dir, + _system_config=_system_config, + enable_object_reconstruction=_enable_object_reconstruction, + metrics_export_port=_metrics_export_port, + ) + try: + _global_node = ray._private.node.Node( + ray_params, + head=False, + shutdown_at_exit=False, + spawn_reaper=False, + connect_only=True, + ) + except (ConnectionError, RuntimeError): + if gcs_address == ray._private.utils.read_ray_address(_temp_dir): + logger.info( + "Failed to connect to the default Ray cluster address at " + f"{gcs_address}. This is most likely due to a previous Ray " + "instance that has since crashed. To reset the default " + "address to connect to, run `ray stop` or restart Ray with " + "`ray start`." + ) + raise ConnectionError + + # Log a message to find the Ray address that we connected to and the + # dashboard URL. + if ray_constants.RAY_OVERRIDE_DASHBOARD_URL in os.environ: + dashboard_url = os.environ.get(ray_constants.RAY_OVERRIDE_DASHBOARD_URL) + else: + dashboard_url = _global_node.webui_url + # Add http protocol to dashboard URL if it doesn't + # already contain a protocol. + if dashboard_url and not urlparse(dashboard_url).scheme: + dashboard_url = "http://" + dashboard_url + + # We logged the address before attempting the connection, so we don't need + # to log it again. + info_str = "Connected to Ray cluster." + if gcs_address is None: + info_str = "Started a local Ray instance." + if dashboard_url: + logger.info( + info_str + " View the dashboard at %s%s%s %s%s", + colorama.Style.BRIGHT, + colorama.Fore.GREEN, + dashboard_url, + colorama.Fore.RESET, + colorama.Style.NORMAL, + ) + else: + logger.info(info_str) + + connect( + _global_node, + _global_node.session_name, + mode=driver_mode, + log_to_driver=log_to_driver, + worker=global_worker, + driver_object_store_memory=_driver_object_store_memory, + job_id=None, + namespace=namespace, + job_config=job_config, + entrypoint=ray._private.utils.get_entrypoint_name(), + ) + if job_config and job_config.code_search_path: + global_worker.set_load_code_from_local(True) + else: + # Because `ray.shutdown()` doesn't reset this flag, for multiple + # sessions in one process, the 2nd `ray.init()` will reuse the + # flag of last session. For example: + # ray.init(load_code_from_local=True) + # ray.shutdown() + # ray.init() + # # Here the flag `load_code_from_local` is still True if we + # # doesn't have this `else` branch. + # ray.shutdown() + global_worker.set_load_code_from_local(False) + + for hook in _post_init_hooks: + hook() + + node_id = global_worker.core_worker.get_current_node_id() + global_node_address_info = _global_node.address_info.copy() + global_node_address_info["webui_url"] = _remove_protocol_from_url(dashboard_url) + return RayContext(dict(global_node_address_info, node_id=node_id.hex())) + + +# Functions to run as callback after a successful ray init. +_post_init_hooks = [] + + +@PublicAPI +@client_mode_hook +def shutdown(_exiting_interpreter: bool = False): + """Disconnect the worker, and terminate processes started by ray.init(). + + This will automatically run at the end when a Python process that uses Ray + exits. It is ok to run this twice in a row. The primary use case for this + function is to cleanup state between tests. + + Note that this will clear any remote function definitions, actor + definitions, and existing actors, so if you wish to use any previously + defined remote functions or actors after calling ray.shutdown(), then you + need to redefine them. If they were defined in an imported module, then you + will need to reload the module. + + Args: + _exiting_interpreter: True if this is called by the atexit hook + and false otherwise. If we are exiting the interpreter, we will + wait a little while to print any extra error messages. + """ + # Make sure to clean up compiled dag node if exists. + from ray.dag.compiled_dag_node import _shutdown_all_compiled_dags + + _shutdown_all_compiled_dags() + + if _exiting_interpreter and global_worker.mode == SCRIPT_MODE: + # This is a duration to sleep before shutting down everything in order + # to make sure that log messages finish printing. + time.sleep(0.5) + disconnect(_exiting_interpreter) + + # disconnect internal kv + if hasattr(global_worker, "gcs_client"): + del global_worker.gcs_client + _internal_kv_reset() + + # We need to destruct the core worker here because after this function, + # we will tear down any processes spawned by ray.init() and the background + # IO thread in the core worker doesn't currently handle that gracefully. + if hasattr(global_worker, "core_worker"): + if global_worker.mode == SCRIPT_MODE or global_worker.mode == LOCAL_MODE: + global_worker.core_worker.shutdown_driver() + del global_worker.core_worker + # We need to reset function actor manager to clear the context + global_worker.function_actor_manager = FunctionActorManager(global_worker) + # Disconnect global state from GCS. + ray._private.state.state.disconnect() + + # Shut down the Ray processes. + global _global_node + if _global_node is not None: + if _global_node.is_head(): + _global_node.destroy_external_storage() + _global_node.kill_all_processes(check_alive=False, allow_graceful=True) + _global_node = None + + # TODO(rkn): Instead of manually resetting some of the worker fields, we + # should simply set "global_worker" to equal "None" or something like that. + global_worker.set_mode(None) + global_worker.set_cached_job_id(None) + + +atexit.register(shutdown, True) + +# Define a custom excepthook so that if the driver exits with an exception, we +# can push that exception to Redis. +normal_excepthook = sys.excepthook + + +def custom_excepthook(type, value, tb): + import ray.core.generated.common_pb2 as common_pb2 + + # If this is a driver, push the exception to GCS worker table. + if global_worker.mode == SCRIPT_MODE and hasattr(global_worker, "worker_id"): + error_message = "".join(traceback.format_tb(tb)) + worker_id = global_worker.worker_id + worker_type = common_pb2.DRIVER + worker_info = {"exception": error_message} + + ray._private.state.state._check_connected() + ray._private.state.state.add_worker(worker_id, worker_type, worker_info) + # Call the normal excepthook. + normal_excepthook(type, value, tb) + + +sys.excepthook = custom_excepthook + + +def print_to_stdstream(data, ignore_prefix: bool): + should_dedup = data.get("pid") not in ["autoscaler"] + + if data["is_err"]: + if should_dedup: + batches = stderr_deduplicator.deduplicate(data) + else: + batches = [data] + sink = sys.stderr + else: + if should_dedup: + batches = stdout_deduplicator.deduplicate(data) + else: + batches = [data] + sink = sys.stdout + + for batch in batches: + print_worker_logs(batch, sink, ignore_prefix) + + +# Start time of this process, used for relative time logs. +t0 = time.time() +autoscaler_log_fyi_printed = False + + +def filter_autoscaler_events(lines: List[str]) -> Iterator[str]: + """Given raw log lines from the monitor, return only autoscaler events. + + For Autoscaler V1: + Autoscaler events are denoted by the ":event_summary:" magic token. + For Autoscaler V2: + Autoscaler events are published from log_monitor.py which read + them from the `event_AUTOSCALER.log`. + """ + + if not ray_constants.AUTOSCALER_EVENTS: + return + + AUTOSCALER_LOG_FYI = ( + "Tip: use `ray status` to view detailed " + "cluster status. To disable these " + "messages, set RAY_SCHEDULER_EVENTS=0." + ) + + def autoscaler_log_fyi_needed() -> bool: + global autoscaler_log_fyi_printed + if not autoscaler_log_fyi_printed: + autoscaler_log_fyi_printed = True + return True + return False + + from ray.autoscaler.v2.utils import is_autoscaler_v2 + + if is_autoscaler_v2(): + from ray._private.event.event_logger import filter_event_by_level, parse_event + + for event_line in lines: + if autoscaler_log_fyi_needed(): + yield AUTOSCALER_LOG_FYI + + event = parse_event(event_line) + if not event or not event.message: + continue + + if filter_event_by_level( + event, ray_constants.RAY_LOG_TO_DRIVER_EVENT_LEVEL + ): + continue + + yield event.message + else: + # Print out autoscaler events only, ignoring other messages. + for line in lines: + if ray_constants.LOG_PREFIX_EVENT_SUMMARY in line: + if autoscaler_log_fyi_needed(): + yield AUTOSCALER_LOG_FYI + # The event text immediately follows the ":event_summary:" + # magic token. + yield line.split(ray_constants.LOG_PREFIX_EVENT_SUMMARY)[1] + + +def time_string() -> str: + """Return the relative time from the start of this job. + + For example, 15m30s. + """ + delta = time.time() - t0 + hours = 0 + minutes = 0 + while delta > 3600: + hours += 1 + delta -= 3600 + while delta > 60: + minutes += 1 + delta -= 60 + output = "" + if hours: + output += f"{hours}h" + if minutes: + output += f"{minutes}m" + output += f"{int(delta)}s" + return output + + +# When we enter a breakpoint, worker logs are automatically disabled via this. +_worker_logs_enabled = True + + +def print_worker_logs( + data: Dict[str, str], print_file: Any, ignore_prefix: bool = False +): + if not _worker_logs_enabled: + return + + def prefix_for(data: Dict[str, str]) -> str: + """The PID prefix for this log line.""" + if data.get("pid") in ["autoscaler", "raylet"]: + return "" + else: + res = "pid=" + if data.get("actor_name"): + res = f"{data['actor_name']} {res}" + elif data.get("task_name"): + res = f"{data['task_name']} {res}" + return res + + def message_for(data: Dict[str, str], line: str) -> str: + """The printed message of this log line.""" + if ray_constants.LOG_PREFIX_INFO_MESSAGE in line: + return line.split(ray_constants.LOG_PREFIX_INFO_MESSAGE)[1] + return line + + def color_for(data: Dict[str, str], line: str) -> str: + """The color for this log line.""" + if ( + data.get("pid") == "raylet" + and ray_constants.LOG_PREFIX_INFO_MESSAGE not in line + ): + return colorama.Fore.YELLOW + elif data.get("pid") == "autoscaler": + if "Error:" in line or "Warning:" in line: + return colorama.Fore.YELLOW + else: + return colorama.Fore.CYAN + elif os.getenv("RAY_COLOR_PREFIX") == "1": + colors = [ + # colorama.Fore.BLUE, # Too dark + colorama.Fore.MAGENTA, + colorama.Fore.CYAN, + colorama.Fore.GREEN, + # colorama.Fore.WHITE, # Too light + # colorama.Fore.RED, + colorama.Fore.LIGHTBLACK_EX, + colorama.Fore.LIGHTBLUE_EX, + # colorama.Fore.LIGHTCYAN_EX, # Too light + # colorama.Fore.LIGHTGREEN_EX, # Too light + colorama.Fore.LIGHTMAGENTA_EX, + # colorama.Fore.LIGHTWHITE_EX, # Too light + # colorama.Fore.LIGHTYELLOW_EX, # Too light + ] + pid = data.get("pid", 0) + try: + i = int(pid) + except ValueError: + i = 0 + return colors[i % len(colors)] + else: + return colorama.Fore.CYAN + + if data.get("pid") == "autoscaler": + pid = "autoscaler +{}".format(time_string()) + lines = filter_autoscaler_events(data.get("lines", [])) + else: + pid = data.get("pid") + lines = data.get("lines", []) + + ip = data.get("ip") + ip_prefix = "" if ip == data.get("localhost") else f", ip={ip}" + for line in lines: + if RAY_TQDM_MAGIC in line: + process_tqdm(line) + else: + hide_tqdm() + # If RAY_COLOR_PREFIX=0, do not wrap with any color codes + if os.getenv("RAY_COLOR_PREFIX") == "0": + color_pre = "" + color_post = "" + else: + color_pre = color_for(data, line) + color_post = colorama.Style.RESET_ALL + + if ignore_prefix: + print( + f"{message_for(data, line)}", + file=print_file, + ) + else: + print( + f"{color_pre}({prefix_for(data)}{pid}{ip_prefix}){color_post} " + f"{message_for(data, line)}", + file=print_file, + ) + + # Restore once at end of batch to avoid excess hiding/unhiding of tqdm. + restore_tqdm() + + +def process_tqdm(line): + """Experimental distributed tqdm: see ray.experimental.tqdm_ray.""" + try: + data = json.loads(line) + tqdm_ray.instance().process_state_update(data) + except Exception: + if log_once("tqdm_corruption"): + logger.warning( + f"[tqdm_ray] Failed to decode {line}, this may be due to " + "logging too fast. This warning will not be printed again." + ) + + +def hide_tqdm(): + """Hide distributed tqdm bars temporarily to avoid conflicts with other logs.""" + tqdm_ray.instance().hide_bars() + + +def restore_tqdm(): + """Undo hide_tqdm().""" + tqdm_ray.instance().unhide_bars() + + +def listen_error_messages(worker, threads_stopped): + """Listen to error messages in the background on the driver. + + This runs in a separate thread on the driver and pushes (error, time) + tuples to be published. + + Args: + worker: The worker class that this thread belongs to. + threads_stopped (threading.Event): A threading event used to signal to + the thread that it should exit. + """ + + # TODO: we should just subscribe to the errors for this specific job. + worker.gcs_error_subscriber.subscribe() + + try: + if _internal_kv_initialized(): + # Get any autoscaler errors that occurred before the call to + # subscribe. + error_message = _internal_kv_get(ray_constants.DEBUG_AUTOSCALING_ERROR) + if error_message is not None: + logger.warning(error_message.decode()) + while True: + # Exit if received a signal that the thread should stop. + if threads_stopped.is_set(): + return + + _, error_data = worker.gcs_error_subscriber.poll() + if error_data is None: + continue + if error_data["job_id"] is not None and error_data["job_id"] not in [ + worker.current_job_id.binary(), + JobID.nil().binary(), + ]: + continue + + error_message = error_data["error_message"] + print_to_stdstream( + { + "lines": [error_message], + "pid": "raylet", + "is_err": False, + }, + ignore_prefix=False, + ) + except (OSError, ConnectionError) as e: + logger.error(f"listen_error_messages: {e}") + + +@PublicAPI +@client_mode_hook +def is_initialized() -> bool: + """Check if ray.init has been called yet. + + Returns: + True if ray.init has already been called and false otherwise. + """ + return ray._private.worker.global_worker.connected + + +# TODO(hjiang): Add cgroup path along with [enable_resource_isolation]. +def connect( + node, + session_name: str, + mode=WORKER_MODE, + log_to_driver: bool = False, + worker=global_worker, + driver_object_store_memory: Optional[int] = None, + job_id=None, + namespace: Optional[str] = None, + job_config=None, + runtime_env_hash: int = 0, + startup_token: int = 0, + ray_debugger_external: bool = False, + entrypoint: str = "", + worker_launch_time_ms: int = -1, + worker_launched_time_ms: int = -1, + debug_source: str = "", + enable_resource_isolation: bool = False, +): + """Connect this worker to the raylet, to Plasma, and to GCS. + + Args: + node (ray._private.node.Node): The node to connect. + session_name: The session name (cluster id) of this cluster. + mode: The mode of the worker. One of SCRIPT_MODE, WORKER_MODE, and LOCAL_MODE. + log_to_driver: If true, then output from all of the worker + processes on all nodes will be directed to the driver. + worker: The ray.Worker instance. + driver_object_store_memory: Deprecated. + job_id: The ID of job. If it's None, then we will generate one. + namespace: Namespace to use. + job_config (ray.job_config.JobConfig): The job configuration. + runtime_env_hash: The hash of the runtime env for this worker. + startup_token: The startup token of the process assigned to + it during startup as a command line argument. + ray_debugger_external: If True, make the debugger external to the + node this worker is running on. + entrypoint: The name of the entrypoint script. Ignored if the + mode != SCRIPT_MODE + worker_launch_time_ms: The time when the worker process for this worker + is launched. If the worker is not launched by raylet (e.g., + driver), this must be -1 (default value). + worker_launched_time_ms: The time when the worker process for this worker + finshes launching. If the worker is not launched by raylet (e.g., + driver), this must be -1 (default value). + debug_source: Source information for `CoreWorker`, used for debugging and informational purpose, rather than functional purpose. + enable_resource_isolation: If true, core worker enables resource isolation by adding itself into appropriate cgroup. + """ + # Do some basic checking to make sure we didn't call ray.init twice. + error_message = "Perhaps you called ray.init twice by accident?" + assert not worker.connected, error_message + + # Enable nice stack traces on SIGSEGV etc. + try: + if not faulthandler.is_enabled(): + faulthandler.enable(all_threads=False) + except io.UnsupportedOperation: + pass # ignore + + worker.gcs_client = node.get_gcs_client() + assert worker.gcs_client is not None + _initialize_internal_kv(worker.gcs_client) + ray._private.state.state._initialize_global_state( + ray._raylet.GcsClientOptions.create( + node.gcs_address, + node.cluster_id.hex(), + allow_cluster_id_nil=False, + fetch_cluster_id_if_nil=False, + ) + ) + # Initialize some fields. + if mode in (WORKER_MODE, RESTORE_WORKER_MODE, SPILL_WORKER_MODE): + # We should not specify the job_id if it's `WORKER_MODE`. + assert job_id is None + job_id = JobID.nil() + else: + # This is the code path of driver mode. + if job_id is None: + job_id = ray._private.state.next_job_id() + + if mode is not SCRIPT_MODE and mode is not LOCAL_MODE: + process_name = ray_constants.WORKER_PROCESS_TYPE_IDLE_WORKER + if mode is SPILL_WORKER_MODE: + process_name = ray_constants.WORKER_PROCESS_TYPE_SPILL_WORKER_IDLE + elif mode is RESTORE_WORKER_MODE: + process_name = ray_constants.WORKER_PROCESS_TYPE_RESTORE_WORKER_IDLE + ray._raylet.setproctitle(process_name) + + if not isinstance(job_id, JobID): + raise TypeError("The type of given job id must be JobID.") + + # All workers start out as non-actors. A worker can be turned into an actor + # after it is created. + worker.node = node + worker.set_mode(mode) + + # For driver's check that the version information matches the version + # information that the Ray cluster was started with. + try: + node.check_version_info() + except Exception as e: + if mode == SCRIPT_MODE: + raise e + elif mode == WORKER_MODE: + traceback_str = traceback.format_exc() + ray._private.utils.publish_error_to_driver( + ray_constants.VERSION_MISMATCH_PUSH_ERROR, + traceback_str, + gcs_client=worker.gcs_client, + ) + + driver_name = "" + interactive_mode = False + if mode == SCRIPT_MODE: + import __main__ as main + + if hasattr(main, "__file__"): + driver_name = main.__file__ + else: + interactive_mode = True + driver_name = "INTERACTIVE MODE" + elif not LOCAL_MODE: + raise ValueError("Invalid worker mode. Expected DRIVER, WORKER or LOCAL.") + + gcs_options = ray._raylet.GcsClientOptions.create( + node.gcs_address, + node.cluster_id.hex(), + allow_cluster_id_nil=False, + fetch_cluster_id_if_nil=False, + ) + if job_config is None: + job_config = ray.job_config.JobConfig() + + if namespace is not None: + ray._private.utils.validate_namespace(namespace) + + # The namespace field of job config may have already been set in code + # paths such as the client. + job_config.set_ray_namespace(namespace) + + # Make sure breakpoint() in the user's code will + # invoke the Ray debugger if we are in a worker or actor process + # (but not on the driver). + if mode == WORKER_MODE: + os.environ["PYTHONBREAKPOINT"] = "ray.util.rpdb.set_trace" + else: + # Add hook to suppress worker logs during breakpoint. + os.environ["PYTHONBREAKPOINT"] = "ray.util.rpdb._driver_set_trace" + + worker.ray_debugger_external = ray_debugger_external + + # If it's a driver and it's not coming from ray client, we'll prepare the + # environment here. If it's ray client, the environment will be prepared + # at the server side. + if mode == SCRIPT_MODE and not job_config._client_job and job_config.runtime_env: + scratch_dir: str = worker.node.get_runtime_env_dir_path() + runtime_env = job_config.runtime_env or {} + runtime_env = upload_py_modules_if_needed( + runtime_env, scratch_dir, logger=logger + ) + runtime_env = upload_working_dir_if_needed( + runtime_env, scratch_dir, logger=logger + ) + runtime_env = upload_worker_process_setup_hook_if_needed( + runtime_env, + worker, + ) + # Remove excludes, it isn't relevant after the upload step. + runtime_env.pop("excludes", None) + job_config.set_runtime_env(runtime_env, validate=True) + + if mode == SCRIPT_MODE: + # Add the directory containing the script that is running to the Python + # paths of the workers. Also add the current directory. Note that this + # assumes that the directory structures on the machines in the clusters + # are the same. + # When using an interactive shell, there is no script directory. + # We also want to skip adding script directory when running from dashboard. + code_paths = [] + if not interactive_mode and not ( + namespace and namespace == ray_constants.RAY_INTERNAL_DASHBOARD_NAMESPACE + ): + script_directory = os.path.dirname(os.path.realpath(sys.argv[0])) + # If driver's sys.path doesn't include the script directory + # (e.g driver is started via `python -m`, + # see https://peps.python.org/pep-0338/), + # then we shouldn't add it to the workers. + if script_directory in sys.path: + code_paths.append(script_directory) + # In client mode, if we use runtime envs with "working_dir", then + # it'll be handled automatically. Otherwise, add the current dir. + if not job_config._client_job and not job_config._runtime_env_has_working_dir(): + current_directory = os.path.abspath(os.path.curdir) + code_paths.append(current_directory) + if len(code_paths) != 0: + job_config._py_driver_sys_path.extend(code_paths) + + serialized_job_config = job_config._serialize() + if not node.should_redirect_logs(): + # Logging to stderr, so give core worker empty logs directory. + logs_dir = "" + else: + logs_dir = node.get_logs_dir_path() + + worker.core_worker = ray._raylet.CoreWorker( + mode, + node.plasma_store_socket_name, + node.raylet_socket_name, + job_id, + gcs_options, + logs_dir, + node.node_ip_address, + node.node_manager_port, + node.raylet_ip_address, + (mode == LOCAL_MODE), + driver_name, + serialized_job_config, + node.metrics_agent_port, + runtime_env_hash, + startup_token, + session_name, + node.cluster_id.hex(), + "" if mode != SCRIPT_MODE else entrypoint, + worker_launch_time_ms, + worker_launched_time_ms, + debug_source, + enable_resource_isolation, + ) + + if mode == SCRIPT_MODE: + worker_id = worker.worker_id + worker.gcs_error_subscriber = ray._raylet.GcsErrorSubscriber( + worker_id=worker_id, address=worker.gcs_client.address + ) + worker.gcs_log_subscriber = ray._raylet.GcsLogSubscriber( + worker_id=worker_id, address=worker.gcs_client.address + ) + + if driver_object_store_memory is not None: + logger.warning( + "`driver_object_store_memory` is deprecated" + " and will be removed in the future." + ) + + # If this is a driver running in SCRIPT_MODE, start a thread to print error + # messages asynchronously in the background. Ideally the scheduler would + # push messages to the driver's worker service, but we ran into bugs when + # trying to properly shutdown the driver's worker service, so we are + # temporarily using this implementation which constantly queries the + # scheduler for new error messages. + if mode == SCRIPT_MODE: + worker.listener_thread = threading.Thread( + target=listen_error_messages, + name="ray_listen_error_messages", + args=(worker, worker.threads_stopped), + ) + worker.listener_thread.daemon = True + worker.listener_thread.start() + # If the job's logging config is set, don't add the prefix + # (task/actor's name and its PID) to the logs. + ignore_prefix = global_worker.job_logging_config is not None + + if log_to_driver: + global_worker_stdstream_dispatcher.add_handler( + "ray_print_logs", + functools.partial(print_to_stdstream, ignore_prefix=ignore_prefix), + ) + worker.logger_thread = threading.Thread( + target=worker.print_logs, name="ray_print_logs" + ) + worker.logger_thread.daemon = True + worker.logger_thread.start() + + # Setup tracing here + tracing_hook_val = worker.gcs_client.internal_kv_get( + b"tracing_startup_hook", ray_constants.KV_NAMESPACE_TRACING + ) + if tracing_hook_val is not None: + ray.util.tracing.tracing_helper._enable_tracing() + if not getattr(ray, "__traced__", False): + _setup_tracing = _import_from_string(tracing_hook_val.decode("utf-8")) + _setup_tracing() + ray.__traced__ = True + + # Mark the worker as connected. + worker.set_is_connected(True) + + +def disconnect(exiting_interpreter=False): + """Disconnect this worker from the raylet and object store.""" + # Reset the list of cached remote functions and actors so that if more + # remote functions or actors are defined and then connect is called again, + # the remote functions will be exported. This is mostly relevant for the + # tests. + worker = global_worker + if worker.connected: + # Shutdown all of the threads that we've started. TODO(rkn): This + # should be handled cleanly in the worker object's destructor and not + # in this disconnect method. + worker.threads_stopped.set() + if hasattr(worker, "gcs_error_subscriber"): + worker.gcs_error_subscriber.close() + if hasattr(worker, "gcs_log_subscriber"): + worker.gcs_log_subscriber.close() + if hasattr(worker, "listener_thread"): + worker.listener_thread.join() + if hasattr(worker, "logger_thread"): + worker.logger_thread.join() + worker.threads_stopped.clear() + + # Ignore the prefix if the logging config is set. + ignore_prefix = worker.job_logging_config is not None + for leftover in stdout_deduplicator.flush(): + print_worker_logs(leftover, sys.stdout, ignore_prefix) + for leftover in stderr_deduplicator.flush(): + print_worker_logs(leftover, sys.stderr, ignore_prefix) + global_worker_stdstream_dispatcher.remove_handler("ray_print_logs") + + worker.node = None # Disconnect the worker from the node. + worker.serialization_context_map.clear() + try: + ray_actor = ray.actor + except AttributeError: + ray_actor = None # This can occur during program termination + if ray_actor is not None: + ray_actor._ActorClassMethodMetadata.reset_cache() + + # Mark the worker as disconnected. + worker.set_is_connected(False) + + +@contextmanager +def _changeproctitle(title, next_title): + if _mode() is not LOCAL_MODE: + ray._raylet.setproctitle(title) + try: + yield + finally: + if _mode() is not LOCAL_MODE: + ray._raylet.setproctitle(next_title) + + +@DeveloperAPI +def show_in_dashboard(message: str, key: str = "", dtype: str = "text"): + """Display message in dashboard. + + Display message for the current task or actor in the dashboard. + For example, this can be used to display the status of a long-running + computation. + + Args: + message: Message to be displayed. + key: The key name for the message. Multiple message under + different keys will be displayed at the same time. Messages + under the same key will be overridden. + dtype: The type of message for rendering. One of the + following: text, html. + """ + worker = global_worker + worker.check_connected() + + acceptable_dtypes = {"text", "html"} + assert dtype in acceptable_dtypes, f"dtype accepts only: {acceptable_dtypes}" + + message_wrapped = {"message": message, "dtype": dtype} + message_encoded = json.dumps(message_wrapped).encode() + + worker.core_worker.set_webui_display(key.encode(), message_encoded) + + +# Global variable to make sure we only send out the warning once. +blocking_get_inside_async_warned = False + + +@overload +def get( + object_refs: "Sequence[ObjectRef[Any]]", *, timeout: Optional[float] = None +) -> List[Any]: + ... + + +@overload +def get( + object_refs: "Sequence[ObjectRef[R]]", *, timeout: Optional[float] = None +) -> List[R]: + ... + + +@overload +def get(object_refs: "ObjectRef[R]", *, timeout: Optional[float] = None) -> R: + ... + + +@overload +def get( + object_refs: Sequence[CompiledDAGRef], *, timeout: Optional[float] = None +) -> List[Any]: + ... + + +@overload +def get(object_refs: CompiledDAGRef, *, timeout: Optional[float] = None) -> Any: + ... + + +@PublicAPI +@client_mode_hook +def get( + object_refs: Union[ + "ObjectRef[Any]", + Sequence["ObjectRef[Any]"], + CompiledDAGRef, + Sequence[CompiledDAGRef], + ], + *, + timeout: Optional[float] = None, +) -> Union[Any, List[Any]]: + """Get a remote object or a list of remote objects from the object store. + + This method blocks until the object corresponding to the object ref is + available in the local object store. If this object is not in the local + object store, it will be shipped from an object store that has it (once the + object has been created). If object_refs is a list, then the objects + corresponding to each object in the list will be returned. + + Ordering for an input list of object refs is preserved for each object + returned. That is, if an object ref to A precedes an object ref to B in the + input list, then A will precede B in the returned list. + + This method will issue a warning if it's running inside async context, + you can use ``await object_ref`` instead of ``ray.get(object_ref)``. For + a list of object refs, you can use ``await asyncio.gather(*object_refs)``. + + Passing :class:`~ObjectRefGenerator` is not allowed. + + Related patterns and anti-patterns: + + - :doc:`/ray-core/patterns/ray-get-loop` + - :doc:`/ray-core/patterns/unnecessary-ray-get` + - :doc:`/ray-core/patterns/ray-get-submission-order` + - :doc:`/ray-core/patterns/ray-get-too-many-objects` + + + Args: + object_refs: Object ref of the object to get or a list of object refs + to get. + timeout (Optional[float]): The maximum amount of time in seconds to + wait before returning. Set this to None will block until the + corresponding object becomes available. Setting ``timeout=0`` will + return the object immediately if it's available, else raise + GetTimeoutError in accordance with the above docstring. + + Returns: + A Python object or a list of Python objects. + + Raises: + GetTimeoutError: A GetTimeoutError is raised if a timeout is set and + the get takes longer than timeout to return. + Exception: An exception is raised immediately if any task that created + the object or that created one of the objects raised an exception, + without waiting for the remaining ones to finish. + """ + worker = global_worker + worker.check_connected() + + if hasattr(worker, "core_worker") and worker.core_worker.current_actor_is_asyncio(): + global blocking_get_inside_async_warned + if not blocking_get_inside_async_warned: + logger.warning( + "Using blocking ray.get inside async actor. " + "This blocks the event loop. Please use `await` " + "on object ref with asyncio.gather if you want to " + "yield execution to the event loop instead." + ) + blocking_get_inside_async_warned = True + + with profiling.profile("ray.get"): + # TODO(sang): Should make ObjectRefGenerator + # compatible to ray.get for dataset. + if isinstance(object_refs, ObjectRefGenerator): + return object_refs + + if isinstance(object_refs, CompiledDAGRef): + return object_refs.get(timeout=timeout) + + if isinstance(object_refs, list): + all_compiled_dag_refs = True + any_compiled_dag_refs = False + for object_ref in object_refs: + is_dag_ref = isinstance(object_ref, CompiledDAGRef) + all_compiled_dag_refs = all_compiled_dag_refs and is_dag_ref + any_compiled_dag_refs = any_compiled_dag_refs or is_dag_ref + if all_compiled_dag_refs: + return [object_ref.get(timeout=timeout) for object_ref in object_refs] + elif any_compiled_dag_refs: + raise ValueError( + "Invalid type of object refs. 'object_refs' must be a list of " + "CompiledDAGRefs if there is any CompiledDAGRef within it. " + ) + + is_individual_id = isinstance(object_refs, ray.ObjectRef) + if is_individual_id: + object_refs = [object_refs] + + if not isinstance(object_refs, list): + raise ValueError( + f"Invalid type of object refs, {type(object_refs)}, is given. " + "'object_refs' must either be an ObjectRef or a list of ObjectRefs. " + ) + + # TODO(ujvl): Consider how to allow user to retrieve the ready objects. + values, debugger_breakpoint = worker.get_objects(object_refs, timeout=timeout) + for i, value in enumerate(values): + if isinstance(value, RayError): + if isinstance(value, ray.exceptions.ObjectLostError): + worker.core_worker.dump_object_store_memory_usage() + if isinstance(value, RayTaskError): + raise value.as_instanceof_cause() + else: + raise value + + if is_individual_id: + values = values[0] + + if debugger_breakpoint != b"": + frame = sys._getframe().f_back + rdb = ray.util.pdb._connect_ray_pdb( + host=None, + port=None, + patch_stdstreams=False, + quiet=None, + breakpoint_uuid=( + debugger_breakpoint.decode() if debugger_breakpoint else None + ), + debugger_external=worker.ray_debugger_external, + ) + rdb.set_trace(frame=frame) + + return values + + +@PublicAPI +@client_mode_hook +def put( + value: Any, + *, + _owner: Optional["ray.actor.ActorHandle"] = None, +) -> "ray.ObjectRef": + """Store an object in the object store. + + The object may not be evicted while a reference to the returned ID exists. + + Related patterns and anti-patterns: + + - :doc:`/ray-core/patterns/return-ray-put` + - :doc:`/ray-core/patterns/pass-large-arg-by-value` + - :doc:`/ray-core/patterns/closure-capture-large-objects` + + Args: + value: The Python object to be stored. + _owner [Experimental]: The actor that should own this object. This + allows creating objects with lifetimes decoupled from that of the + creating process. The owner actor must be passed a reference to the + object prior to the object creator exiting, otherwise the reference + will still be lost. *Note that this argument is an experimental API + and should be avoided if possible.* + + Returns: + The object ref assigned to this value. + """ + worker = global_worker + worker.check_connected() + + if _owner is None: + serialize_owner_address = None + elif isinstance(_owner, ray.actor.ActorHandle): + # Ensure `ray._private.state.state.global_state_accessor` is not None + ray._private.state.state._check_connected() + serialize_owner_address = ( + ray._raylet._get_actor_serialized_owner_address_or_none( + ray._private.state.state.global_state_accessor.get_actor_info( + _owner._actor_id + ) + ) + ) + if not serialize_owner_address: + raise RuntimeError(f"{_owner} is not alive, it's worker_id is empty!") + else: + raise TypeError(f"Expect an `ray.actor.ActorHandle`, but got: {type(_owner)}") + + with profiling.profile("ray.put"): + try: + object_ref = worker.put_object(value, owner_address=serialize_owner_address) + except ObjectStoreFullError: + logger.info( + "Put failed since the value was either too large or the " + "store was full of pinned objects." + ) + raise + return object_ref + + +# Global variable to make sure we only send out the warning once. +blocking_wait_inside_async_warned = False + + +@PublicAPI +@client_mode_hook +def wait( + ray_waitables: List[Union[ObjectRef, ObjectRefGenerator]], + *, + num_returns: int = 1, + timeout: Optional[float] = None, + fetch_local: bool = True, +) -> Tuple[ + List[Union[ObjectRef, ObjectRefGenerator]], + List[Union[ObjectRef, ObjectRefGenerator]], +]: + """Return a list of IDs that are ready and a list of IDs that are not. + + If timeout is set, the function returns either when the requested number of + IDs are ready or when the timeout is reached, whichever occurs first. If it + is not set, the function simply waits until that number of objects is ready + and returns that exact number of object refs. + + `ray_waitables` is a list of :class:`~ray.ObjectRef` and + :class:`~ray.ObjectRefGenerator`. + + The method returns two lists, ready and unready `ray_waitables`. + + ObjectRef: + object refs that correspond to objects that are available + in the object store are in the first list. + The rest of the object refs are in the second list. + + ObjectRefGenerator: + Generators whose next reference (that will be obtained + via `next(generator)`) has a corresponding object available + in the object store are in the first list. + All other generators are placed in the second list. + + Ordering of the input list of ray_waitables is preserved. That is, if A + precedes B in the input list, and both are in the ready list, then A will + precede B in the ready list. This also holds true if A and B are both in + the remaining list. + + This method will issue a warning if it's running inside an async context. + Instead of ``ray.wait(ray_waitables)``, you can use + ``await asyncio.wait(ray_waitables)``. + + Related patterns and anti-patterns: + + - :doc:`/ray-core/patterns/limit-pending-tasks` + - :doc:`/ray-core/patterns/ray-get-submission-order` + + Args: + ray_waitables: List of :class:`~ObjectRef` or + :class:`~ObjectRefGenerator` for objects that may or may + not be ready. Note that these must be unique. + num_returns: The number of ray_waitables that should be returned. + timeout: The maximum amount of time in seconds to wait before + returning. + fetch_local: If True, wait for the object to be downloaded onto + the local node before returning it as ready. If the `ray_waitable` + is a generator, it will wait until the next object in the generator + is downloaed. If False, ray.wait() will not trigger fetching of + objects to the local node and will return immediately once the + object is available anywhere in the cluster. + + Returns: + A list of object refs that are ready and a list of the remaining object + IDs. + """ + worker = global_worker + worker.check_connected() + + if ( + hasattr(worker, "core_worker") + and worker.core_worker.current_actor_is_asyncio() + and timeout != 0 + ): + global blocking_wait_inside_async_warned + if not blocking_wait_inside_async_warned: + logger.debug( + "Using blocking ray.wait inside async method. " + "This blocks the event loop. Please use `await` " + "on object ref with asyncio.wait. " + ) + blocking_wait_inside_async_warned = True + + if isinstance(ray_waitables, ObjectRef) or isinstance( + ray_waitables, ObjectRefGenerator + ): + raise TypeError( + "wait() expected a list of ray.ObjectRef or ray.ObjectRefGenerator" + ", got a single ray.ObjectRef or ray.ObjectRefGenerator " + f"{ray_waitables}" + ) + + if not isinstance(ray_waitables, list): + raise TypeError( + "wait() expected a list of ray.ObjectRef or " + "ray.ObjectRefGenerator, " + f"got {type(ray_waitables)}" + ) + + if timeout is not None and timeout < 0: + raise ValueError( + "The 'timeout' argument must be nonnegative. " f"Received {timeout}" + ) + + for ray_waitable in ray_waitables: + if not isinstance(ray_waitable, ObjectRef) and not isinstance( + ray_waitable, ObjectRefGenerator + ): + raise TypeError( + "wait() expected a list of ray.ObjectRef or " + "ray.ObjectRefGenerator, " + f"got list containing {type(ray_waitable)}" + ) + worker.check_connected() + + # TODO(swang): Check main thread. + with profiling.profile("ray.wait"): + # TODO(rkn): This is a temporary workaround for + # https://github.com/ray-project/ray/issues/997. However, it should be + # fixed in Arrow instead of here. + if len(ray_waitables) == 0: + return [], [] + + if len(ray_waitables) != len(set(ray_waitables)): + raise ValueError("Wait requires a list of unique ray_waitables.") + if num_returns <= 0: + raise ValueError("Invalid number of objects to return %d." % num_returns) + if num_returns > len(ray_waitables): + raise ValueError( + "num_returns cannot be greater than the number " + "of ray_waitables provided to ray.wait." + ) + + timeout = timeout if timeout is not None else 10**6 + timeout_milliseconds = int(timeout * 1000) + ready_ids, remaining_ids = worker.core_worker.wait( + ray_waitables, + num_returns, + timeout_milliseconds, + fetch_local, + ) + return ready_ids, remaining_ids + + +@PublicAPI +@client_mode_hook +def get_actor(name: str, namespace: Optional[str] = None) -> "ray.actor.ActorHandle": + """Get a handle to a named actor. + + Gets a handle to an actor with the given name. The actor must + have been created with Actor.options(name="name").remote(). This + works for both detached & non-detached actors. + + This method is a sync call and it'll timeout after 60s. This can be modified + by setting OS env RAY_gcs_server_request_timeout_seconds before starting + the cluster. + + Args: + name: The name of the actor. + namespace: The namespace of the actor, or None to specify the current + namespace. + + Returns: + ActorHandle to the actor. + + Raises: + ValueError: if the named actor does not exist. + """ + if not name: + raise ValueError("Please supply a non-empty value to get_actor") + + if namespace is not None: + ray._private.utils.validate_namespace(namespace) + + worker = global_worker + worker.check_connected() + return worker.core_worker.get_named_actor_handle(name, namespace or "") + + +@PublicAPI +@client_mode_hook +def kill(actor: "ray.actor.ActorHandle", *, no_restart: bool = True): + """Kill an actor forcefully. + + This will interrupt any running tasks on the actor, causing them to fail + immediately. ``atexit`` handlers installed in the actor will not be run. + + If you want to kill the actor but let pending tasks finish, + you can call ``actor.__ray_terminate__.remote()`` instead to queue a + termination task. Any ``atexit`` handlers installed in the actor *will* + be run in this case. + + If the actor is a detached actor, subsequent calls to get its handle via + ray.get_actor will fail. + + Args: + actor: Handle to the actor to kill. + no_restart: Whether or not this actor should be restarted if + it's a restartable actor. + """ + worker = global_worker + worker.check_connected() + if not isinstance(actor, ray.actor.ActorHandle): + raise ValueError( + "ray.kill() only supported for actors. For tasks, try ray.cancel(). " + "Got: {}.".format(type(actor)) + ) + worker.core_worker.kill_actor(actor._ray_actor_id, no_restart) + + +@PublicAPI +@client_mode_hook +def cancel( + ray_waitable: Union["ObjectRef[R]", "ObjectRefGenerator[R]"], + *, + force: bool = False, + recursive: bool = True, +) -> None: + """Cancels a task. + + Cancel API has a different behavior depending on if it is a remote function + (Task) or a remote Actor method (Actor Task). + + Task: + If the specified Task is pending execution, it is cancelled and not + executed. If the Task is currently executing, the behavior depends + on the `force` flag. When `force=False`, a KeyboardInterrupt is + raised in Python and when `force=True`, the executing Task + immediately exits. If the Task is already finished, nothing happens. + + Cancelled Tasks aren't retried. `max_task_retries` aren't respected. + + Calling ray.get on a cancelled Task raises a TaskCancelledError + if the Task has been scheduled or interrupted. + It raises a WorkerCrashedError if `force=True`. + + If `recursive=True`, all the child Tasks and Actor Tasks + are cancelled. If `force=True` and `recursive=True`, `force=True` + is ignored for child Actor Tasks. + + Actor Task: + If the specified Task is pending execution, it is cancelled and not + executed. If the Task is currently executing, the behavior depends + on the execution model of an Actor. If it is a regular Actor + or a threaded Actor, the execution isn't cancelled. + Actor Tasks cannot be interrupted because Actors have + states. If it is an async Actor, Ray cancels a `asyncio.Task`. + The semantic of cancellation is equivalent to asyncio's cancellation. + https://docs.python.org/3/library/asyncio-task.html#task-cancellation + If the Task has finished, nothing happens. + + Only `force=False` is allowed for an Actor Task. Otherwise, it raises + `ValueError`. Use `ray.kill(actor)` instead to kill an Actor. + + Cancelled Tasks aren't retried. `max_task_retries` aren't respected. + + Calling ray.get on a cancelled Task raises a TaskCancelledError + if the Task has been scheduled or interrupted. Also note that + only async actor tasks can be interrupted. + + If `recursive=True`, all the child Tasks and actor Tasks + are cancelled. + + Args: + ray_waitable: :class:`~ObjectRef` and + :class:`~ObjectRefGenerator` + returned by the task that should be canceled. + force: Whether to force-kill a running task by killing + the worker that is running the task. + recursive: Whether to try to cancel tasks submitted by the + task specified. + """ + worker = ray._private.worker.global_worker + worker.check_connected() + + if isinstance(ray_waitable, ray._raylet.ObjectRefGenerator): + assert hasattr(ray_waitable, "_generator_ref") + ray_waitable = ray_waitable._generator_ref + + if not isinstance(ray_waitable, ray.ObjectRef): + raise TypeError( + "ray.cancel() only supported for object refs. " + f"For actors, try ray.kill(). Got: {type(ray_waitable)}." + ) + return worker.core_worker.cancel_task(ray_waitable, force, recursive) + + +def _mode(worker=global_worker): + """This is a wrapper around worker.mode. + + We use this wrapper so that in the remote decorator, we can call _mode() + instead of worker.mode. The difference is that when we attempt to + serialize remote functions, we don't attempt to serialize the worker + object, which cannot be serialized. + """ + return worker.mode + + +def _make_remote(function_or_class, options): + if not function_or_class.__module__: + function_or_class.__module__ = "global" + + if inspect.isfunction(function_or_class) or is_cython(function_or_class): + ray_option_utils.validate_task_options(options, in_options=False) + return ray.remote_function.RemoteFunction( + Language.PYTHON, + function_or_class, + None, + options, + ) + + if inspect.isclass(function_or_class): + ray_option_utils.validate_actor_options(options, in_options=False) + return ray.actor._make_actor(function_or_class, options) + + raise TypeError( + "The @ray.remote decorator must be applied to either a function or a class." + ) + + +class RemoteDecorator(Protocol): + @overload + def __call__(self, __function: Callable[[], R]) -> RemoteFunctionNoArgs[R]: + ... + + @overload + def __call__(self, __function: Callable[[T0], R]) -> RemoteFunction0[R, T0]: + ... + + @overload + def __call__(self, __function: Callable[[T0, T1], R]) -> RemoteFunction1[R, T0, T1]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2], R] + ) -> RemoteFunction2[R, T0, T1, T2]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2, T3], R] + ) -> RemoteFunction3[R, T0, T1, T2, T3]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2, T3, T4], R] + ) -> RemoteFunction4[R, T0, T1, T2, T3, T4]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2, T3, T4, T5], R] + ) -> RemoteFunction5[R, T0, T1, T2, T3, T4, T5]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2, T3, T4, T5, T6], R] + ) -> RemoteFunction6[R, T0, T1, T2, T3, T4, T5, T6]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7], R] + ) -> RemoteFunction7[R, T0, T1, T2, T3, T4, T5, T6, T7]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8], R] + ) -> RemoteFunction8[R, T0, T1, T2, T3, T4, T5, T6, T7, T8]: + ... + + @overload + def __call__( + self, __function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9], R] + ) -> RemoteFunction9[R, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]: + ... + + # Pass on typing actors for now. The following makes it so no type errors + # are generated for actors. + @overload + def __call__(self, __t: type) -> Any: + ... + + +@overload +def remote(__t: Type[T]) -> ActorClass[T]: + ... + + +@overload +def remote(__function: Callable[[], R]) -> RemoteFunctionNoArgs[R]: + ... + + +@overload +def remote(__function: Callable[[T0], R]) -> RemoteFunction0[R, T0]: + ... + + +@overload +def remote(__function: Callable[[T0, T1], R]) -> RemoteFunction1[R, T0, T1]: + ... + + +@overload +def remote(__function: Callable[[T0, T1, T2], R]) -> RemoteFunction2[R, T0, T1, T2]: + ... + + +@overload +def remote( + __function: Callable[[T0, T1, T2, T3], R] +) -> RemoteFunction3[R, T0, T1, T2, T3]: + ... + + +@overload +def remote( + __function: Callable[[T0, T1, T2, T3, T4], R] +) -> RemoteFunction4[R, T0, T1, T2, T3, T4]: + ... + + +@overload +def remote( + __function: Callable[[T0, T1, T2, T3, T4, T5], R] +) -> RemoteFunction5[R, T0, T1, T2, T3, T4, T5]: + ... + + +@overload +def remote( + __function: Callable[[T0, T1, T2, T3, T4, T5, T6], R] +) -> RemoteFunction6[R, T0, T1, T2, T3, T4, T5, T6]: + ... + + +@overload +def remote( + __function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7], R] +) -> RemoteFunction7[R, T0, T1, T2, T3, T4, T5, T6, T7]: + ... + + +@overload +def remote( + __function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8], R] +) -> RemoteFunction8[R, T0, T1, T2, T3, T4, T5, T6, T7, T8]: + ... + + +@overload +def remote( + __function: Callable[[T0, T1, T2, T3, T4, T5, T6, T7, T8, T9], R] +) -> RemoteFunction9[R, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9]: + ... + + +# Passing options +@overload +def remote( + *, + num_returns: Union[int, Literal["streaming"]] = Undefined, + num_cpus: Union[int, float] = Undefined, + num_gpus: Union[int, float] = Undefined, + resources: Dict[str, float] = Undefined, + accelerator_type: str = Undefined, + memory: Union[int, float] = Undefined, + max_calls: int = Undefined, + max_restarts: int = Undefined, + max_task_retries: int = Undefined, + max_retries: int = Undefined, + runtime_env: Dict[str, Any] = Undefined, + retry_exceptions: bool = Undefined, + scheduling_strategy: Union[ + None, Literal["DEFAULT"], Literal["SPREAD"], PlacementGroupSchedulingStrategy + ] = Undefined, + label_selector: Dict[str, str] = Undefined, +) -> RemoteDecorator: + ... + + +@PublicAPI +def remote( + *args, **kwargs +) -> Union[ray.remote_function.RemoteFunction, ray.actor.ActorClass]: + """Defines a remote function or an actor class. + + This function can be used as a decorator with no arguments + to define a remote function or actor as follows: + + .. testcode:: + + import ray + + @ray.remote + def f(a, b, c): + return a + b + c + + object_ref = f.remote(1, 2, 3) + result = ray.get(object_ref) + assert result == (1 + 2 + 3) + + @ray.remote + class Foo: + def __init__(self, arg): + self.x = arg + + def method(self, a): + return self.x + a + + actor_handle = Foo.remote(123) + object_ref = actor_handle.method.remote(321) + result = ray.get(object_ref) + assert result == (123 + 321) + + Equivalently, use a function call to create a remote function or actor. + + .. testcode:: + + def g(a, b, c): + return a + b + c + + remote_g = ray.remote(g) + object_ref = remote_g.remote(1, 2, 3) + assert ray.get(object_ref) == (1 + 2 + 3) + + class Bar: + def __init__(self, arg): + self.x = arg + + def method(self, a): + return self.x + a + + RemoteBar = ray.remote(Bar) + actor_handle = RemoteBar.remote(123) + object_ref = actor_handle.method.remote(321) + result = ray.get(object_ref) + assert result == (123 + 321) + + + It can also be used with specific keyword arguments as follows: + + .. testcode:: + + @ray.remote(num_gpus=1, max_calls=1, num_returns=2) + def f(): + return 1, 2 + + @ray.remote(num_cpus=2, resources={"CustomResource": 1}) + class Foo: + def method(self): + return 1 + + Remote task and actor objects returned by @ray.remote can also be + dynamically modified with the same arguments as above using + ``.options()`` as follows: + + .. testcode:: + :hide: + + ray.shutdown() + + ray.init(num_cpus=5, num_gpus=5) + + .. testcode:: + + @ray.remote(num_gpus=1, max_calls=1, num_returns=2) + def f(): + return 1, 2 + + f_with_2_gpus = f.options(num_gpus=2) + object_refs = f_with_2_gpus.remote() + assert ray.get(object_refs) == [1, 2] + + @ray.remote(num_cpus=2, resources={"CustomResource": 1}) + class Foo: + def method(self): + return 1 + + Foo_with_no_resources = Foo.options(num_cpus=1, resources=None) + foo_actor = Foo_with_no_resources.remote() + assert ray.get(foo_actor.method.remote()) == 1 + + + A remote actor will be terminated when all actor handle to it + in Python is deleted, which will cause them to complete any outstanding + work and then shut down. If you only have 1 reference to an actor handle, + calling ``del actor`` *could* trigger actor deletion. Note that your program + may have multiple references to the same ActorHandle, and actor termination + will not occur until the reference count goes to 0. See the Python + documentation for more context about object deletion. + https://docs.python.org/3.9/reference/datamodel.html#object.__del__ + + If you want to kill actors immediately, you can also call ``ray.kill(actor)``. + + .. tip:: + Avoid repeatedly passing in large arguments to remote task or method calls. + + Instead, use ray.put to create a copy of the object in the object store. + + See :ref:`more info here `. + + Args: + num_returns: This is only for *remote functions*. It specifies + the number of object refs returned by the remote function + invocation. The default value is 1. + Pass "dynamic" to allow the task to decide how many + return values to return during execution, and the caller will + receive an ObjectRef[DynamicObjectRefGenerator]. + See :ref:`dynamic generators ` for more details. + num_cpus: The quantity of CPU resources to reserve + for this task or for the lifetime of the actor. + By default, tasks use 1 CPU resource and actors use 1 CPU + for scheduling and 0 CPU for running + (This means, by default, actors cannot get scheduled on a zero-cpu node, + but an infinite number of them can run on any non-zero cpu node. + The default value for actors was chosen for historical reasons. + It's recommended to always explicitly set num_cpus for actors + to avoid any surprises. + If resources are specified explicitly, + they are required for both scheduling and running.) + See :ref:`specifying resource requirements ` + for more details. + num_gpus: The quantity of GPU resources to reserve + for this task or for the lifetime of the actor. + The default value is 0. + See :ref:`Ray GPU support ` for more details. + resources (Dict[str, float]): The quantity of various + :ref:`custom resources ` + to reserve for this task or for the lifetime of the actor. + This is a dictionary mapping strings (resource names) to floats. + By default it is empty. + label_selector (Dict[str, str]): [Experimental] If specified, the labels required for the node on + which this actor can be scheduled on. The label selector consist of key-value pairs, + where the keys are label names and the value are expressions consisting of an operator + with label values or just a value to indicate equality. + accelerator_type: If specified, requires that the task or actor run + on a node with the specified type of accelerator. + See :ref:`accelerator types `. + memory: The heap memory request in bytes for this task/actor, + rounded down to the nearest integer. + max_calls: Only for *remote functions*. This specifies the + maximum number of times that a given worker can execute + the given remote function before it must exit + (this can be used to address :ref:`memory leaks ` in third-party + libraries or to reclaim resources that cannot easily be + released, e.g., GPU memory that was acquired by TensorFlow). + By default this is infinite for CPU tasks and 1 for GPU tasks + (to force GPU tasks to release resources after finishing). + max_restarts: Only for *actors*. This specifies the maximum + number of times that the actor should be restarted when it dies + unexpectedly. The minimum valid value is 0 (default), + which indicates that the actor doesn't need to be restarted. + A value of -1 indicates that an actor should be restarted + indefinitely. + See :ref:`actor fault tolerance ` for more details. + max_task_retries: Only for *actors*. How many times to + retry an actor task if the task fails due to a system error, + e.g., the actor has died. If set to -1, the system will + retry the failed task until the task succeeds, or the actor + has reached its max_restarts limit. If set to `n > 0`, the + system will retry the failed task up to n times, after which the + task will throw a `RayActorError` exception upon :obj:`ray.get`. + Note that Python exceptions are not considered system errors + and will not trigger retries. + The default value is 0. + See :ref:`actor fault tolerance ` for more details. + max_retries: Only for *remote functions*. This specifies + the maximum number of times that the remote function + should be rerun when the worker process executing it + crashes unexpectedly. The minimum valid value is 0, + the default value is 3, and a value of -1 indicates + infinite retries. + See :ref:`task fault tolerance ` for more details. + runtime_env (Dict[str, Any]): Specifies the runtime environment for + this actor or task and its children. See + :ref:`runtime-environments` for detailed documentation. + retry_exceptions: Only for *remote functions*. This specifies whether + application-level errors should be retried up to max_retries times. + This can be a boolean or a list of exceptions that should be retried. + See :ref:`task fault tolerance ` for more details. + scheduling_strategy: Strategy about how to + schedule a remote function or actor. Possible values are + None: ray will figure out the scheduling strategy to use, it + will either be the PlacementGroupSchedulingStrategy using parent's + placement group if parent has one and has + placement_group_capture_child_tasks set to true, + or "DEFAULT"; + "DEFAULT": default hybrid scheduling; + "SPREAD": best effort spread scheduling; + `PlacementGroupSchedulingStrategy`: + placement group based scheduling; + `NodeAffinitySchedulingStrategy`: + node id based affinity scheduling. + See :ref:`Ray scheduling strategies ` + for more details. + _metadata: Extended options for Ray libraries. For example, + _metadata={"workflows.io/options": } for Ray workflows. + _labels: The key-value labels of a task or actor. + """ + # "callable" returns true for both function and class. + if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): + # This is the case where the decorator is just @ray.remote. + # "args[0]" is the class or function under the decorator. + return _make_remote(args[0], {}) + assert len(args) == 0 and len(kwargs) > 0, ray_option_utils.remote_args_error_string + return functools.partial(_make_remote, options=kwargs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/default_worker.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/default_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..11c4c02e0d2577cbc8b13f31681ae15fb8b4ac70 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/default_worker.py @@ -0,0 +1,328 @@ +import argparse +import base64 +import json +import os +import sys +import time + +import ray +import ray._private.node +import ray._private.ray_constants as ray_constants +import ray._private.utils +import ray.actor +from ray._private.async_compat import try_install_uvloop +from ray._private.parameter import RayParams +from ray._private.ray_logging import get_worker_log_file_name +from ray._private.runtime_env.setup_hook import load_and_execute_setup_hook + +parser = argparse.ArgumentParser( + description=("Parse addresses for the worker to connect to.") +) +parser.add_argument( + "--cluster-id", + required=True, + type=str, + help="the auto-generated ID of the cluster", +) +parser.add_argument( + "--node-id", + required=True, + type=str, + help="the auto-generated ID of the node", +) +parser.add_argument( + "--node-ip-address", + required=True, + type=str, + help="the ip address of the worker's node", +) +parser.add_argument( + "--node-manager-port", required=True, type=int, help="the port of the worker's node" +) +parser.add_argument( + "--raylet-ip-address", + required=False, + type=str, + default=None, + help="the ip address of the worker's raylet", +) +parser.add_argument( + "--redis-address", required=True, type=str, help="the address to use for Redis" +) +parser.add_argument( + "--gcs-address", required=True, type=str, help="the address to use for GCS" +) +parser.add_argument( + "--redis-username", + required=False, + type=str, + default=None, + help="the username to use for Redis", +) +parser.add_argument( + "--redis-password", + required=False, + type=str, + default=None, + help="the password to use for Redis", +) +parser.add_argument( + "--object-store-name", required=True, type=str, help="the object store's name" +) +parser.add_argument("--raylet-name", required=False, type=str, help="the raylet's name") +parser.add_argument( + "--logging-level", + required=False, + type=str, + default=ray_constants.LOGGER_LEVEL, + choices=ray_constants.LOGGER_LEVEL_CHOICES, + help=ray_constants.LOGGER_LEVEL_HELP, +) +parser.add_argument( + "--logging-format", + required=False, + type=str, + default=ray_constants.LOGGER_FORMAT, + help=ray_constants.LOGGER_FORMAT_HELP, +) +parser.add_argument( + "--temp-dir", + required=False, + type=str, + default=None, + help="Specify the path of the temporary directory use by Ray process.", +) +parser.add_argument( + "--load-code-from-local", + default=False, + action="store_true", + help="True if code is loaded from local files, as opposed to the GCS.", +) +parser.add_argument( + "--worker-type", + required=False, + type=str, + default="WORKER", + help="Specify the type of the worker process", +) +parser.add_argument( + "--metrics-agent-port", + required=True, + type=int, + help="the port of the node's metric agent.", +) +parser.add_argument( + "--runtime-env-agent-port", + required=True, + type=int, + default=None, + help="The port on which the runtime env agent receives HTTP requests.", +) +parser.add_argument( + "--object-spilling-config", + required=False, + type=str, + default="", + help="The configuration of object spilling. Only used by I/O workers.", +) +parser.add_argument( + "--logging-rotate-bytes", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BYTES, + help="Specify the max bytes for rotating " + "log file, default is " + f"{ray_constants.LOGGING_ROTATE_BYTES} bytes.", +) +parser.add_argument( + "--logging-rotate-backup-count", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT, + help="Specify the backup count of rotated log file, default is " + f"{ray_constants.LOGGING_ROTATE_BACKUP_COUNT}.", +) +parser.add_argument( + "--runtime-env-hash", + required=False, + type=int, + default=0, + help="The computed hash of the runtime env for this worker.", +) +parser.add_argument( + "--startup-token", + required=True, + type=int, + help="The startup token assigned to this worker process by the raylet.", +) +parser.add_argument( + "--ray-debugger-external", + default=False, + action="store_true", + help="True if Ray debugger is made available externally.", +) +parser.add_argument("--session-name", required=False, help="The current session name") +parser.add_argument( + "--webui", + required=False, + help="The address of web ui", +) +parser.add_argument( + "--worker-launch-time-ms", + required=True, + type=int, + help="The time when raylet starts to launch the worker process.", +) + +parser.add_argument( + "--worker-preload-modules", + type=str, + required=False, + help=( + "A comma-separated list of Python module names " + "to import before accepting work." + ), +) +parser.add_argument( + "--enable-resource-isolation", + type=bool, + required=False, + default=False, + help=( + "If true, core worker enables resource isolation by adding itself into appropriate cgroup." + ), +) + +if __name__ == "__main__": + # NOTE(sang): For some reason, if we move the code below + # to a separate function, tensorflow will capture that method + # as a step function. For more details, check out + # https://github.com/ray-project/ray/pull/12225#issue-525059663. + args = parser.parse_args() + ray._private.ray_logging.setup_logger(args.logging_level, args.logging_format) + worker_launched_time_ms = time.time_ns() // 1e6 + if args.worker_type == "WORKER": + mode = ray.WORKER_MODE + elif args.worker_type == "SPILL_WORKER": + mode = ray.SPILL_WORKER_MODE + elif args.worker_type == "RESTORE_WORKER": + mode = ray.RESTORE_WORKER_MODE + else: + raise ValueError("Unknown worker type: " + args.worker_type) + + # Try installing uvloop as default event-loop implementation + # for asyncio + try_install_uvloop() + + raylet_ip_address = args.raylet_ip_address + if raylet_ip_address is None: + raylet_ip_address = args.node_ip_address + ray_params = RayParams( + node_ip_address=args.node_ip_address, + raylet_ip_address=raylet_ip_address, + node_manager_port=args.node_manager_port, + redis_address=args.redis_address, + redis_username=args.redis_username, + redis_password=args.redis_password, + plasma_store_socket_name=args.object_store_name, + raylet_socket_name=args.raylet_name, + temp_dir=args.temp_dir, + metrics_agent_port=args.metrics_agent_port, + runtime_env_agent_port=args.runtime_env_agent_port, + gcs_address=args.gcs_address, + session_name=args.session_name, + webui=args.webui, + cluster_id=args.cluster_id, + node_id=args.node_id, + ) + node = ray._private.node.Node( + ray_params, + head=False, + shutdown_at_exit=False, + spawn_reaper=False, + connect_only=True, + default_worker=True, + ) + + # NOTE(suquark): We must initialize the external storage before we + # connect to raylet. Otherwise we may receive requests before the + # external storage is initialized. + if mode == ray.RESTORE_WORKER_MODE or mode == ray.SPILL_WORKER_MODE: + from ray._private import external_storage + + if args.object_spilling_config: + object_spilling_config = base64.b64decode(args.object_spilling_config) + object_spilling_config = json.loads(object_spilling_config) + else: + object_spilling_config = {} + external_storage.setup_external_storage( + object_spilling_config, node.node_id, node.session_name + ) + + ray._private.worker._global_node = node + ray._private.worker.connect( + node, + node.session_name, + mode=mode, + runtime_env_hash=args.runtime_env_hash, + startup_token=args.startup_token, + ray_debugger_external=args.ray_debugger_external, + worker_launch_time_ms=args.worker_launch_time_ms, + worker_launched_time_ms=worker_launched_time_ms, + enable_resource_isolation=args.enable_resource_isolation, + ) + + worker = ray._private.worker.global_worker + + stdout_fileno = sys.stdout.fileno() + stderr_fileno = sys.stderr.fileno() + # We also manually set sys.stdout and sys.stderr because that seems to + # have an effect on the output buffering. Without doing this, stdout + # and stderr are heavily buffered resulting in seemingly lost logging + # statements. We never want to close the stdout file descriptor, dup2 will + # close it when necessary and we don't want python's GC to close it. + sys.stdout = ray._private.utils.open_log( + stdout_fileno, unbuffered=True, closefd=False + ) + sys.stderr = ray._private.utils.open_log( + stderr_fileno, unbuffered=True, closefd=False + ) + + # Setup log file. + out_filepath, err_filepath = node.get_log_file_names( + get_worker_log_file_name(args.worker_type), + unique=False, # C++ core worker process already creates the file, should use a deterministic function to get the same file path. + create_out=True, + create_err=True, + ) + worker.set_out_file(out_filepath) + worker.set_err_file(err_filepath) + + rotation_max_bytes = os.getenv("RAY_ROTATION_MAX_BYTES", None) + + # Log rotation is disabled on windows platform. + if sys.platform != "win32" and rotation_max_bytes and int(rotation_max_bytes) > 0: + worker.set_file_rotation_enabled(True) + + if mode == ray.WORKER_MODE and args.worker_preload_modules: + module_names_to_import = args.worker_preload_modules.split(",") + ray._private.utils.try_import_each_module(module_names_to_import) + + # If the worker setup function is configured, run it. + worker_process_setup_hook_key = os.getenv( + ray_constants.WORKER_PROCESS_SETUP_HOOK_ENV_VAR + ) + if worker_process_setup_hook_key: + error = load_and_execute_setup_hook(worker_process_setup_hook_key) + if error is not None: + worker.core_worker.drain_and_exit_worker("system", error) + + if mode == ray.WORKER_MODE: + worker.main_loop() + elif mode in [ray.RESTORE_WORKER_MODE, ray.SPILL_WORKER_MODE]: + # It is handled by another thread in the C++ core worker. + # We just need to keep the worker alive. + while True: + time.sleep(100000) + else: + raise ValueError(f"Unexcepted worker mode: {mode}") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/setup_worker.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/setup_worker.py new file mode 100644 index 0000000000000000000000000000000000000000..23ba980a5bb22b2ce648c6df45f8ba0b7e73f3dd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/_private/workers/setup_worker.py @@ -0,0 +1,33 @@ +import argparse +import logging + +from ray._private.ray_constants import LOGGER_FORMAT, LOGGER_LEVEL +from ray._private.ray_logging import setup_logger +from ray._private.runtime_env.context import RuntimeEnvContext +from ray.core.generated.common_pb2 import Language + +logger = logging.getLogger(__name__) + +parser = argparse.ArgumentParser( + description=("Set up the environment for a Ray worker and launch the worker.") +) + +parser.add_argument( + "--serialized-runtime-env-context", + type=str, + help="the serialized runtime env context", +) + +parser.add_argument("--language", type=str, help="the language type of the worker") + + +if __name__ == "__main__": + setup_logger(LOGGER_LEVEL, LOGGER_FORMAT) + args, remaining_args = parser.parse_known_args() + # NOTE(edoakes): args.serialized_runtime_env_context is only None when + # we're starting the main Ray client proxy server. That case should + # probably not even go through this codepath. + runtime_env_context = RuntimeEnvContext.deserialize( + args.serialized_runtime_env_context or "{}" + ) + runtime_env_context.exec_worker(remaining_args, Language.Value(args.language)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..67f41865b669ca092c3a4f63791375a1b1b3f25b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/__init__.py @@ -0,0 +1,21 @@ +from ray.air.config import ( + CheckpointConfig, + FailureConfig, + RunConfig, + ScalingConfig, +) +from ray.air.data_batch_type import DataBatchType +from ray.air.execution.resources.request import AcquiredResources, ResourceRequest +from ray.air.result import Result +import ray.data # noqa: F401 # TODO: This is a hack to avoid circular import + +__all__ = [ + "DataBatchType", + "RunConfig", + "Result", + "ScalingConfig", + "FailureConfig", + "CheckpointConfig", + "AcquiredResources", + "ResourceRequest", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/config.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/config.py new file mode 100644 index 0000000000000000000000000000000000000000..3f7599d54c0925dfb2402292768aab548feb93ab --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/config.py @@ -0,0 +1,696 @@ +import logging +from collections import Counter, defaultdict +from dataclasses import _MISSING_TYPE, dataclass, fields +import os +from pathlib import Path +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Mapping, + Optional, + Tuple, + Union, +) +import warnings + +import pyarrow.fs + +import ray +from ray._common.utils import RESOURCE_CONSTRAINT_PREFIX +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.util.annotations import PublicAPI, RayDeprecationWarning +from ray.widgets import Template, make_table_html_repr + +if TYPE_CHECKING: + from ray.tune.callback import Callback + from ray.tune.execution.placement_groups import PlacementGroupFactory + from ray.tune.experimental.output import AirVerbosity + from ray.tune.search.sample import Domain + from ray.tune.stopper import Stopper + from ray.tune.utils.log import Verbosity + + +# Dict[str, List] is to support `tune.grid_search`: +# TODO(sumanthratna/matt): Upstream this to Tune. +SampleRange = Union["Domain", Dict[str, List]] + + +MAX = "max" +MIN = "min" +_DEPRECATED_VALUE = "DEPRECATED" + + +logger = logging.getLogger(__name__) + + +def _repr_dataclass(obj, *, default_values: Optional[Dict[str, Any]] = None) -> str: + """A utility function to elegantly represent dataclasses. + + In contrast to the default dataclass `__repr__`, which shows all parameters, this + function only shows parameters with non-default values. + + Args: + obj: The dataclass to represent. + default_values: An optional dictionary that maps field names to default values. + Use this parameter to specify default values that are generated dynamically + (e.g., in `__post_init__` or by a `default_factory`). If a default value + isn't specified in `default_values`, then the default value is inferred from + the `dataclass`. + + Returns: + A representation of the dataclass. + """ + if default_values is None: + default_values = {} + + non_default_values = {} # Maps field name to value. + + def equals(value, default_value): + # We need to special case None because of a bug in pyarrow: + # https://github.com/apache/arrow/issues/38535 + if value is None and default_value is None: + return True + if value is None or default_value is None: + return False + return value == default_value + + for field in fields(obj): + value = getattr(obj, field.name) + default_value = default_values.get(field.name, field.default) + is_required = isinstance(field.default, _MISSING_TYPE) + if is_required or not equals(value, default_value): + non_default_values[field.name] = value + + string = f"{obj.__class__.__name__}(" + string += ", ".join( + f"{name}={value!r}" for name, value in non_default_values.items() + ) + string += ")" + + return string + + +@dataclass +@PublicAPI(stability="stable") +class ScalingConfig: + """Configuration for scaling training. + + For more details, see :ref:`train_scaling_config`. + + Args: + trainer_resources: Resources to allocate for the training coordinator. + The training coordinator launches the worker group and executes + the training function per worker, and this process does NOT require + GPUs. The coordinator is always scheduled on the same node as the + rank 0 worker, so one example use case is to set a minimum amount + of resources (e.g. CPU memory) required by the rank 0 node. + By default, this assigns 1 CPU to the training coordinator. + num_workers: The number of workers (Ray actors) to launch. + Each worker will reserve 1 CPU by default. The number of CPUs + reserved by each worker can be overridden with the + ``resources_per_worker`` argument. + use_gpu: If True, training will be done on GPUs (1 per worker). + Defaults to False. The number of GPUs reserved by each + worker can be overridden with the ``resources_per_worker`` + argument. + resources_per_worker: If specified, the resources + defined in this Dict is reserved for each worker. + Define the ``"CPU"`` key (case-sensitive) to + override the number of CPUs used by each worker. + This can also be used to request :ref:`custom resources `. + placement_strategy: The placement strategy to use for the + placement group of the Ray actors. See :ref:`Placement Group + Strategies ` for the possible options. + accelerator_type: [Experimental] If specified, Ray Train will launch the + training coordinator and workers on the nodes with the specified type + of accelerators. + See :ref:`the available accelerator types `. + Ensure that your cluster has instances with the specified accelerator type + or is able to autoscale to fulfill the request. + + Example: + + .. code-block:: python + + from ray.train import ScalingConfig + scaling_config = ScalingConfig( + # Number of distributed workers. + num_workers=2, + # Turn on/off GPU. + use_gpu=True, + # Assign extra CPU/GPU/custom resources per worker. + resources_per_worker={"GPU": 1, "CPU": 1, "memory": 1e9, "custom": 1.0}, + # Try to schedule workers on different nodes. + placement_strategy="SPREAD", + ) + + """ + + trainer_resources: Optional[Union[Dict, SampleRange]] = None + num_workers: Union[int, SampleRange] = 1 + use_gpu: Union[bool, SampleRange] = False + resources_per_worker: Optional[Union[Dict, SampleRange]] = None + placement_strategy: Union[str, SampleRange] = "PACK" + accelerator_type: Optional[str] = None + + def __post_init__(self): + if self.resources_per_worker: + if not self.use_gpu and self.num_gpus_per_worker > 0: + raise ValueError( + "`use_gpu` is False but `GPU` was found in " + "`resources_per_worker`. Either set `use_gpu` to True or " + "remove `GPU` from `resources_per_worker." + ) + + if self.use_gpu and self.num_gpus_per_worker == 0: + raise ValueError( + "`use_gpu` is True but `GPU` is set to 0 in " + "`resources_per_worker`. Either set `use_gpu` to False or " + "request a positive number of `GPU` in " + "`resources_per_worker." + ) + + def __repr__(self): + return _repr_dataclass(self) + + def _repr_html_(self) -> str: + return make_table_html_repr(obj=self, title=type(self).__name__) + + def __eq__(self, o: "ScalingConfig") -> bool: + if not isinstance(o, type(self)): + return False + return self.as_placement_group_factory() == o.as_placement_group_factory() + + @property + def _resources_per_worker_not_none(self): + if self.resources_per_worker is None: + if self.use_gpu: + # Note that we don't request any CPUs, which avoids possible + # scheduling contention. Generally nodes have many more CPUs than + # GPUs, so not requesting a CPU does not lead to oversubscription. + resources_per_worker = {"GPU": 1} + else: + resources_per_worker = {"CPU": 1} + else: + resources_per_worker = { + k: v for k, v in self.resources_per_worker.items() if v != 0 + } + + if self.use_gpu: + resources_per_worker.setdefault("GPU", 1) + + if self.accelerator_type: + accelerator = f"{RESOURCE_CONSTRAINT_PREFIX}{self.accelerator_type}" + resources_per_worker.setdefault(accelerator, 0.001) + return resources_per_worker + + @property + def _trainer_resources_not_none(self): + if self.trainer_resources is None: + if self.num_workers: + # For Google Colab, don't allocate resources to the base Trainer. + # Colab only has 2 CPUs, and because of this resource scarcity, + # we have to be careful on where we allocate resources. Since Colab + # is not distributed, the concern about many parallel Ray Tune trials + # leading to all Trainers being scheduled on the head node if we set + # `trainer_resources` to 0 is no longer applicable. + try: + import google.colab # noqa: F401 + + trainer_num_cpus = 0 + except ImportError: + trainer_num_cpus = 1 + else: + # If there are no additional workers, then always reserve 1 CPU for + # the Trainer. + trainer_num_cpus = 1 + + trainer_resources = {"CPU": trainer_num_cpus} + else: + trainer_resources = { + k: v for k, v in self.trainer_resources.items() if v != 0 + } + + return trainer_resources + + @property + def total_resources(self): + """Map of total resources required for the trainer.""" + total_resource_map = defaultdict(float, self._trainer_resources_not_none) + for k, value in self._resources_per_worker_not_none.items(): + total_resource_map[k] += value * self.num_workers + return dict(total_resource_map) + + @property + def num_cpus_per_worker(self): + """The number of CPUs to set per worker.""" + return self._resources_per_worker_not_none.get("CPU", 0) + + @property + def num_gpus_per_worker(self): + """The number of GPUs to set per worker.""" + return self._resources_per_worker_not_none.get("GPU", 0) + + @property + def additional_resources_per_worker(self): + """Resources per worker, not including CPU or GPU resources.""" + return { + k: v + for k, v in self._resources_per_worker_not_none.items() + if k not in ["CPU", "GPU"] + } + + def as_placement_group_factory(self) -> "PlacementGroupFactory": + """Returns a PlacementGroupFactory to specify resources for Tune.""" + from ray.tune.execution.placement_groups import PlacementGroupFactory + + trainer_bundle = self._trainer_resources_not_none + worker_bundle = self._resources_per_worker_not_none + + # Colocate Trainer and rank0 worker by merging their bundles + # Note: This empty bundle is required so that the Tune actor manager schedules + # the Trainable onto the combined bundle while taking none of its resources, + # rather than a non-empty head bundle. + combined_bundle = dict(Counter(trainer_bundle) + Counter(worker_bundle)) + bundles = [{}, combined_bundle] + [worker_bundle] * (self.num_workers - 1) + return PlacementGroupFactory(bundles, strategy=self.placement_strategy) + + @classmethod + def from_placement_group_factory( + cls, pgf: "PlacementGroupFactory" + ) -> "ScalingConfig": + """Create a ScalingConfig from a Tune's PlacementGroupFactory + + Note that this is only needed for ResourceChangingScheduler, which + modifies a trial's PlacementGroupFactory but doesn't propagate + the changes to ScalingConfig. TrainTrainable needs to reconstruct + a ScalingConfig from on the trial's PlacementGroupFactory. + """ + + # pgf.bundles = [{trainer + worker}, {worker}, ..., {worker}] + num_workers = len(pgf.bundles) + combined_resources = pgf.bundles[0] + resources_per_worker = pgf.bundles[-1] + use_gpu = bool(resources_per_worker.get("GPU", False)) + placement_strategy = pgf.strategy + + # In `as_placement_group_factory`, we merged the trainer resource into the + # first worker resources bundle. We need to calculate the resources diff to + # get the trainer resources. + # Note: If there's only one worker, we won't be able to calculate the diff. + # We'll have empty trainer bundle and assign all resources to the worker. + trainer_resources = dict( + Counter(combined_resources) - Counter(resources_per_worker) + ) + + return ScalingConfig( + trainer_resources=trainer_resources, + num_workers=num_workers, + use_gpu=use_gpu, + resources_per_worker=resources_per_worker, + placement_strategy=placement_strategy, + ) + + +@dataclass +@PublicAPI(stability="stable") +class FailureConfig: + """Configuration related to failure handling of each training/tuning run. + + Args: + max_failures: Tries to recover a run at least this many times. + Will recover from the latest checkpoint if present. + Setting to -1 will lead to infinite recovery retries. + Setting to 0 will disable retries. Defaults to 0. + fail_fast: Whether to fail upon the first error. + If fail_fast='raise' provided, the original error during training will be + immediately raised. fail_fast='raise' can easily leak resources and + should be used with caution. + """ + + max_failures: int = 0 + fail_fast: Union[bool, str] = False + + def __post_init__(self): + # Same check as in TuneController + if not (isinstance(self.fail_fast, bool) or self.fail_fast.upper() == "RAISE"): + raise ValueError( + "fail_fast must be one of {bool, 'raise'}. " f"Got {self.fail_fast}." + ) + + # Same check as in tune.run + if self.fail_fast and self.max_failures != 0: + raise ValueError( + f"max_failures must be 0 if fail_fast={repr(self.fail_fast)}." + ) + + def __repr__(self): + return _repr_dataclass(self) + + def _repr_html_(self): + return Template("scrollableTable.html.j2").render( + table=tabulate( + { + "Setting": ["Max failures", "Fail fast"], + "Value": [self.max_failures, self.fail_fast], + }, + tablefmt="html", + showindex=False, + headers="keys", + ), + max_height="none", + ) + + +@dataclass +@PublicAPI(stability="stable") +class CheckpointConfig: + """Configurable parameters for defining the checkpointing strategy. + + Default behavior is to persist all checkpoints to disk. If + ``num_to_keep`` is set, the default retention policy is to keep the + checkpoints with maximum timestamp, i.e. the most recent checkpoints. + + Args: + num_to_keep: The number of checkpoints to keep + on disk for this run. If a checkpoint is persisted to disk after + there are already this many checkpoints, then an existing + checkpoint will be deleted. If this is ``None`` then checkpoints + will not be deleted. Must be >= 1. + checkpoint_score_attribute: The attribute that will be used to + score checkpoints to determine which checkpoints should be kept + on disk when there are greater than ``num_to_keep`` checkpoints. + This attribute must be a key from the checkpoint + dictionary which has a numerical value. Per default, the last + checkpoints will be kept. + checkpoint_score_order: Either "max" or "min". + If "max", then checkpoints with highest values of + ``checkpoint_score_attribute`` will be kept. + If "min", then checkpoints with lowest values of + ``checkpoint_score_attribute`` will be kept. + checkpoint_frequency: Number of iterations between checkpoints. If 0 + this will disable checkpointing. + Please note that most trainers will still save one checkpoint at + the end of training. + This attribute is only supported + by trainers that don't take in custom training loops. + checkpoint_at_end: If True, will save a checkpoint at the end of training. + This attribute is only supported by trainers that don't take in + custom training loops. Defaults to True for trainers that support it + and False for generic function trainables. + _checkpoint_keep_all_ranks: This experimental config is deprecated. + This behavior is now controlled by reporting `checkpoint=None` + in the workers that shouldn't persist a checkpoint. + For example, if you only want the rank 0 worker to persist a checkpoint + (e.g., in standard data parallel training), then you should save and + report a checkpoint if `ray.train.get_context().get_world_rank() == 0` + and `None` otherwise. + _checkpoint_upload_from_workers: This experimental config is deprecated. + Uploading checkpoint directly from the worker is now the default behavior. + """ + + num_to_keep: Optional[int] = None + checkpoint_score_attribute: Optional[str] = None + checkpoint_score_order: Optional[str] = MAX + checkpoint_frequency: Optional[int] = 0 + checkpoint_at_end: Optional[bool] = None + _checkpoint_keep_all_ranks: Optional[bool] = _DEPRECATED_VALUE + _checkpoint_upload_from_workers: Optional[bool] = _DEPRECATED_VALUE + + def __post_init__(self): + if self._checkpoint_keep_all_ranks != _DEPRECATED_VALUE: + raise DeprecationWarning( + "The experimental `_checkpoint_keep_all_ranks` config is deprecated. " + "This behavior is now controlled by reporting `checkpoint=None` " + "in the workers that shouldn't persist a checkpoint. " + "For example, if you only want the rank 0 worker to persist a " + "checkpoint (e.g., in standard data parallel training), " + "then you should save and report a checkpoint if " + "`ray.train.get_context().get_world_rank() == 0` " + "and `None` otherwise." + ) + + if self._checkpoint_upload_from_workers != _DEPRECATED_VALUE: + raise DeprecationWarning( + "The experimental `_checkpoint_upload_from_workers` config is " + "deprecated. Uploading checkpoint directly from the worker is " + "now the default behavior." + ) + + if self.num_to_keep is not None and self.num_to_keep <= 0: + raise ValueError( + f"Received invalid num_to_keep: " + f"{self.num_to_keep}. " + f"Must be None or an integer >= 1." + ) + if self.checkpoint_score_order not in (MAX, MIN): + raise ValueError( + f"checkpoint_score_order must be either " f'"{MAX}" or "{MIN}".' + ) + + if self.checkpoint_frequency < 0: + raise ValueError( + f"checkpoint_frequency must be >=0, got {self.checkpoint_frequency}" + ) + + def __repr__(self): + return _repr_dataclass(self) + + def _repr_html_(self) -> str: + if self.num_to_keep is None: + num_to_keep_repr = "All" + else: + num_to_keep_repr = self.num_to_keep + + if self.checkpoint_score_attribute is None: + checkpoint_score_attribute_repr = "Most recent" + else: + checkpoint_score_attribute_repr = self.checkpoint_score_attribute + + if self.checkpoint_at_end is None: + checkpoint_at_end_repr = "" + else: + checkpoint_at_end_repr = self.checkpoint_at_end + + return Template("scrollableTable.html.j2").render( + table=tabulate( + { + "Setting": [ + "Number of checkpoints to keep", + "Checkpoint score attribute", + "Checkpoint score order", + "Checkpoint frequency", + "Checkpoint at end", + ], + "Value": [ + num_to_keep_repr, + checkpoint_score_attribute_repr, + self.checkpoint_score_order, + self.checkpoint_frequency, + checkpoint_at_end_repr, + ], + }, + tablefmt="html", + showindex=False, + headers="keys", + ), + max_height="none", + ) + + @property + def _tune_legacy_checkpoint_score_attr(self) -> Optional[str]: + """Same as ``checkpoint_score_attr`` in ``tune.run``. + + Only used for Legacy API compatibility. + """ + if self.checkpoint_score_attribute is None: + return self.checkpoint_score_attribute + prefix = "" + if self.checkpoint_score_order == MIN: + prefix = "min-" + return f"{prefix}{self.checkpoint_score_attribute}" + + +@dataclass +@PublicAPI(stability="stable") +class RunConfig: + """Runtime configuration for training and tuning runs. + + Upon resuming from a training or tuning run checkpoint, + Ray Train/Tune will automatically apply the RunConfig from + the previously checkpointed run. + + Args: + name: Name of the trial or experiment. If not provided, will be deduced + from the Trainable. + storage_path: [Beta] Path where all results and checkpoints are persisted. + Can be a local directory or a destination on cloud storage. + For multi-node training/tuning runs, this must be set to a + shared storage location (e.g., S3, NFS). + This defaults to the local ``~/ray_results`` directory. + storage_filesystem: [Beta] A custom filesystem to use for storage. + If this is provided, `storage_path` should be a path with its + prefix stripped (e.g., `s3://bucket/path` -> `bucket/path`). + failure_config: Failure mode configuration. + checkpoint_config: Checkpointing configuration. + sync_config: Configuration object for syncing. See train.SyncConfig. + verbose: 0, 1, or 2. Verbosity mode. + 0 = silent, 1 = default, 2 = verbose. Defaults to 1. + If the ``RAY_AIR_NEW_OUTPUT=1`` environment variable is set, + uses the old verbosity settings: + 0 = silent, 1 = only status updates, 2 = status and brief + results, 3 = status and detailed results. + stop: Stop conditions to consider. Refer to ray.tune.stopper.Stopper + for more info. Stoppers should be serializable. + callbacks: [DeveloperAPI] Callbacks to invoke. + Refer to ray.tune.callback.Callback for more info. + Callbacks should be serializable. + Currently only stateless callbacks are supported for resumed runs. + (any state of the callback will not be checkpointed by Tune + and thus will not take effect in resumed runs). + progress_reporter: [DeveloperAPI] Progress reporter for reporting + intermediate experiment progress. Defaults to CLIReporter if + running in command-line, or JupyterNotebookReporter if running in + a Jupyter notebook. + log_to_file: [DeveloperAPI] Log stdout and stderr to files in + trial directories. If this is `False` (default), no files + are written. If `true`, outputs are written to `trialdir/stdout` + and `trialdir/stderr`, respectively. If this is a single string, + this is interpreted as a file relative to the trialdir, to which + both streams are written. If this is a Sequence (e.g. a Tuple), + it has to have length 2 and the elements indicate the files to + which stdout and stderr are written, respectively. + + """ + + name: Optional[str] = None + storage_path: Optional[str] = None + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None + failure_config: Optional[FailureConfig] = None + checkpoint_config: Optional[CheckpointConfig] = None + sync_config: Optional["ray.train.SyncConfig"] = None + verbose: Optional[Union[int, "AirVerbosity", "Verbosity"]] = None + stop: Optional[Union[Mapping, "Stopper", Callable[[str, Mapping], bool]]] = None + callbacks: Optional[List["Callback"]] = None + progress_reporter: Optional[ + "ray.tune.progress_reporter.ProgressReporter" # noqa: F821 + ] = None + log_to_file: Union[bool, str, Tuple[str, str]] = False + + # Deprecated + local_dir: Optional[str] = None + + def __post_init__(self): + from ray.train import SyncConfig + from ray.train.constants import DEFAULT_STORAGE_PATH + from ray.tune.experimental.output import AirVerbosity, get_air_verbosity + + if self.local_dir is not None: + raise DeprecationWarning( + "The `RunConfig(local_dir)` argument is deprecated. " + "You should set the `RunConfig(storage_path)` instead." + "See the docs: https://docs.ray.io/en/latest/train/user-guides/" + "persistent-storage.html#setting-the-local-staging-directory" + ) + + if self.storage_path is None: + self.storage_path = DEFAULT_STORAGE_PATH + + # TODO(justinvyu): [Deprecated] + ray_storage_uri: Optional[str] = os.environ.get("RAY_STORAGE") + if ray_storage_uri is not None: + logger.info( + "Using configured Ray Storage URI as the `storage_path`: " + f"{ray_storage_uri}" + ) + warnings.warn( + "The `RAY_STORAGE` environment variable is deprecated. " + "Please use `RunConfig(storage_path)` instead.", + RayDeprecationWarning, + stacklevel=2, + ) + self.storage_path = ray_storage_uri + + if not self.failure_config: + self.failure_config = FailureConfig() + + if not self.sync_config: + self.sync_config = SyncConfig() + + if not self.checkpoint_config: + self.checkpoint_config = CheckpointConfig() + + # Save the original verbose value to check for deprecations + self._verbose = self.verbose + if self.verbose is None: + # Default `verbose` value. For new output engine, + # this is AirVerbosity.DEFAULT. + # For old output engine, this is Verbosity.V3_TRIAL_DETAILS + # Todo (krfricke): Currently uses number to pass test_configs::test_repr + self.verbose = get_air_verbosity(AirVerbosity.DEFAULT) or 3 + + if isinstance(self.storage_path, Path): + self.storage_path = self.storage_path.as_posix() + + def __repr__(self): + from ray.train import SyncConfig + + return _repr_dataclass( + self, + default_values={ + "failure_config": FailureConfig(), + "sync_config": SyncConfig(), + "checkpoint_config": CheckpointConfig(), + }, + ) + + def _repr_html_(self) -> str: + reprs = [] + if self.failure_config is not None: + reprs.append( + Template("title_data_mini.html.j2").render( + title="Failure Config", data=self.failure_config._repr_html_() + ) + ) + if self.sync_config is not None: + reprs.append( + Template("title_data_mini.html.j2").render( + title="Sync Config", data=self.sync_config._repr_html_() + ) + ) + if self.checkpoint_config is not None: + reprs.append( + Template("title_data_mini.html.j2").render( + title="Checkpoint Config", data=self.checkpoint_config._repr_html_() + ) + ) + + # Create a divider between each displayed repr + subconfigs = [Template("divider.html.j2").render()] * (2 * len(reprs) - 1) + subconfigs[::2] = reprs + + settings = Template("scrollableTable.html.j2").render( + table=tabulate( + { + "Name": self.name, + "Local results directory": self.local_dir, + "Verbosity": self.verbose, + "Log to file": self.log_to_file, + }.items(), + tablefmt="html", + headers=["Setting", "Value"], + showindex=False, + ), + max_height="300px", + ) + + return Template("title_data.html.j2").render( + title="RunConfig", + data=Template("run_config.html.j2").render( + subconfigs=subconfigs, + settings=settings, + ), + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0e79f848b9f1cbfa7c61f9903abee4e1c4390a4c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/constants.py @@ -0,0 +1,94 @@ +# Key to denote the preprocessor in the checkpoint dict. +PREPROCESSOR_KEY = "_preprocessor" + +# Key to denote the model in the checkpoint dict. +MODEL_KEY = "model" + +# Key to denote which dataset is the evaluation dataset. +# Only used in trainers which do not support multiple +# evaluation datasets. +EVALUATION_DATASET_KEY = "evaluation" + +# Key to denote which dataset is the training dataset. +# This is the dataset that the preprocessor is fit on. +TRAIN_DATASET_KEY = "train" + +# Name to use for the column when representing tensors in table format. +TENSOR_COLUMN_NAME = "__value__" + +# The maximum length of strings returned by `__repr__` for AIR objects constructed with +# default values. +MAX_REPR_LENGTH = int(80 * 1.5) + +# Timeout used when putting exceptions raised by runner thread into the queue. +_ERROR_REPORT_TIMEOUT = 10 + +# Timeout when fetching new results after signaling the training function to continue. +_RESULT_FETCH_TIMEOUT = 0.2 + +# Timeout for fetching exceptions raised by the training function. +_ERROR_FETCH_TIMEOUT = 1 + +# The key used to identify whether we have already warned about ray.air.session +# functions being used outside of the session +SESSION_MISUSE_LOG_ONCE_KEY = "air_warn_session_misuse" + +# Name of attribute in Checkpoint storing current Tune ID for restoring +# training with Ray Train +CHECKPOINT_ID_ATTR = "_current_checkpoint_id" + +# Name of the marker dropped by the Trainable. If a worker detects +# the presence of the marker in the trial dir, it will use lazy +# checkpointing. +LAZY_CHECKPOINT_MARKER_FILE = ".lazy_checkpoint_marker" + + +# The timestamp of when the result is generated. +# Default to when the result is processed by tune. +TIMESTAMP = "timestamp" + +# (Auto-filled) Time in seconds this iteration took to run. +# This may be overridden to override the system-computed time difference. +TIME_THIS_ITER_S = "time_this_iter_s" + +# (Auto-filled) The index of this training iteration. +TRAINING_ITERATION = "training_iteration" + +# File that stores parameters of the trial. +EXPR_PARAM_FILE = "params.json" + +# Pickle File that stores parameters of the trial. +EXPR_PARAM_PICKLE_FILE = "params.pkl" + +# File that stores the progress of the trial. +EXPR_PROGRESS_FILE = "progress.csv" + +# File that stores results of the trial. +EXPR_RESULT_FILE = "result.json" + +# File that stores the pickled error file +EXPR_ERROR_PICKLE_FILE = "error.pkl" + +# File that stores the error file +EXPR_ERROR_FILE = "error.txt" + +# File that stores the checkpoint metadata +CHECKPOINT_TUNE_METADATA_FILE = ".tune_metadata" + +# ================================================== +# Environment Variables +# ================================================== + +# Integer value which if set will copy files in reported AIR directory +# checkpoints instead of moving them (if worker is on the same node as Trainable) +COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING_ENV = ( + "TRAIN_COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING" +) + +# NOTE: When adding a new environment variable, please track it in this list. +# TODO(ml-team): Most env var constants should get moved here. +AIR_ENV_VARS = { + COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING_ENV, + "RAY_AIR_FULL_TRACEBACKS", + "RAY_AIR_NEW_OUTPUT", +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/data_batch_type.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/data_batch_type.py new file mode 100644 index 0000000000000000000000000000000000000000..5d5d09b3218ee11299dfc1ff6aa5d44b2fff67d4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/data_batch_type.py @@ -0,0 +1,11 @@ +from typing import TYPE_CHECKING, Dict, Union + +if TYPE_CHECKING: + import numpy + import pandas # noqa: F401 + import pyarrow + +# TODO de-dup with ray.data.block.DataBatch +DataBatchType = Union[ + "numpy.ndarray", "pyarrow.Table" "pandas.DataFrame", Dict[str, "numpy.ndarray"] +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/result.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/result.py new file mode 100644 index 0000000000000000000000000000000000000000..9b911a563233fde34e665694a74564a6094d0396 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/result.py @@ -0,0 +1,284 @@ +import io +import json +import logging +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, List, Optional, Tuple, Union + +import pandas as pd +import pyarrow + +import ray +from ray.air.constants import ( + EXPR_ERROR_PICKLE_FILE, + EXPR_PROGRESS_FILE, + EXPR_RESULT_FILE, +) +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +@dataclass +@PublicAPI(stability="stable") +class Result: + """The final result of a ML training run or a Tune trial. + + This is the output produced by ``Trainer.fit``. + ``Tuner.fit`` outputs a :class:`~ray.tune.ResultGrid` that is a collection + of ``Result`` objects. + + This API is the recommended way to access the outputs such as: + - checkpoints (``Result.checkpoint``) + - the history of reported metrics (``Result.metrics_dataframe``, ``Result.metrics``) + - errors encountered during a training run (``Result.error``) + + The constructor is a private API -- use ``Result.from_path`` to create a result + object from a directory. + + Attributes: + metrics: The latest set of reported metrics. + checkpoint: The latest checkpoint. + error: The execution error of the Trainable run, if the trial finishes in error. + path: Path pointing to the result directory on persistent storage. This can + point to a remote storage location (e.g. S3) or to a local location (path + on the head node). The path is accessible via the result's associated + `filesystem`. For instance, for a result stored in S3 at + ``s3://bucket/location``, ``path`` will have the value ``bucket/location``. + metrics_dataframe: The full result dataframe of the Trainable. + The dataframe is indexed by iterations and contains reported + metrics. Note that the dataframe columns are indexed with the + *flattened* keys of reported metrics, so the format of this dataframe + may be slightly different than ``Result.metrics``, which is an unflattened + dict of the latest set of reported metrics. + best_checkpoints: A list of tuples of the best checkpoints and + their associated metrics. The number of + saved checkpoints is determined by :class:`~ray.train.CheckpointConfig` + (by default, all checkpoints will be saved). + """ + + metrics: Optional[Dict[str, Any]] + checkpoint: Optional["ray.tune.Checkpoint"] + error: Optional[Exception] + path: str + metrics_dataframe: Optional["pd.DataFrame"] = None + best_checkpoints: Optional[ + List[Tuple["ray.tune.Checkpoint", Dict[str, Any]]] + ] = None + _storage_filesystem: Optional[pyarrow.fs.FileSystem] = None + _items_to_repr = ["error", "metrics", "path", "filesystem", "checkpoint"] + + @property + def config(self) -> Optional[Dict[str, Any]]: + """The config associated with the result.""" + if not self.metrics: + return None + return self.metrics.get("config", None) + + @property + def filesystem(self) -> pyarrow.fs.FileSystem: + """Return the filesystem that can be used to access the result path. + + Returns: + pyarrow.fs.FileSystem implementation. + """ + return self._storage_filesystem or pyarrow.fs.LocalFileSystem() + + def _repr(self, indent: int = 0) -> str: + """Construct the representation with specified number of space indent.""" + from ray.tune.experimental.output import BLACKLISTED_KEYS + from ray.tune.result import AUTO_RESULT_KEYS + + shown_attributes = {k: getattr(self, k) for k in self._items_to_repr} + if self.error: + shown_attributes["error"] = type(self.error).__name__ + else: + shown_attributes.pop("error") + + shown_attributes["filesystem"] = shown_attributes["filesystem"].type_name + + if self.metrics: + exclude = set(AUTO_RESULT_KEYS) + exclude.update(BLACKLISTED_KEYS) + shown_attributes["metrics"] = { + k: v for k, v in self.metrics.items() if k not in exclude + } + + cls_indent = " " * indent + kws_indent = " " * (indent + 2) + + kws = [ + f"{kws_indent}{key}={value!r}" for key, value in shown_attributes.items() + ] + kws_repr = ",\n".join(kws) + return "{0}{1}(\n{2}\n{0})".format(cls_indent, type(self).__name__, kws_repr) + + def __repr__(self) -> str: + return self._repr(indent=0) + + @staticmethod + def _read_file_as_str( + storage_filesystem: pyarrow.fs.FileSystem, + storage_path: str, + ) -> str: + """Opens a file as an input stream reading all byte content sequentially and + decoding read bytes as utf-8 string. + + Args: + storage_filesystem: The filesystem to use. + storage_path: The source to open for reading. + """ + + with storage_filesystem.open_input_stream(storage_path) as f: + return f.readall().decode() + + @classmethod + def from_path( + cls, + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + ) -> "Result": + """Restore a Result object from local or remote trial directory. + + Args: + path: A path of a trial directory on local or remote storage + (ex: s3://bucket/path or /tmp/ray_results). + storage_filesystem: A custom filesystem to use. If not provided, + this will be auto-resolved by pyarrow. If provided, the path + is assumed to be prefix-stripped already, and must be a valid path + on the filesystem. + + Returns: + A :py:class:`Result` object of that trial. + """ + # TODO(justinvyu): Fix circular dependency. + from ray.train import Checkpoint + from ray.train._internal.storage import ( + _exists_at_fs_path, + _list_at_fs_path, + get_fs_and_path, + ) + from ray.train.constants import CHECKPOINT_DIR_NAME + + fs, fs_path = get_fs_and_path(path, storage_filesystem) + if not _exists_at_fs_path(fs, fs_path): + raise RuntimeError(f"Trial folder {fs_path} doesn't exist!") + + # Restore metrics from result.json + result_json_file = Path(fs_path, EXPR_RESULT_FILE).as_posix() + progress_csv_file = Path(fs_path, EXPR_PROGRESS_FILE).as_posix() + if _exists_at_fs_path(fs, result_json_file): + lines = cls._read_file_as_str(fs, result_json_file).split("\n") + json_list = [json.loads(line) for line in lines if line] + metrics_df = pd.json_normalize(json_list, sep="/") + latest_metrics = json_list[-1] if json_list else {} + # Fallback to restore from progress.csv + elif _exists_at_fs_path(fs, progress_csv_file): + metrics_df = pd.read_csv( + io.StringIO(cls._read_file_as_str(fs, progress_csv_file)) + ) + latest_metrics = ( + metrics_df.iloc[-1].to_dict() if not metrics_df.empty else {} + ) + else: + raise RuntimeError( + f"Failed to restore the Result object: Neither {EXPR_RESULT_FILE}" + f" nor {EXPR_PROGRESS_FILE} exists in the trial folder!" + ) + + # Restore all checkpoints from the checkpoint folders + checkpoint_dir_names = sorted( + _list_at_fs_path( + fs, + fs_path, + file_filter=lambda file_info: file_info.type + == pyarrow.fs.FileType.Directory + and file_info.base_name.startswith("checkpoint_"), + ) + ) + + if checkpoint_dir_names: + checkpoints = [ + Checkpoint( + path=Path(fs_path, checkpoint_dir_name).as_posix(), filesystem=fs + ) + for checkpoint_dir_name in checkpoint_dir_names + ] + + metrics = [] + for checkpoint_dir_name in checkpoint_dir_names: + metrics_corresponding_to_checkpoint = metrics_df[ + metrics_df[CHECKPOINT_DIR_NAME] == checkpoint_dir_name + ] + if metrics_corresponding_to_checkpoint.empty: + logger.warning( + "Could not find metrics corresponding to " + f"{checkpoint_dir_name}. These will default to an empty dict." + ) + metrics.append( + {} + if metrics_corresponding_to_checkpoint.empty + else metrics_corresponding_to_checkpoint.iloc[-1].to_dict() + ) + + latest_checkpoint = checkpoints[-1] + # TODO(justinvyu): These are ordered by checkpoint index, since we don't + # know the metric to order these with. + best_checkpoints = list(zip(checkpoints, metrics)) + else: + best_checkpoints = latest_checkpoint = None + + # Restore the trial error if it exists + error = None + error_file_path = Path(fs_path, EXPR_ERROR_PICKLE_FILE).as_posix() + if _exists_at_fs_path(fs, error_file_path): + with fs.open_input_stream(error_file_path) as f: + error = ray.cloudpickle.load(f) + + return Result( + metrics=latest_metrics, + checkpoint=latest_checkpoint, + path=fs_path, + _storage_filesystem=fs, + metrics_dataframe=metrics_df, + best_checkpoints=best_checkpoints, + error=error, + ) + + @PublicAPI(stability="alpha") + def get_best_checkpoint( + self, metric: str, mode: str + ) -> Optional["ray.tune.Checkpoint"]: + """Get the best checkpoint from this trial based on a specific metric. + + Any checkpoints without an associated metric value will be filtered out. + + Args: + metric: The key for checkpoints to order on. + mode: One of ["min", "max"]. + + Returns: + :class:`Checkpoint ` object, or None if there is + no valid checkpoint associated with the metric. + """ + if not self.best_checkpoints: + raise RuntimeError("No checkpoint exists in the trial directory!") + + if mode not in ["max", "min"]: + raise ValueError( + f'Unsupported mode: {mode}. Please choose from ["min", "max"]!' + ) + + op = max if mode == "max" else min + valid_checkpoints = [ + ckpt_info for ckpt_info in self.best_checkpoints if metric in ckpt_info[1] + ] + + if not valid_checkpoints: + raise RuntimeError( + f"Invalid metric name {metric}! " + f"You may choose from the following metrics: {self.metrics.keys()}." + ) + + return op(valid_checkpoints, key=lambda x: x[1][metric])[0] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/session.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/session.py new file mode 100644 index 0000000000000000000000000000000000000000..b6a9fba5a6d6c89e2aeed911849e9ab136724fe1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/air/session.py @@ -0,0 +1 @@ +from ray.train._internal.session import * # noqa: F401,F403 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8fa62e35a4e45bb40b5cf9500f3ea6ec2a13fc13 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/__init__.py @@ -0,0 +1,8 @@ +import os +from pathlib import Path + +from ray.autoscaler import sdk + +__all__ = ["sdk"] + +AUTOSCALER_DIR_PATH = Path(os.path.abspath(os.path.dirname(__file__))) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/batching_node_provider.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/batching_node_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..6a9118585fa54c0e548ed0a5b5e69268107aa018 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/batching_node_provider.py @@ -0,0 +1,255 @@ +import logging +from collections import defaultdict +from dataclasses import dataclass, field +from typing import Any, Dict, List, Optional, Set + +from ray.autoscaler._private.constants import ( + DISABLE_LAUNCH_CONFIG_CHECK_KEY, + DISABLE_NODE_UPDATERS_KEY, + FOREGROUND_NODE_LAUNCH_KEY, +) +from ray.autoscaler._private.util import NodeID, NodeIP, NodeKind, NodeStatus, NodeType +from ray.autoscaler.node_provider import NodeProvider +from ray.autoscaler.tags import ( + NODE_KIND_HEAD, + TAG_RAY_NODE_KIND, + TAG_RAY_NODE_STATUS, + TAG_RAY_REPLICA_INDEX, + TAG_RAY_USER_NODE_TYPE, +) + +logger = logging.getLogger(__name__) + + +@dataclass +class ScaleRequest: + """Stores desired scale computed by the autoscaler. + + Attributes: + desired_num_workers: Map of worker NodeType to desired number of workers of + that type. + workers_to_delete: List of ids of nodes that should be removed. + """ + + desired_num_workers: Dict[NodeType, int] = field(default_factory=dict) + workers_to_delete: Set[NodeID] = field(default_factory=set) + + +@dataclass +class NodeData: + """Stores all data about a Ray node needed by the autoscaler. + + Attributes: + kind: Whether the node is the head or a worker. + type: The user-defined type of the node. + replica_index: An identifier for nodes in a replica of a TPU worker group. + This value is set as a Pod label by a GKE webhook when TPUs are requested + ip: Cluster-internal ip of the node. ip can be None if the ip + has not yet been assigned. + status: The status of the node. You must adhere to the following semantics + for status: + * The status must be "up-to-date" if and only if the node is running. + * The status must be "update-failed" if and only if the node is in an + unknown or failed state. + * If the node is in a pending (starting-up) state, the status should be + a brief user-facing description of why the node is pending. + """ + + kind: NodeKind + type: NodeType + ip: Optional[NodeIP] + status: NodeStatus + replica_index: Optional[str] = None + + +class BatchingNodeProvider(NodeProvider): + """Abstract subclass of NodeProvider meant for use with external cluster managers. + + Batches reads of cluster state into a single method, get_node_data, called at the + start of an autoscaling update. + + Batches modifications to cluster state into a single method, submit_scale_request, + called at the end of an autoscaling update. + + Implementing a concrete subclass of BatchingNodeProvider only requires overriding + get_node_data() and submit_scale_request(). + + See the method docstrings for more information. + + Note that an autoscaling update may be conditionally + cancelled using the optional method safe_to_scale() + of the root NodeProvider. + """ + + def __init__( + self, + provider_config: Dict[str, Any], + cluster_name: str, + ) -> None: + NodeProvider.__init__(self, provider_config, cluster_name) + self.node_data_dict: Dict[NodeID, NodeData] = {} + + # These flags enforce correct behavior for single-threaded node providers + # which interact with external cluster managers: + assert ( + provider_config.get(DISABLE_NODE_UPDATERS_KEY, False) is True + ), f"To use BatchingNodeProvider, must set `{DISABLE_NODE_UPDATERS_KEY}:True`." + assert provider_config.get(DISABLE_LAUNCH_CONFIG_CHECK_KEY, False) is True, ( + "To use BatchingNodeProvider, must set " + f"`{DISABLE_LAUNCH_CONFIG_CHECK_KEY}:True`." + ) + assert ( + provider_config.get(FOREGROUND_NODE_LAUNCH_KEY, False) is True + ), f"To use BatchingNodeProvider, must set `{FOREGROUND_NODE_LAUNCH_KEY}:True`." + + # self.scale_change_needed tracks whether we need to update scale. + # set to True in create_node and terminate_nodes calls + # reset to False in non_terminated_nodes, which occurs at the start of the + # autoscaling update. For good measure, also set to false in post_process. + self.scale_change_needed = False + + self.scale_request = ScaleRequest() + + # Initialize map of replica indices to nodes in that replica + self.replica_index_to_nodes = defaultdict(list[str]) + + def get_node_data(self) -> Dict[NodeID, NodeData]: + """Queries cluster manager for node info. Returns a mapping from node id to + NodeData. + + Each NodeData value must adhere to the semantics of the NodeData docstring. + (Note in particular the requirements for NodeData.status.) + + Consistency requirement: + If a node id was present in ScaleRequest.workers_to_delete of a previously + submitted scale request, it should no longer be present as a key in + get_node_data. + (Node termination must be registered immediately when submit_scale_request + returns.) + """ + raise NotImplementedError + + def submit_scale_request(self, scale_request: ScaleRequest) -> None: + """Tells the cluster manager which nodes to delete and how many nodes of + each node type to maintain. + + Consistency requirement: + If a node id was present in ScaleRequest.workers_to_delete of a previously + submitted scale request, it should no longer be present as key in get_node_data. + (Node termination must be registered immediately when submit_scale_request + returns.) + """ + raise NotImplementedError + + def post_process(self) -> None: + """Submit a scale request if it is necessary to do so.""" + if self.scale_change_needed: + self.submit_scale_request(self.scale_request) + self.scale_change_needed = False + + def non_terminated_nodes(self, tag_filters: Dict[str, str]) -> List[str]: + self.scale_change_needed = False + self.node_data_dict = self.get_node_data() + + # Initialize ScaleRequest + self.scale_request = ScaleRequest( + desired_num_workers=self.cur_num_workers(), # Current scale + workers_to_delete=set(), # No workers to delete yet + ) + all_nodes = list(self.node_data_dict.keys()) + self.replica_index_to_nodes.clear() + for node_id in all_nodes: + replica_index = self.node_data_dict[node_id].replica_index + # Only add node to map if it belongs to a multi-host podslice + if replica_index is not None: + self.replica_index_to_nodes[replica_index].append(node_id) + # Support filtering by TAG_RAY_NODE_KIND, TAG_RAY_NODE_STATUS, and + # TAG_RAY_USER_NODE_TYPE. + # The autoscaler only uses tag_filters={}, + # but filtering by the these keys is useful for testing. + filtered_nodes = [ + node + for node in all_nodes + if tag_filters.items() <= self.node_tags(node).items() + ] + return filtered_nodes + + def cur_num_workers(self): + """Returns dict mapping node type to the number of nodes of that type.""" + # Factor like this for convenient re-use. + return self._cur_num_workers(self.node_data_dict) + + def _cur_num_workers(self, node_data_dict: Dict[str, Any]): + num_workers_dict = defaultdict(int) + for node_data in node_data_dict.values(): + if node_data.kind == NODE_KIND_HEAD: + # Only track workers. + continue + num_workers_dict[node_data.type] += 1 + return num_workers_dict + + def node_tags(self, node_id: str) -> Dict[str, str]: + node_data = self.node_data_dict[node_id] + tags = { + TAG_RAY_NODE_KIND: node_data.kind, + TAG_RAY_NODE_STATUS: node_data.status, + TAG_RAY_USER_NODE_TYPE: node_data.type, + } + if node_data.replica_index is not None: + tags[TAG_RAY_REPLICA_INDEX] = node_data.replica_index + return tags + + def internal_ip(self, node_id: str) -> str: + return self.node_data_dict[node_id].ip + + def create_node( + self, node_config: Dict[str, Any], tags: Dict[str, str], count: int + ) -> Optional[Dict[str, Any]]: + node_type = tags[TAG_RAY_USER_NODE_TYPE] + self.scale_request.desired_num_workers[node_type] += count + self.scale_change_needed = True + + def terminate_node(self, node_id: str) -> Optional[Dict[str, Any]]: + # Sanity check: We should never try to delete the same node twice. + if node_id in self.scale_request.workers_to_delete: + logger.warning( + f"Autoscaler tried to terminate node {node_id} twice in the same update" + ". Skipping termination request." + ) + return + + # Sanity check: We should never try to delete a node we haven't seen. + if node_id not in self.node_data_dict: + logger.warning( + f"Autoscaler tried to terminate unkown node {node_id}" + ". Skipping termination request." + ) + return + + node_type = self.node_data_dict[node_id].type + + # Sanity check: Don't request less than 0 nodes. + if self.scale_request.desired_num_workers[node_type] <= 0: + # This is logically impossible. + raise AssertionError( + "NodeProvider attempted to request less than 0 workers of type " + f"{node_type}. Skipping termination request." + ) + + # Terminate node + self.scale_request.desired_num_workers[node_type] -= 1 + self.scale_request.workers_to_delete.add(node_id) + + # Scale down all nodes in replica if node_id is part of a multi-host podslice + tags = self.node_tags(node_id) + if TAG_RAY_REPLICA_INDEX in tags: + node_replica_index = tags[TAG_RAY_REPLICA_INDEX] + for worker_id in self.replica_index_to_nodes[node_replica_index]: + # Check if worker has already been scheduled to delete + if worker_id not in self.scale_request.workers_to_delete: + self.scale_request.workers_to_delete.add(worker_id) + logger.info( + f"Autoscaler terminating node {worker_id} " + f"in multi-host replica {node_replica_index}." + ) + self.scale_change_needed = True diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/command_runner.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/command_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..94a6eaa08a5edff33d2bcf8eb982dec0e7d5320b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/command_runner.py @@ -0,0 +1,92 @@ +from typing import Any, Dict, List, Optional, Tuple + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class CommandRunnerInterface: + """Interface to run commands on a remote cluster node. + + **Important**: This is an INTERNAL API that is only exposed for the purpose + of implementing custom node providers. It is not allowed to call into + CommandRunner methods from any Ray package outside the autoscaler, only to + define new implementations for use with the "external" node provider + option. + + Command runner instances are returned by provider.get_command_runner().""" + + def run( + self, + cmd: Optional[str] = None, + timeout: int = 120, + exit_on_fail: bool = False, + port_forward: Optional[List[Tuple[int, int]]] = None, + with_output: bool = False, + environment_variables: Optional[Dict[str, object]] = None, + run_env: str = "auto", + ssh_options_override_ssh_key: str = "", + shutdown_after_run: bool = False, + ) -> str: + """Run the given command on the cluster node and optionally get output. + + WARNING: the cloudgateway needs arguments of "run" function to be json + dumpable to send them over HTTP requests. + + Args: + cmd: The command to run. + timeout: The command timeout in seconds. + exit_on_fail: Whether to sys exit on failure. + port_forward: List of (local, remote) ports to forward, or + a single tuple. + with_output: Whether to return output. + environment_variables (Dict[str, str | int | Dict[str, str]): + Environment variables that `cmd` should be run with. + run_env: Options: docker/host/auto. Used in + DockerCommandRunner to determine the run environment. + ssh_options_override_ssh_key: if provided, overwrites + SSHOptions class with SSHOptions(ssh_options_override_ssh_key). + shutdown_after_run: if provided, shutdowns down the machine + after executing the command with `sudo shutdown -h now`. + """ + raise NotImplementedError + + def run_rsync_up( + self, source: str, target: str, options: Optional[Dict[str, Any]] = None + ) -> None: + """Rsync files up to the cluster node. + + Args: + source: The (local) source directory or file. + target: The (remote) destination path. + """ + raise NotImplementedError + + def run_rsync_down( + self, source: str, target: str, options: Optional[Dict[str, Any]] = None + ) -> None: + """Rsync files down from the cluster node. + + Args: + source: The (remote) source directory or file. + target: The (local) destination path. + """ + raise NotImplementedError + + def remote_shell_command_str(self) -> str: + """Return the command the user can use to open a shell.""" + raise NotImplementedError + + def run_init( + self, *, as_head: bool, file_mounts: Dict[str, str], sync_run_yet: bool + ) -> Optional[bool]: + """Used to run extra initialization commands. + + Args: + as_head: Run as head image or worker. + file_mounts: Files to copy to the head and worker nodes. + sync_run_yet: Whether sync has been run yet. + + Returns: + optional: Whether initialization is necessary. + """ + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/launch_and_verify_cluster.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/launch_and_verify_cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..2dee563eac9a5c3d98abbb83a914c53a5121bb13 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/launch_and_verify_cluster.py @@ -0,0 +1,439 @@ +""" +This script automates the process of launching and verifying a Ray cluster using a given +cluster configuration file. It also handles cluster cleanup before and after the +verification process. The script requires one command-line argument: the path to the +cluster configuration file. + +Usage: + python launch_and_verify_cluster.py [--no-config-cache] [--retries NUM_RETRIES] + [--num-expected-nodes NUM_NODES] [--docker-override DOCKER_OVERRIDE] + [--wheel-override WHEEL_OVERRIDE] + +""" +import argparse +import os +import re +import subprocess +import sys +import tempfile +import time +import traceback +from pathlib import Path + +import boto3 +import botocore +import yaml +from google.cloud import storage + +import ray +from ray.autoscaler._private.aws.config import RAY + + +def check_arguments(): + """ + Check command line arguments and return the cluster configuration file path, the + number of retries, the number of expected nodes, and the value of the + --no-config-cache flag. + """ + parser = argparse.ArgumentParser(description="Launch and verify a Ray cluster") + parser.add_argument( + "--no-config-cache", + action="store_true", + help="Pass the --no-config-cache flag to Ray CLI commands", + ) + parser.add_argument( + "--retries", + type=int, + default=3, + help="Number of retries for verifying Ray is running (default: 3)", + ) + parser.add_argument( + "--num-expected-nodes", + type=int, + default=1, + help="Number of nodes for verifying Ray is running (default: 1)", + ) + parser.add_argument( + "--docker-override", + choices=["disable", "latest", "nightly", "commit"], + default="disable", + help="Override the docker image used for the head node and worker nodes", + ) + parser.add_argument( + "--wheel-override", + type=str, + default="", + help="Override the wheel used for the head node and worker nodes", + ) + parser.add_argument( + "cluster_config", type=str, help="Path to the cluster configuration file" + ) + args = parser.parse_args() + + assert not ( + args.docker_override != "disable" and args.wheel_override != "" + ), "Cannot override both docker and wheel" + + return ( + args.cluster_config, + args.retries, + args.no_config_cache, + args.num_expected_nodes, + args.docker_override, + args.wheel_override, + ) + + +def get_docker_image(docker_override): + """ + Get the docker image to use for the head node and worker nodes. + + Args: + docker_override: The value of the --docker-override flag. + + Returns: + The docker image to use for the head node and worker nodes, or None if not + applicable. + """ + if docker_override == "latest": + return "rayproject/ray:latest-py39" + elif docker_override == "nightly": + return "rayproject/ray:nightly-py39" + elif docker_override == "commit": + if re.match("^[0-9]+.[0-9]+.[0-9]+$", ray.__version__): + return f"rayproject/ray:{ray.__version__}.{ray.__commit__[:6]}-py39" + else: + print( + "Error: docker image is only available for " + f"release version, but we get: {ray.__version__}" + ) + sys.exit(1) + return None + + +def check_file(file_path): + """ + Check if the provided file path is valid and readable. + + Args: + file_path: The path of the file to check. + + Raises: + SystemExit: If the file is not readable or does not exist. + """ + if not file_path.is_file() or not os.access(file_path, os.R_OK): + print(f"Error: Cannot read cluster configuration file: {file_path}") + sys.exit(1) + + +def override_wheels_url(config_yaml, wheel_url): + setup_commands = config_yaml.get("setup_commands", []) + setup_commands.append( + f'pip3 uninstall -y ray && pip3 install -U "ray[default] @ {wheel_url}"' + ) + config_yaml["setup_commands"] = setup_commands + + +def override_docker_image(config_yaml, docker_image): + docker_config = config_yaml.get("docker", {}) + docker_config["image"] = docker_image + docker_config["container_name"] = "ray_container" + assert docker_config.get("head_image") is None, "Cannot override head_image" + assert docker_config.get("worker_image") is None, "Cannot override worker_image" + config_yaml["docker"] = docker_config + + +def download_ssh_key_aws(): + """Download the ssh key from the S3 bucket to the local machine.""" + print("======================================") + print("Downloading ssh key...") + # Create a Boto3 client to interact with S3 + s3_client = boto3.client("s3", region_name="us-west-2") + + # Set the name of the S3 bucket and the key to download + bucket_name = "aws-cluster-launcher-test" + key_name = "ray-autoscaler_59_us-west-2.pem" + + # Download the key from the S3 bucket to a local file + local_key_path = os.path.expanduser(f"~/.ssh/{key_name}") + if not os.path.exists(os.path.dirname(local_key_path)): + os.makedirs(os.path.dirname(local_key_path)) + s3_client.download_file(bucket_name, key_name, local_key_path) + + # Set permissions on the key file + os.chmod(local_key_path, 0o400) + + +def download_ssh_key_gcp(): + """Download the ssh key from the google cloud bucket to the local machine.""" + print("======================================") + print("Downloading ssh key from GCP...") + + # Initialize the GCP storage client + client = storage.Client() + + # Set the name of the GCS bucket and the blob (key) to download + bucket_name = "gcp-cluster-launcher-release-test-ssh-keys" + key_name = "ray-autoscaler_gcp_us-west1_anyscale-bridge-cd812d38_ubuntu_0.pem" + + # Get the bucket and blob + bucket = client.get_bucket(bucket_name) + blob = bucket.get_blob(key_name) + + # Download the blob to a local file + local_key_path = os.path.expanduser(f"~/.ssh/{key_name}") + if not os.path.exists(os.path.dirname(local_key_path)): + os.makedirs(os.path.dirname(local_key_path)) + blob.download_to_filename(local_key_path) + + # Set permissions on the key file + os.chmod(local_key_path, 0o400) + + +def cleanup_cluster(config_yaml, cluster_config): + """ + Clean up the cluster using the given cluster configuration file. + + Args: + cluster_config: The path of the cluster configuration file. + """ + print("======================================") + print("Cleaning up cluster...") + + # We do multiple retries here because sometimes the cluster + # fails to clean up properly, resulting in a non-zero exit code (e.g. + # when processes have to be killed forcefully). + + last_error = None + num_tries = 3 + for i in range(num_tries): + try: + subprocess.run( + ["ray", "down", "-v", "-y", str(cluster_config)], + check=True, + capture_output=True, + ) + cleanup_security_groups(config_yaml) + # Final success + return + except subprocess.CalledProcessError as e: + print(f"ray down fails[{i+1}/{num_tries}]: ") + print(e.output.decode("utf-8")) + + # Print full traceback + traceback.print_exc() + + # Print stdout and stderr from ray down + print(f"stdout:\n{e.stdout.decode('utf-8')}") + print(f"stderr:\n{e.stderr.decode('utf-8')}") + + last_error = e + + raise last_error + + +def cleanup_security_group(ec2_client, id): + retry = 0 + while retry < 10: + try: + ec2_client.delete_security_group(GroupId=id) + return + except botocore.exceptions.ClientError as e: + if e.response["Error"]["Code"] == "DependencyViolation": + sleep_time = 2**retry + print( + f"Waiting {sleep_time}s for the instance to be terminated before deleting the security group {id}" # noqa E501 + ) + time.sleep(sleep_time) + retry += 1 + else: + print(f"Error deleting security group: {e}") + return + + +def cleanup_security_groups(config): + provider_type = config.get("provider", {}).get("type") + if provider_type != "aws": + return + + try: + ec2_client = boto3.client("ec2", region_name="us-west-2") + response = ec2_client.describe_security_groups( + Filters=[ + { + "Name": "tag-key", + "Values": [RAY], + }, + { + "Name": "tag:ray-cluster-name", + "Values": [config["cluster_name"]], + }, + ] + ) + for security_group in response["SecurityGroups"]: + cleanup_security_group(ec2_client, security_group["GroupId"]) + except Exception as e: + print(f"Error cleaning up security groups: {e}") + + +def run_ray_commands( + config_yaml, cluster_config, retries, no_config_cache, num_expected_nodes=1 +): + """ + Run the necessary Ray commands to start a cluster, verify Ray is running, and clean + up the cluster. + + Args: + cluster_config: The path of the cluster configuration file. + retries: The number of retries for the verification step. + no_config_cache: Whether to pass the --no-config-cache flag to the ray CLI + commands. + """ + + print("======================================") + print("Starting new cluster...") + cmd = ["ray", "up", "-v", "-y"] + if no_config_cache: + cmd.append("--no-config-cache") + cmd.append(str(cluster_config)) + + print(" ".join(cmd)) + + try: + subprocess.run(cmd, check=True, capture_output=True) + except subprocess.CalledProcessError as e: + print(e.output) + # print stdout and stderr + print(f"stdout:\n{e.stdout.decode('utf-8')}") + print(f"stderr:\n{e.stderr.decode('utf-8')}") + raise e + + print("======================================") + print("Verifying Ray is running...") + + success = False + count = 0 + while count < retries: + try: + cmd = [ + "ray", + "exec", + "-v", + str(cluster_config), + ( + 'python -c \'import ray; ray.init("localhost:6379");' + + f" assert len(ray.nodes()) >= {num_expected_nodes}'" + ), + ] + if no_config_cache: + cmd.append("--no-config-cache") + subprocess.run(cmd, check=True) + success = True + break + except subprocess.CalledProcessError: + count += 1 + print(f"Verification failed. Retry attempt {count} of {retries}...") + time.sleep(60) + + if not success: + print("======================================") + print( + f"Error: Verification failed after {retries} attempts. Cleaning up cluster " + "before exiting..." + ) + cleanup_cluster(config_yaml, cluster_config) + print("======================================") + print("Exiting script.") + sys.exit(1) + + print("======================================") + print("Ray verification successful.") + + cleanup_cluster(config_yaml, cluster_config) + + print("======================================") + print("Finished executing script successfully.") + + +if __name__ == "__main__": + ( + cluster_config, + retries, + no_config_cache, + num_expected_nodes, + docker_override, + wheel_override, + ) = check_arguments() + cluster_config = Path(cluster_config) + check_file(cluster_config) + + print(f"Using cluster configuration file: {cluster_config}") + print(f"Number of retries for 'verify ray is running' step: {retries}") + print(f"Using --no-config-cache flag: {no_config_cache}") + print(f"Number of expected nodes for 'verify ray is running': {num_expected_nodes}") + + config_yaml = yaml.safe_load(cluster_config.read_text()) + # Make the cluster name unique + config_yaml["cluster_name"] = ( + config_yaml["cluster_name"] + "-" + str(int(time.time())) + ) + + print("======================================") + print(f"Overriding ray wheel...: {wheel_override}") + if wheel_override: + override_wheels_url(config_yaml, wheel_override) + + print("======================================") + print(f"Overriding docker image...: {docker_override}") + docker_override_image = get_docker_image(docker_override) + print(f"Using docker image: {docker_override_image}") + if docker_override_image: + override_docker_image(config_yaml, docker_override_image) + + provider_type = config_yaml.get("provider", {}).get("type") + config_yaml["provider"]["cache_stopped_nodes"] = False + if provider_type == "aws": + download_ssh_key_aws() + elif provider_type == "gcp": + download_ssh_key_gcp() + # Get the active account email + account_email = ( + subprocess.run( + ["gcloud", "config", "get-value", "account"], + stdout=subprocess.PIPE, + check=True, + ) + .stdout.decode("utf-8") + .strip() + ) + print("Active account email:", account_email) + # Get the current project ID + project_id = ( + subprocess.run( + ["gcloud", "config", "get-value", "project"], + stdout=subprocess.PIPE, + check=True, + ) + .stdout.decode("utf-8") + .strip() + ) + print( + f"Injecting GCP project '{project_id}' into cluster configuration file..." + ) + config_yaml["provider"]["project_id"] = project_id + elif provider_type == "vsphere": + print("======================================") + print("VSPHERE provider detected.") + else: + print("======================================") + print("Provider type not recognized. Exiting script.") + sys.exit(1) + + # Create a new temporary file and dump the updated configuration into it + with tempfile.NamedTemporaryFile(suffix=".yaml") as temp: + temp.write(yaml.dump(config_yaml).encode("utf-8")) + temp.flush() + cluster_config = Path(temp.name) + run_ray_commands( + config_yaml, cluster_config, retries, no_config_cache, num_expected_nodes + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/node_launch_exception.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/node_launch_exception.py new file mode 100644 index 0000000000000000000000000000000000000000..eb6bd25f2c612162b97bca2f721b4ebb9fad0242 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/node_launch_exception.py @@ -0,0 +1,37 @@ +from typing import Any, Optional, Tuple + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class NodeLaunchException(Exception): + """A structured exception that can be thrown by a node provider during a + `create_node` call to pass additional information for observability. + """ + + def __init__( + self, + category: str, + description: str, + src_exc_info: Optional[Tuple[Any, Any, Any]], # The + ): + """Args: + category: A short (<20 chars) label for the error. + description: A longer, human readable description of the error. + src_exc_info: The source exception info if applicable. This is a + tuple of (type, exception, traceback) as returned by + sys.exc_info() + + """ + super().__init__(f"Node Launch Exception ({category}): {description}") + self.category = category + self.description = description + self.src_exc_info = src_exc_info + + def __reduce__(self): + # NOTE: Since tracebacks can't be pickled, we'll drop the optional + # traceback if we have to serialize this object. + return ( + self.__class__, + (self.category, self.description, None), + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/node_provider.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/node_provider.py new file mode 100644 index 0000000000000000000000000000000000000000..fec6fd6190589dcdcf34aa2b9bf16b91e7b08d8a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/node_provider.py @@ -0,0 +1,263 @@ +import logging +from types import ModuleType +from typing import Any, Dict, List, Optional + +from ray.autoscaler._private.command_runner import DockerCommandRunner, SSHCommandRunner +from ray.autoscaler.command_runner import CommandRunnerInterface +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class NodeProvider: + """Interface for getting and returning nodes from a Cloud. + + **Important**: This is an INTERNAL API that is only exposed for the purpose + of implementing custom node providers. It is not allowed to call into + NodeProvider methods from any Ray package outside the autoscaler, only to + define new implementations of NodeProvider for use with the "external" node + provider option. + + NodeProviders are namespaced by the `cluster_name` parameter; they only + operate on nodes within that namespace. + + Nodes may be in one of three states: {pending, running, terminated}. Nodes + appear immediately once started by `create_node`, and transition + immediately to terminated when `terminate_node` is called. + """ + + def __init__(self, provider_config: Dict[str, Any], cluster_name: str) -> None: + self.provider_config = provider_config + self.cluster_name = cluster_name + self._internal_ip_cache: Dict[str, str] = {} + self._external_ip_cache: Dict[str, str] = {} + + def is_readonly(self) -> bool: + """Returns whether this provider is readonly. + + Readonly node providers do not allow nodes to be created or terminated. + """ + return False + + def non_terminated_nodes(self, tag_filters: Dict[str, str]) -> List[str]: + """Return a list of node ids filtered by the specified tags dict. + + This list must not include terminated nodes. For performance reasons, + providers are allowed to cache the result of a call to + non_terminated_nodes() to serve single-node queries + (e.g. is_running(node_id)). This means that non_terminate_nodes() must + be called again to refresh results. + + Examples: + >>> from ray.autoscaler.node_provider import NodeProvider + >>> from ray.autoscaler.tags import TAG_RAY_NODE_KIND + >>> provider = NodeProvider(...) # doctest: +SKIP + >>> provider.non_terminated_nodes( # doctest: +SKIP + ... {TAG_RAY_NODE_KIND: "worker"}) + ["node-1", "node-2"] + + """ + raise NotImplementedError + + def is_running(self, node_id: str) -> bool: + """Return whether the specified node is running.""" + raise NotImplementedError + + def is_terminated(self, node_id: str) -> bool: + """Return whether the specified node is terminated.""" + raise NotImplementedError + + def node_tags(self, node_id: str) -> Dict[str, str]: + """Returns the tags of the given node (string dict).""" + raise NotImplementedError + + def external_ip(self, node_id: str) -> str: + """Returns the external ip of the given node.""" + raise NotImplementedError + + def internal_ip(self, node_id: str) -> str: + """Returns the internal ip (Ray ip) of the given node.""" + raise NotImplementedError + + def get_node_id(self, ip_address: str, use_internal_ip: bool = False) -> str: + """Returns the node_id given an IP address. + + Assumes ip-address is unique per node. + + Args: + ip_address: Address of node. + use_internal_ip: Whether the ip address is + public or private. + + Raises: + ValueError: If not found. + """ + + def find_node_id(): + if use_internal_ip: + return self._internal_ip_cache.get(ip_address) + else: + return self._external_ip_cache.get(ip_address) + + if not find_node_id(): + all_nodes = self.non_terminated_nodes({}) + ip_func = self.internal_ip if use_internal_ip else self.external_ip + ip_cache = ( + self._internal_ip_cache if use_internal_ip else self._external_ip_cache + ) + for node_id in all_nodes: + ip_cache[ip_func(node_id)] = node_id + + if not find_node_id(): + if use_internal_ip: + known_msg = f"Worker internal IPs: {list(self._internal_ip_cache)}" + else: + known_msg = f"Worker external IP: {list(self._external_ip_cache)}" + raise ValueError(f"ip {ip_address} not found. " + known_msg) + + return find_node_id() + + def create_node( + self, node_config: Dict[str, Any], tags: Dict[str, str], count: int + ) -> Optional[Dict[str, Any]]: + """Creates a number of nodes within the namespace. + + Optionally returns a mapping from created node ids to node metadata. + + Optionally may throw a + ray.autoscaler.node_launch_exception.NodeLaunchException which the + autoscaler may use to provide additional functionality such as + observability. + + """ + raise NotImplementedError + + def create_node_with_resources_and_labels( + self, + node_config: Dict[str, Any], + tags: Dict[str, str], + count: int, + resources: Dict[str, float], + labels: Dict[str, str], + ) -> Optional[Dict[str, Any]]: + """Create nodes with a given resource and label config. + + This is the method actually called by the autoscaler. Prefer to + implement this when possible directly, otherwise it delegates to the + create_node() implementation. + + Optionally may throw a ray.autoscaler.node_launch_exception.NodeLaunchException. + """ + return self.create_node(node_config, tags, count) + + def set_node_tags(self, node_id: str, tags: Dict[str, str]) -> None: + """Sets the tag values (string dict) for the specified node.""" + raise NotImplementedError + + def terminate_node(self, node_id: str) -> Optional[Dict[str, Any]]: + """Terminates the specified node. + + Optionally return a mapping from deleted node ids to node + metadata. + """ + raise NotImplementedError + + def terminate_nodes(self, node_ids: List[str]) -> Optional[Dict[str, Any]]: + """Terminates a set of nodes. + + May be overridden with a batch method, which optionally may return a + mapping from deleted node ids to node metadata. + """ + for node_id in node_ids: + logger.info("NodeProvider: {}: Terminating node".format(node_id)) + self.terminate_node(node_id) + return None + + @property + def max_terminate_nodes(self) -> Optional[int]: + """The maximum number of nodes which can be terminated in one single + API request. By default, this is "None", which means that the node + provider's underlying API allows infinite requests to be terminated + with one request. + + For example, AWS only allows 1000 nodes to be terminated + at once; to terminate more, we must issue multiple separate API + requests. If the limit is infinity, then simply set this to None. + + This may be overridden. The value may be useful when overriding the + "terminate_nodes" method. + """ + return None + + @staticmethod + def bootstrap_config(cluster_config: Dict[str, Any]) -> Dict[str, Any]: + """Bootstraps the cluster config by adding env defaults if needed.""" + return cluster_config + + def get_command_runner( + self, + log_prefix: str, + node_id: str, + auth_config: Dict[str, Any], + cluster_name: str, + process_runner: ModuleType, + use_internal_ip: bool, + docker_config: Optional[Dict[str, Any]] = None, + ) -> CommandRunnerInterface: + """Returns the CommandRunner class used to perform SSH commands. + + Args: + log_prefix: stores "NodeUpdater: {}: ".format(). Used + to print progress in the CommandRunner. + node_id: the node ID. + auth_config: the authentication configs from the autoscaler + yaml file. + cluster_name: the name of the cluster. + process_runner: the module to use to run the commands + in the CommandRunner. E.g., subprocess. + use_internal_ip: whether the node_id belongs to an internal ip + or external ip. + docker_config: If set, the docker information of the docker + container that commands should be run on. + """ + common_args = { + "log_prefix": log_prefix, + "node_id": node_id, + "provider": self, + "auth_config": auth_config, + "cluster_name": cluster_name, + "process_runner": process_runner, + "use_internal_ip": use_internal_ip, + } + if docker_config and docker_config["container_name"] != "": + return DockerCommandRunner(docker_config, **common_args) + else: + return SSHCommandRunner(**common_args) + + def prepare_for_head_node(self, cluster_config: Dict[str, Any]) -> Dict[str, Any]: + """Returns a new cluster config with custom configs for head node.""" + return cluster_config + + @staticmethod + def fillout_available_node_types_resources( + cluster_config: Dict[str, Any] + ) -> Dict[str, Any]: + """Fills out missing "resources" field for available_node_types.""" + return cluster_config + + def safe_to_scale(self) -> bool: + """Optional condition to determine if it's safe to proceed with an autoscaling + update. Can be used to wait for convergence of state managed by an external + cluster manager. + + Called by the autoscaler immediately after non_terminated_nodes(). + If False is returned, the autoscaler will abort the update. + """ + return True + + def post_process(self) -> None: + """This optional method is executed at the end of + StandardAutoscaler._update(). + """ + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/ray-schema.json b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/ray-schema.json new file mode 100644 index 0000000000000000000000000000000000000000..e65b239f233469308088399957b0d7e64e706aec --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/ray-schema.json @@ -0,0 +1,400 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://github.com/ray-project/ray/python/ray/autoscaler/ray-schema.json", + "title": "Ray AutoScaler", + "description": "Ray autoscaler schema", + "type": "object", + "definitions": { + "commands": { + "type": "array", + "items": { + "type": "string", + "description": "shell command" + } + } + }, + "required": [ + "cluster_name", + "provider" + ], + "additionalProperties": false, + "properties": { + "cluster_name": { + "description": "A unique identifier for the head node and workers of this cluster.", + "type": "string" + }, + "max_workers": { + "description": "The maximum number of workers nodes to launch in addition to the head node. This should be no larger than the sum of min_workers for all available node types.", + "type": "integer", + "minimum": 0 + }, + "upscaling_speed": { + "description": "The autoscaler will scale up the cluster faster with higher upscaling speed. E.g., if the task requires adding more nodes then autoscaler will gradually scale up the cluster in chunks of upscaling_speed*currently_running_nodes. This number should be > 0.", + "type": "number", + "minimum": 0 + }, + "idle_timeout_minutes": { + "description": "If a node is idle for this many minutes, it will be removed.", + "type": "number", + "minimum": 0 + }, + "provider": { + "type": "object", + "description": "Cloud-provider specific configuration.", + "required": [ "type" ], + "additionalProperties": true, + "properties": { + "type": { + "type": "string", + "description": "e.g. aws, azure, gcp,..." + }, + "region": { + "type": "string", + "description": "e.g. us-east-1" + }, + "module": { + "type": "string", + "description": "module, if using external node provider" + }, + "head_ip": { + "type": "string", + "description": "gcp project id, if using gcp" + }, + "worker_ips": { + "type": "array", + "description": "local cluster head node" + }, + "use_internal_ips": { + "type": "boolean", + "description": "don't require public ips" + }, + "namespace": { + "type": "string", + "description": "k8s namespace, if using k8s" + }, + "location": { + "type": "string", + "description": "Azure location" + }, + "resource_group": { + "type": "string", + "description": "Azure resource group" + }, + "tags": { + "type": "object", + "description": "Azure user-defined tags" + }, + "subscription_id": { + "type": "string", + "description": "Azure subscription id" + }, + "msi_identity_id": { + "type": "string", + "description": "User-defined managed identity (generated by config)" + }, + "msi_identity_principal_id": { + "type": "string", + "description": "User-defined managed identity principal id (generated by config)" + }, + "subnet_id": { + "type": "string", + "description": "Network subnet id" + }, + "autoscaler_service_account": { + "type": "object", + "description": "k8s autoscaler permissions, if using k8s" + }, + "autoscaler_role": { + "type": "object", + "description": "k8s autoscaler permissions, if using k8s" + }, + "autoscaler_role_binding": { + "type": "object", + "description": "k8s autoscaler permissions, if using k8s" + }, + "cache_stopped_nodes": { + "type": "boolean", + "description": " Whether to try to reuse previously stopped nodes instead of launching nodes. This will also cause the autoscaler to stop nodes instead of terminating them. Only implemented for AWS." + }, + "availability_zone": { + "type": "string", + "description": "GCP availability zone" + }, + "project_id": { + "type": ["string", "null"], + "description": "GCP globally unique project id" + }, + "security_group": { + "type": "object", + "description": "AWS security group", + "additionalProperties": false, + "properties": { + "GroupName": { + "type": "string", + "description": "Security group name" + }, + "IpPermissions": { + "type": "array", + "description": "Security group in bound rules" + } + } + }, + "disable_node_updaters": { + "type": "boolean", + "description": "Disables node updaters if set to True. Default is False. (For Kubernetes operator usage.)" + }, + "gcp_credentials": { + "type": "object", + "description": "Credentials for authenticating with the GCP client", + "required": [ "type" ], + "additionalProperties": false, + "properties": { + "type": { + "type": "string", + "enum": ["credentials_token", "service_account"], + "description": "Credentials type: either temporary OAuth 2.0 token or permanent service account credentials blob." + }, + "credentials": { + "type": "string", + "description": "Oauth token or JSON string constituting service account credentials" + } + } + }, + "cloudwatch": { + "agent": { + "CLOUDWATCH_AGENT_INSTALLED_AMI_TAG": { + "type": ["string"], + "description": "Tag to be added to cloudwatch agent pre-installed AMI name." + }, + "config": { + "type": ["string", "null"], + "description": "Path to Unified CloudWatch Agent config file. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Agent-Configuration-File-Details.html for additional details." + }, + "retryer": { + "max_attempts": { + "type": ["integer", "null"], + "description": "Max allowed Unified CloudWatch Agent installation attempts on any host." + }, + "delay_seconds": { + "type": ["integer", "null"], + "description": "Seconds to wait between each Unified CloudWatch Agent installation attempt." + } + } + }, + "dashboard": { + "name": { + "type": ["string", "null"], + "description": "User defined CloudWatch Dashboard name." + }, + "config": { + "type": ["string", "null"], + "description": "Path to CloudWatch Dashboard config file. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/CloudWatch-Dashboard-Body-Structure.html for additional details." + } + }, + "alarm": { + "config": { + "type": ["string", "null"], + "description": "Path to CloudWatch Alarm config file. See https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_PutMetricAlarm.html for additional details." + } + } + } + } + }, + "auth": { + "type": "object", + "description": "How Ray will authenticate with newly launched nodes.", + "additionalProperties": false, + "properties": { + "ssh_user": { + "type": "string", + "default": "ubuntu" + }, + "ssh_public_key": { + "type": "string" + }, + "ssh_private_key": { + "type": "string" + }, + "ssh_proxy_command": { + "description": "A value for ProxyCommand ssh option, for connecting through proxies. Example: nc -x proxy.example.com:1234 %h %p", + "type": "string" + } + } + }, + "docker": { + "type": "object", + "description": "Docker configuration. If this is specified, all setup and start commands will be executed in the container.", + "additionalProperties": false, + "properties": { + "image": { + "type": "string", + "description": "the docker image name", + "default": "rayproject/ray:latest" + }, + "container_name": { + "type": "string", + "default": "ray_docker" + }, + "pull_before_run": { + "type": "boolean", + "description": "run `docker pull` first" + }, + "run_options": { + "type": "array", + "description": "shared options for starting head/worker docker" + }, + "head_image": { + "type": "string", + "description": "image for head node, takes precedence over 'image' if specified" + }, + "head_run_options": { + "type": "array", + "description": "head specific run options, appended to run_options" + }, + "worker_image": { + "type": "string", + "description": "analogous to head_image" + }, + "worker_run_options": { + "type": "array", + "description": "analogous to head_run_options" + }, + "disable_automatic_runtime_detection" : { + "type": "boolean", + "description": "disable Ray from automatically using the NVIDIA runtime if available", + "default": false + }, + "disable_shm_size_detection" : { + "type": "boolean", + "description": "disable Ray from automatically detecting /dev/shm size for the container", + "default": false + }, + "use_podman" : { + "type": "boolean", + "description": "Use 'podman' command in place of 'docker'", + "default": false + } + } + }, + "head_node_type": { + "type": "string", + "description": "If using multiple node types, specifies the head node type." + }, + "file_mounts": { + "type": "object", + "description": "Map of remote paths to local paths, e.g. {\"/tmp/data\": \"/my/local/data\"}" + }, + "cluster_synced_files": { + "type": "array", + "description": "List of paths on the head node which should sync to the worker nodes, e.g. [\"/some/data/somehwere\"]" + }, + "file_mounts_sync_continuously": { + "type": "boolean", + "description": "If enabled, file mounts will sync continously between the head node and the worker nodes. The nodes will not re-run setup commands if only the contents of the file mounts folders change." + }, + "rsync_exclude": { + "type": "array", + "description": "File pattern to not sync up or down when using the rsync command. Matches the format of rsync's --exclude param." + }, + "rsync_filter": { + "type": "array", + "description": "Pattern files to lookup patterns to exclude when using rsync up or rsync down. This file is checked for recursively in all directories. For example, if .gitignore is provided here, the behavior will match git's .gitignore behavior." + }, + "metadata": { + "type": "object", + "description": "Metadata field that can be used to store user-defined data in the cluster config. Ray does not interpret these fields." + }, + "initialization_commands": { + "$ref": "#/definitions/commands", + "description": "List of commands that will be run before `setup_commands`. If docker is enabled, these commands will run outside the container and before docker is setup." + }, + "setup_commands": { + "$ref": "#/definitions/commands", + "description": "List of common shell commands to run to setup nodes." + }, + "head_setup_commands": { + "$ref": "#/definitions/commands", + "description": "Commands that will be run on the head node after common setup." + }, + "worker_setup_commands": { + "$ref": "#/definitions/commands", + "description": "Commands that will be run on worker nodes after common setup." + }, + "head_start_ray_commands": { + "$ref": "#/definitions/commands", + "description": "Command to start ray on the head node. You shouldn't need to modify this." + }, + "worker_start_ray_commands": { + "$ref": "#/definitions/commands", + "description": "Command to start ray on worker nodes. You shouldn't need to modify this." + }, + "no_restart": { + "description": "Whether to avoid restarting the cluster during updates. This field is controlled by the ray --no-restart flag and cannot be set by the user." + }, + "available_node_types": { + "type": "object", + "description": "A list of node types for multi-node-type autoscaling.", + "patternProperties": { + ".*": { + "type": "object", + "required": [ "resources", "node_config" ], + "properties": { + "node_config": { + "type": "object", + "description": "Provider-specific config for the node, e.g. instance type." + }, + "min_workers": {"type": "integer"}, + "max_workers": {"type": "integer"}, + "idle_timeout_s": {"type": "number", "nullable": true}, + "resources": { + "type": "object", + "patternProperties": { + ".*":{ + "type": "integer", + "minimum": 0 + } + } + }, + "labels": { + "type": "object", + "patternProperties": { + ".*":{ + "type": "string" + } + } + }, + "initialization_commands": { + "$ref": "#/definitions/commands", + "description": "List of commands that will be run before `setup_commands`. If docker is enabled, these commands will run outside the container and before docker is setup." + }, + "worker_setup_commands": { + "$ref": "#/definitions/commands", + "description": "List of common shell commands to run to setup nodes. This node specfic list will override the global setup_commands and worker_setup_commands." + }, + "docker": { + "description": "Configuration of Worker nodes.", + "type": "object", + "properties": { + "pull_before_run": { + "type": "boolean", + "description": "run `docker pull` first" + }, + "worker_image": { + "type": "string", + "description": "analogous to head_image" + }, + "worker_run_options": { + "type": "array", + "description": "analogous to head_run_options, merged with the global docker run_options." + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + }, + "additionalProperties": false + } + } +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/tags.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/tags.py new file mode 100644 index 0000000000000000000000000000000000000000..38d03855040fd512e32b2d31f9972e1da8dcedbb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/autoscaler/tags.py @@ -0,0 +1,47 @@ +"""The Ray autoscaler uses tags/labels to associate metadata with instances.""" + +# Tag for the name of the node +TAG_RAY_NODE_NAME = "ray-node-name" + +# Tag for the kind of node (e.g. Head, Worker). For legacy reasons, the tag +# value says 'type' instead of 'kind'. +TAG_RAY_NODE_KIND = "ray-node-type" +NODE_KIND_HEAD = "head" +NODE_KIND_WORKER = "worker" +NODE_KIND_UNMANAGED = "unmanaged" + +# Tag for user defined node types (e.g., m4xl_spot). This is used for multi +# node type clusters. +TAG_RAY_USER_NODE_TYPE = "ray-user-node-type" +# Tag for index of replica node belongs to. Used for multi-host worker groups. +TAG_RAY_REPLICA_INDEX = "ray-replica-index" +# Tag for autofilled node types for legacy cluster yamls without multi +# node type defined in the cluster configs. +NODE_TYPE_LEGACY_HEAD = "ray-legacy-head-node-type" +NODE_TYPE_LEGACY_WORKER = "ray-legacy-worker-node-type" + +# Tag that reports the current state of the node (e.g. Updating, Up-to-date) +TAG_RAY_NODE_STATUS = "ray-node-status" +STATUS_UNINITIALIZED = "uninitialized" +STATUS_WAITING_FOR_SSH = "waiting-for-ssh" +STATUS_SYNCING_FILES = "syncing-files" +STATUS_SETTING_UP = "setting-up" +STATUS_UPDATE_FAILED = "update-failed" +STATUS_UP_TO_DATE = "up-to-date" + +# Tag uniquely identifying all nodes of a cluster +TAG_RAY_CLUSTER_NAME = "ray-cluster-name" + +# Hash of the node launch config, used to identify out-of-date nodes +TAG_RAY_LAUNCH_CONFIG = "ray-launch-config" + +# Hash of the node runtime config, used to determine if updates are needed +TAG_RAY_RUNTIME_CONFIG = "ray-runtime-config" +# Hash of the contents of the directories specified by the file_mounts config +# if the node is a worker, this also hashes content of the directories +# specified by the cluster_synced_files config +TAG_RAY_FILE_MOUNTS_CONTENTS = "ray-file-mounts-contents" + +# Tag for the launch request id, used to identify nodes launched by the same +# launch request. +TAG_RAY_LAUNCH_REQUEST = "ray-launch-request" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8677c85b2c2666f45896d685c7477c287ab4f2fd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/__init__.py @@ -0,0 +1,47 @@ +from __future__ import absolute_import + +import os +from pickle import PicklingError + +from ray.cloudpickle.cloudpickle import * # noqa +from ray.cloudpickle.cloudpickle_fast import CloudPickler, dumps, dump # noqa + + +# Conform to the convention used by python serialization libraries, which +# expose their Pickler subclass at top-level under the "Pickler" name. +Pickler = CloudPickler + +__version__ = '3.0.0' + + +def _warn_msg(obj, method, exc): + return ( + f"{method}({str(obj)}) failed." + "\nTo check which non-serializable variables are captured " + "in scope, re-run the ray script with 'RAY_PICKLE_VERBOSE_DEBUG=1'.") + + +def dump_debug(obj, *args, **kwargs): + try: + return dump(obj, *args, **kwargs) + except (TypeError, PicklingError) as exc: + if os.environ.get("RAY_PICKLE_VERBOSE_DEBUG"): + from ray.util.check_serialize import inspect_serializability + inspect_serializability(obj) + raise + else: + msg = _warn_msg(obj, "ray.cloudpickle.dump", exc) + raise type(exc)(msg) + + +def dumps_debug(obj, *args, **kwargs): + try: + return dumps(obj, *args, **kwargs) + except (TypeError, PicklingError) as exc: + if os.environ.get("RAY_PICKLE_VERBOSE_DEBUG"): + from ray.util.check_serialize import inspect_serializability + inspect_serializability(obj) + raise + else: + msg = _warn_msg(obj, "ray.cloudpickle.dumps", exc) + raise type(exc)(msg) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle.py new file mode 100644 index 0000000000000000000000000000000000000000..8f00b5f3f9769f8c549f25e8affe0198e5a65655 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle.py @@ -0,0 +1,1487 @@ +"""Pickler class to extend the standard pickle.Pickler functionality + +The main objective is to make it natural to perform distributed computing on +clusters (such as PySpark, Dask, Ray...) with interactively defined code +(functions, classes, ...) written in notebooks or console. + +In particular this pickler adds the following features: +- serialize interactively-defined or locally-defined functions, classes, + enums, typevars, lambdas and nested functions to compiled byte code; +- deal with some other non-serializable objects in an ad-hoc manner where + applicable. + +This pickler is therefore meant to be used for the communication between short +lived Python processes running the same version of Python and libraries. In +particular, it is not meant to be used for long term storage of Python objects. + +It does not include an unpickler, as standard Python unpickling suffices. + +This module was extracted from the `cloud` package, developed by `PiCloud, Inc. +`_. + +Copyright (c) 2012-now, CloudPickle developers and contributors. +Copyright (c) 2012, Regents of the University of California. +Copyright (c) 2009 `PiCloud, Inc. `_. +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions +are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the University of California, Berkeley nor the + names of its contributors may be used to endorse or promote + products derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED +TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +""" + +import _collections_abc +from collections import ChainMap, OrderedDict +import abc +import builtins +import copyreg +import dataclasses +import dis +from enum import Enum +import io +import itertools +import logging +import opcode +import pickle +from pickle import _getattribute +import platform +import struct +import sys +import threading +import types +import typing +import uuid +import warnings +import weakref + +# The following import is required to be imported in the cloudpickle +# namespace to be able to load pickle files generated with older versions of +# cloudpickle. See: tests/test_backward_compat.py +from types import CellType # noqa: F401 + + +# cloudpickle is meant for inter process communication: we expect all +# communicating processes to run the same Python version hence we favor +# communication speed over compatibility: +DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL + +# Names of modules whose resources should be treated as dynamic. +_PICKLE_BY_VALUE_MODULES = set() + +# Track the provenance of reconstructed dynamic classes to make it possible to +# reconstruct instances from the matching singleton class definition when +# appropriate and preserve the usual "isinstance" semantics of Python objects. +_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary() +_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary() +_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock() + +PYPY = platform.python_implementation() == "PyPy" + +builtin_code_type = None +if PYPY: + # builtin-code objects only exist in pypy + builtin_code_type = type(float.__new__.__code__) + +_extract_code_globals_cache = weakref.WeakKeyDictionary() + + +def _get_or_create_tracker_id(class_def): + with _DYNAMIC_CLASS_TRACKER_LOCK: + class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def) + if class_tracker_id is None: + class_tracker_id = uuid.uuid4().hex + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + _DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def + return class_tracker_id + + +def _lookup_class_or_track(class_tracker_id, class_def): + if class_tracker_id is not None: + with _DYNAMIC_CLASS_TRACKER_LOCK: + class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault( + class_tracker_id, class_def + ) + _DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id + return class_def + + +def register_pickle_by_value(module): + """Register a module to make it functions and classes picklable by value. + + By default, functions and classes that are attributes of an importable + module are to be pickled by reference, that is relying on re-importing + the attribute from the module at load time. + + If `register_pickle_by_value(module)` is called, all its functions and + classes are subsequently to be pickled by value, meaning that they can + be loaded in Python processes where the module is not importable. + + This is especially useful when developing a module in a distributed + execution environment: restarting the client Python process with the new + source code is enough: there is no need to re-install the new version + of the module on all the worker nodes nor to restart the workers. + + Note: this feature is considered experimental. See the cloudpickle + README.md file for more details and limitations. + """ + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + # In the future, cloudpickle may need a way to access any module registered + # for pickling by value in order to introspect relative imports inside + # functions pickled by value. (see + # https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633). + # This access can be ensured by checking that module is present in + # sys.modules at registering time and assuming that it will still be in + # there when accessed during pickling. Another alternative would be to + # store a weakref to the module. Even though cloudpickle does not implement + # this introspection yet, in order to avoid a possible breaking change + # later, we still enforce the presence of module inside sys.modules. + if module.__name__ not in sys.modules: + raise ValueError( + f"{module} was not imported correctly, have you used an " + "`import` statement to access it?" + ) + _PICKLE_BY_VALUE_MODULES.add(module.__name__) + + +def unregister_pickle_by_value(module): + """Unregister that the input module should be pickled by value.""" + if not isinstance(module, types.ModuleType): + raise ValueError(f"Input should be a module object, got {str(module)} instead") + if module.__name__ not in _PICKLE_BY_VALUE_MODULES: + raise ValueError(f"{module} is not registered for pickle by value") + else: + _PICKLE_BY_VALUE_MODULES.remove(module.__name__) + + +def list_registry_pickle_by_value(): + return _PICKLE_BY_VALUE_MODULES.copy() + + +def _is_registered_pickle_by_value(module): + module_name = module.__name__ + if module_name in _PICKLE_BY_VALUE_MODULES: + return True + while True: + parent_name = module_name.rsplit(".", 1)[0] + if parent_name == module_name: + break + if parent_name in _PICKLE_BY_VALUE_MODULES: + return True + module_name = parent_name + return False + + +def _whichmodule(obj, name): + """Find the module an object belongs to. + + This function differs from ``pickle.whichmodule`` in two ways: + - it does not mangle the cases where obj's module is __main__ and obj was + not found in any module. + - Errors arising during module introspection are ignored, as those errors + are considered unwanted side effects. + """ + module_name = getattr(obj, "__module__", None) + + if module_name is not None: + return module_name + # Protect the iteration by using a copy of sys.modules against dynamic + # modules that trigger imports of other modules upon calls to getattr or + # other threads importing at the same time. + for module_name, module in sys.modules.copy().items(): + # Some modules such as coverage can inject non-module objects inside + # sys.modules + if ( + module_name == "__main__" + or module is None + or not isinstance(module, types.ModuleType) + ): + continue + try: + if _getattribute(module, name)[0] is obj: + return module_name + except Exception: + pass + return None + + +def _should_pickle_by_reference(obj, name=None): + """Test whether an function or a class should be pickled by reference + + Pickling by reference means by that the object (typically a function or a + class) is an attribute of a module that is assumed to be importable in the + target Python environment. Loading will therefore rely on importing the + module and then calling `getattr` on it to access the function or class. + + Pickling by reference is the only option to pickle functions and classes + in the standard library. In cloudpickle the alternative option is to + pickle by value (for instance for interactively or locally defined + functions and classes or for attributes of modules that have been + explicitly registered to be pickled by value. + """ + if isinstance(obj, types.FunctionType) or issubclass(type(obj), type): + module_and_name = _lookup_module_and_qualname(obj, name=name) + if module_and_name is None: + return False + module, name = module_and_name + return not _is_registered_pickle_by_value(module) + + elif isinstance(obj, types.ModuleType): + # We assume that sys.modules is primarily used as a cache mechanism for + # the Python import machinery. Checking if a module has been added in + # is sys.modules therefore a cheap and simple heuristic to tell us + # whether we can assume that a given module could be imported by name + # in another Python process. + if _is_registered_pickle_by_value(obj): + return False + return obj.__name__ in sys.modules + else: + raise TypeError( + "cannot check importability of {} instances".format(type(obj).__name__) + ) + + +def _lookup_module_and_qualname(obj, name=None): + if name is None: + name = getattr(obj, "__qualname__", None) + if name is None: # pragma: no cover + # This used to be needed for Python 2.7 support but is probably not + # needed anymore. However we keep the __name__ introspection in case + # users of cloudpickle rely on this old behavior for unknown reasons. + name = getattr(obj, "__name__", None) + + module_name = _whichmodule(obj, name) + + if module_name is None: + # In this case, obj.__module__ is None AND obj was not found in any + # imported module. obj is thus treated as dynamic. + return None + + if module_name == "__main__": + return None + + # Note: if module_name is in sys.modules, the corresponding module is + # assumed importable at unpickling time. See #357 + module = sys.modules.get(module_name, None) + if module is None: + # The main reason why obj's module would not be imported is that this + # module has been dynamically created, using for example + # types.ModuleType. The other possibility is that module was removed + # from sys.modules after obj was created/imported. But this case is not + # supported, as the standard pickle does not support it either. + return None + + try: + obj2, parent = _getattribute(module, name) + except AttributeError: + # obj was not found inside the module it points to + return None + if obj2 is not obj: + return None + return module, name + + +def _extract_code_globals(co): + """Find all globals names read or written to by codeblock co.""" + out_names = _extract_code_globals_cache.get(co) + if out_names is None: + # We use a dict with None values instead of a set to get a + # deterministic order and avoid introducing non-deterministic pickle + # bytes as a results. + out_names = {name: None for name in _walk_global_ops(co)} + + # Declaring a function inside another one using the "def ..." syntax + # generates a constant code object corresponding to the one of the + # nested function's As the nested function may itself need global + # variables, we need to introspect its code, extract its globals, (look + # for code object in it's co_consts attribute..) and add the result to + # code_globals + if co.co_consts: + for const in co.co_consts: + if isinstance(const, types.CodeType): + out_names.update(_extract_code_globals(const)) + + _extract_code_globals_cache[co] = out_names + + return out_names + + +def _find_imported_submodules(code, top_level_dependencies): + """Find currently imported submodules used by a function. + + Submodules used by a function need to be detected and referenced for the + function to work correctly at depickling time. Because submodules can be + referenced as attribute of their parent package (``package.submodule``), we + need a special introspection technique that does not rely on GLOBAL-related + opcodes to find references of them in a code object. + + Example: + ``` + import concurrent.futures + import cloudpickle + def func(): + x = concurrent.futures.ThreadPoolExecutor + if __name__ == '__main__': + cloudpickle.dumps(func) + ``` + The globals extracted by cloudpickle in the function's state include the + concurrent package, but not its submodule (here, concurrent.futures), which + is the module used by func. Find_imported_submodules will detect the usage + of concurrent.futures. Saving this module alongside with func will ensure + that calling func once depickled does not fail due to concurrent.futures + not being imported + """ + + subimports = [] + # check if any known dependency is an imported package + for x in top_level_dependencies: + if ( + isinstance(x, types.ModuleType) + and hasattr(x, "__package__") + and x.__package__ + ): + # check if the package has any currently loaded sub-imports + prefix = x.__name__ + "." + # A concurrent thread could mutate sys.modules, + # make sure we iterate over a copy to avoid exceptions + for name in list(sys.modules): + # Older versions of pytest will add a "None" module to + # sys.modules. + if name is not None and name.startswith(prefix): + # check whether the function can address the sub-module + tokens = set(name[len(prefix) :].split(".")) + if not tokens - set(code.co_names): + subimports.append(sys.modules[name]) + return subimports + + +# relevant opcodes +STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"] +DELETE_GLOBAL = opcode.opmap["DELETE_GLOBAL"] +LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"] +GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL) +HAVE_ARGUMENT = dis.HAVE_ARGUMENT +EXTENDED_ARG = dis.EXTENDED_ARG + + +_BUILTIN_TYPE_NAMES = {} +for k, v in types.__dict__.items(): + if type(v) is type: + _BUILTIN_TYPE_NAMES[v] = k + + +def _builtin_type(name): + if name == "ClassType": # pragma: no cover + # Backward compat to load pickle files generated with cloudpickle + # < 1.3 even if loading pickle files from older versions is not + # officially supported. + return type + return getattr(types, name) + + +def _walk_global_ops(code): + """Yield referenced name for global-referencing instructions in code.""" + for instr in dis.get_instructions(code): + op = instr.opcode + if op in GLOBAL_OPS: + yield instr.argval + + +def _extract_class_dict(cls): + """Retrieve a copy of the dict of a class without the inherited method.""" + clsdict = dict(cls.__dict__) # copy dict proxy to a dict + if len(cls.__bases__) == 1: + inherited_dict = cls.__bases__[0].__dict__ + else: + inherited_dict = {} + for base in reversed(cls.__bases__): + inherited_dict.update(base.__dict__) + to_remove = [] + for name, value in clsdict.items(): + try: + base_value = inherited_dict[name] + if value is base_value: + to_remove.append(name) + except KeyError: + pass + for name in to_remove: + clsdict.pop(name) + return clsdict + + +def is_tornado_coroutine(func): + """Return whether `func` is a Tornado coroutine function. + + Running coroutines are not supported. + """ + warnings.warn( + "is_tornado_coroutine is deprecated in cloudpickle 3.0 and will be " + "removed in cloudpickle 4.0. Use tornado.gen.is_coroutine_function " + "directly instead.", + category=DeprecationWarning, + ) + if "tornado.gen" not in sys.modules: + return False + gen = sys.modules["tornado.gen"] + if not hasattr(gen, "is_coroutine_function"): + # Tornado version is too old + return False + return gen.is_coroutine_function(func) + + +def subimport(name): + # We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is + # the name of a submodule, __import__ will return the top-level root module + # of this submodule. For instance, __import__('os.path') returns the `os` + # module. + __import__(name) + return sys.modules[name] + + +def dynamic_subimport(name, vars): + mod = types.ModuleType(name) + mod.__dict__.update(vars) + mod.__dict__["__builtins__"] = builtins.__dict__ + return mod + + +def _get_cell_contents(cell): + try: + return cell.cell_contents + except ValueError: + # Handle empty cells explicitly with a sentinel value. + return _empty_cell_value + + +def instance(cls): + """Create a new instance of a class. + + Parameters + ---------- + cls : type + The class to create an instance of. + + Returns + ------- + instance : cls + A new instance of ``cls``. + """ + return cls() + + +@instance +class _empty_cell_value: + """Sentinel for empty closures.""" + + @classmethod + def __reduce__(cls): + return cls.__name__ + + +def _make_function(code, globals, name, argdefs, closure): + # Setting __builtins__ in globals is needed for nogil CPython. + globals["__builtins__"] = __builtins__ + return types.FunctionType(code, globals, name, argdefs, closure) + + +def _make_empty_cell(): + if False: + # trick the compiler into creating an empty cell in our lambda + cell = None + raise AssertionError("this route should not be executed") + + return (lambda: cell).__closure__[0] + + +def _make_cell(value=_empty_cell_value): + cell = _make_empty_cell() + if value is not _empty_cell_value: + cell.cell_contents = value + return cell + + +def _make_skeleton_class( + type_constructor, name, bases, type_kwargs, class_tracker_id, extra +): + """Build dynamic class with an empty __dict__ to be filled once memoized + + If class_tracker_id is not None, try to lookup an existing class definition + matching that id. If none is found, track a newly reconstructed class + definition under that id so that other instances stemming from the same + class id will also reuse this class definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + skeleton_class = types.new_class( + name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs) + ) + return _lookup_class_or_track(class_tracker_id, skeleton_class) + + +def _make_skeleton_enum( + bases, name, qualname, members, module, class_tracker_id, extra +): + """Build dynamic enum with an empty __dict__ to be filled once memoized + + The creation of the enum class is inspired by the code of + EnumMeta._create_. + + If class_tracker_id is not None, try to lookup an existing enum definition + matching that id. If none is found, track a newly reconstructed enum + definition under that id so that other instances stemming from the same + class id will also reuse this enum definition. + + The "extra" variable is meant to be a dict (or None) that can be used for + forward compatibility shall the need arise. + """ + # enums always inherit from their base Enum class at the last position in + # the list of base classes: + enum_base = bases[-1] + metacls = enum_base.__class__ + classdict = metacls.__prepare__(name, bases) + + for member_name, member_value in members.items(): + classdict[member_name] = member_value + enum_class = metacls.__new__(metacls, name, bases, classdict) + enum_class.__module__ = module + enum_class.__qualname__ = qualname + + return _lookup_class_or_track(class_tracker_id, enum_class) + + +def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id): + tv = typing.TypeVar( + name, + *constraints, + bound=bound, + covariant=covariant, + contravariant=contravariant, + ) + return _lookup_class_or_track(class_tracker_id, tv) + + +def _decompose_typevar(obj): + return ( + obj.__name__, + obj.__bound__, + obj.__constraints__, + obj.__covariant__, + obj.__contravariant__, + _get_or_create_tracker_id(obj), + ) + + +def _typevar_reduce(obj): + # TypeVar instances require the module information hence why we + # are not using the _should_pickle_by_reference directly + module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__) + + if module_and_name is None: + return (_make_typevar, _decompose_typevar(obj)) + elif _is_registered_pickle_by_value(module_and_name[0]): + return (_make_typevar, _decompose_typevar(obj)) + + return (getattr, module_and_name) + + +def _get_bases(typ): + if "__orig_bases__" in getattr(typ, "__dict__", {}): + # For generic types (see PEP 560) + # Note that simply checking `hasattr(typ, '__orig_bases__')` is not + # correct. Subclasses of a fully-parameterized generic class does not + # have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')` + # will return True because it's defined in the base class. + bases_attr = "__orig_bases__" + else: + # For regular class objects + bases_attr = "__bases__" + return getattr(typ, bases_attr) + + +def _make_dict_keys(obj, is_ordered=False): + if is_ordered: + return OrderedDict.fromkeys(obj).keys() + else: + return dict.fromkeys(obj).keys() + + +def _make_dict_values(obj, is_ordered=False): + if is_ordered: + return OrderedDict((i, _) for i, _ in enumerate(obj)).values() + else: + return {i: _ for i, _ in enumerate(obj)}.values() + + +def _make_dict_items(obj, is_ordered=False): + if is_ordered: + return OrderedDict(obj).items() + else: + return obj.items() + + +# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS +# ------------------------------------------------- + + +def _class_getnewargs(obj): + type_kwargs = {} + if "__module__" in obj.__dict__: + type_kwargs["__module__"] = obj.__module__ + + __dict__ = obj.__dict__.get("__dict__", None) + if isinstance(__dict__, property): + type_kwargs["__dict__"] = __dict__ + + return ( + type(obj), + obj.__name__, + _get_bases(obj), + type_kwargs, + _get_or_create_tracker_id(obj), + None, + ) + + +def _enum_getnewargs(obj): + members = {e.name: e.value for e in obj} + return ( + obj.__bases__, + obj.__name__, + obj.__qualname__, + members, + obj.__module__, + _get_or_create_tracker_id(obj), + None, + ) + + +# COLLECTION OF OBJECTS RECONSTRUCTORS +# ------------------------------------ +def _file_reconstructor(retval): + return retval + + +# COLLECTION OF OBJECTS STATE GETTERS +# ----------------------------------- + + +def _function_getstate(func): + # - Put func's dynamic attributes (stored in func.__dict__) in state. These + # attributes will be restored at unpickling time using + # f.__dict__.update(state) + # - Put func's members into slotstate. Such attributes will be restored at + # unpickling time by iterating over slotstate and calling setattr(func, + # slotname, slotvalue) + slotstate = { + "__name__": func.__name__, + "__qualname__": func.__qualname__, + "__annotations__": func.__annotations__, + "__kwdefaults__": func.__kwdefaults__, + "__defaults__": func.__defaults__, + "__module__": func.__module__, + "__doc__": func.__doc__, + "__closure__": func.__closure__, + } + + f_globals_ref = _extract_code_globals(func.__code__) + f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__} + + if func.__closure__ is not None: + closure_values = list(map(_get_cell_contents, func.__closure__)) + else: + closure_values = () + + # Extract currently-imported submodules used by func. Storing these modules + # in a smoke _cloudpickle_subimports attribute of the object's state will + # trigger the side effect of importing these modules at unpickling time + # (which is necessary for func to work correctly once depickled) + slotstate["_cloudpickle_submodules"] = _find_imported_submodules( + func.__code__, itertools.chain(f_globals.values(), closure_values) + ) + slotstate["__globals__"] = f_globals + + state = func.__dict__ + return state, slotstate + + +def _class_getstate(obj): + clsdict = _extract_class_dict(obj) + clsdict.pop("__weakref__", None) + + if issubclass(type(obj), abc.ABCMeta): + # If obj is an instance of an ABCMeta subclass, don't pickle the + # cache/negative caches populated during isinstance/issubclass + # checks, but pickle the list of registered subclasses of obj. + clsdict.pop("_abc_cache", None) + clsdict.pop("_abc_negative_cache", None) + clsdict.pop("_abc_negative_cache_version", None) + registry = clsdict.pop("_abc_registry", None) + if registry is None: + # The abc caches and registered subclasses of a + # class are bundled into the single _abc_impl attribute + clsdict.pop("_abc_impl", None) + (registry, _, _, _) = abc._get_dump(obj) + + clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry] + else: + # In the above if clause, registry is a set of weakrefs -- in + # this case, registry is a WeakSet + clsdict["_abc_impl"] = [type_ for type_ in registry] + + if "__slots__" in clsdict: + # pickle string length optimization: member descriptors of obj are + # created automatically from obj's __slots__ attribute, no need to + # save them in obj's state + if isinstance(obj.__slots__, str): + clsdict.pop(obj.__slots__) + else: + for k in obj.__slots__: + clsdict.pop(k, None) + + clsdict.pop("__dict__", None) # unpicklable property object + + return (clsdict, {}) + + +def _enum_getstate(obj): + clsdict, slotstate = _class_getstate(obj) + + members = {e.name: e.value for e in obj} + # Cleanup the clsdict that will be passed to _make_skeleton_enum: + # Those attributes are already handled by the metaclass. + for attrname in [ + "_generate_next_value_", + "_member_names_", + "_member_map_", + "_member_type_", + "_value2member_map_", + ]: + clsdict.pop(attrname, None) + for member in members: + clsdict.pop(member) + # Special handling of Enum subclasses + return clsdict, slotstate + + +# COLLECTIONS OF OBJECTS REDUCERS +# ------------------------------- +# A reducer is a function taking a single argument (obj), and that returns a +# tuple with all the necessary data to re-construct obj. Apart from a few +# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to +# correctly pickle an object. +# While many built-in objects (Exceptions objects, instances of the "object" +# class, etc), are shipped with their own built-in reducer (invoked using +# obj.__reduce__), some do not. The following methods were created to "fill +# these holes". + + +def _code_reduce(obj): + """code object reducer.""" + # If you are not sure about the order of arguments, take a look at help + # of the specific type from types, for example: + # >>> from types import CodeType + # >>> help(CodeType) + if hasattr(obj, "co_exceptiontable"): + # Python 3.11 and later: there are some new attributes + # related to the enhanced exceptions. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_names, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_qualname, + obj.co_firstlineno, + obj.co_linetable, + obj.co_exceptiontable, + obj.co_freevars, + obj.co_cellvars, + ) + elif hasattr(obj, "co_linetable"): + # Python 3.10 and later: obj.co_lnotab is deprecated and constructor + # expects obj.co_linetable instead. + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_names, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_firstlineno, + obj.co_linetable, + obj.co_freevars, + obj.co_cellvars, + ) + elif hasattr(obj, "co_nmeta"): # pragma: no cover + # "nogil" Python: modified attributes from 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_framesize, + obj.co_ndefaultargs, + obj.co_nmeta, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_firstlineno, + obj.co_lnotab, + obj.co_exc_handlers, + obj.co_jump_table, + obj.co_freevars, + obj.co_cellvars, + obj.co_free2reg, + obj.co_cell2reg, + ) + else: + # Backward compat for 3.8 and 3.9 + args = ( + obj.co_argcount, + obj.co_posonlyargcount, + obj.co_kwonlyargcount, + obj.co_nlocals, + obj.co_stacksize, + obj.co_flags, + obj.co_code, + obj.co_consts, + obj.co_names, + obj.co_varnames, + obj.co_filename, + obj.co_name, + obj.co_firstlineno, + obj.co_lnotab, + obj.co_freevars, + obj.co_cellvars, + ) + return types.CodeType, args + + +def _cell_reduce(obj): + """Cell (containing values of a function's free variables) reducer.""" + try: + obj.cell_contents + except ValueError: # cell is empty + return _make_empty_cell, () + else: + return _make_cell, (obj.cell_contents,) + + +def _classmethod_reduce(obj): + orig_func = obj.__func__ + return type(obj), (orig_func,) + + +def _file_reduce(obj): + """Save a file.""" + import io + + if not hasattr(obj, "name") or not hasattr(obj, "mode"): + raise pickle.PicklingError( + "Cannot pickle files that do not map to an actual file" + ) + if obj is sys.stdout: + return getattr, (sys, "stdout") + if obj is sys.stderr: + return getattr, (sys, "stderr") + if obj is sys.stdin: + raise pickle.PicklingError("Cannot pickle standard input") + if obj.closed: + raise pickle.PicklingError("Cannot pickle closed files") + if hasattr(obj, "isatty") and obj.isatty(): + raise pickle.PicklingError("Cannot pickle files that map to tty objects") + if "r" not in obj.mode and "+" not in obj.mode: + raise pickle.PicklingError( + "Cannot pickle files that are not opened for reading: %s" % obj.mode + ) + + name = obj.name + + retval = io.StringIO() + + try: + # Read the whole file + curloc = obj.tell() + obj.seek(0) + contents = obj.read() + obj.seek(curloc) + except OSError as e: + raise pickle.PicklingError( + "Cannot pickle file %s as it cannot be read" % name + ) from e + retval.write(contents) + retval.seek(curloc) + + retval.name = name + return _file_reconstructor, (retval,) + + +def _getset_descriptor_reduce(obj): + return getattr, (obj.__objclass__, obj.__name__) + + +def _mappingproxy_reduce(obj): + return types.MappingProxyType, (dict(obj),) + + +def _memoryview_reduce(obj): + return bytes, (obj.tobytes(),) + + +def _module_reduce(obj): + if _should_pickle_by_reference(obj): + return subimport, (obj.__name__,) + else: + # Some external libraries can populate the "__builtins__" entry of a + # module's `__dict__` with unpicklable objects (see #316). For that + # reason, we do not attempt to pickle the "__builtins__" entry, and + # restore a default value for it at unpickling time. + state = obj.__dict__.copy() + state.pop("__builtins__", None) + return dynamic_subimport, (obj.__name__, state) + + +def _method_reduce(obj): + return (types.MethodType, (obj.__func__, obj.__self__)) + + +def _logger_reduce(obj): + return logging.getLogger, (obj.name,) + + +def _root_logger_reduce(obj): + return logging.getLogger, () + + +def _property_reduce(obj): + return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__) + + +def _weakset_reduce(obj): + return weakref.WeakSet, (list(obj),) + + +def _dynamic_class_reduce(obj): + """Save a class that can't be referenced as a module attribute. + + This method is used to serialize classes that are defined inside + functions, or that otherwise can't be serialized as attribute lookups + from importable modules. + """ + if Enum is not None and issubclass(obj, Enum): + return ( + _make_skeleton_enum, + _enum_getnewargs(obj), + _enum_getstate(obj), + None, + None, + _class_setstate, + ) + else: + return ( + _make_skeleton_class, + _class_getnewargs(obj), + _class_getstate(obj), + None, + None, + _class_setstate, + ) + + +def _class_reduce(obj): + """Select the reducer depending on the dynamic nature of the class obj.""" + if obj is type(None): # noqa + return type, (None,) + elif obj is type(Ellipsis): + return type, (Ellipsis,) + elif obj is type(NotImplemented): + return type, (NotImplemented,) + elif obj in _BUILTIN_TYPE_NAMES: + return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],) + elif not _should_pickle_by_reference(obj): + return _dynamic_class_reduce(obj) + return NotImplemented + + +def _dict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj),) + + +def _dict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj),) + + +def _dict_items_reduce(obj): + return _make_dict_items, (dict(obj),) + + +def _odict_keys_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_keys, (list(obj), True) + + +def _odict_values_reduce(obj): + # Safer not to ship the full dict as sending the rest might + # be unintended and could potentially cause leaking of + # sensitive information + return _make_dict_values, (list(obj), True) + + +def _odict_items_reduce(obj): + return _make_dict_items, (dict(obj), True) + + +def _dataclass_field_base_reduce(obj): + return _get_dataclass_field_type_sentinel, (obj.name,) + + +# COLLECTIONS OF OBJECTS STATE SETTERS +# ------------------------------------ +# state setters are called at unpickling time, once the object is created and +# it has to be updated to how it was at unpickling time. + + +def _function_setstate(obj, state): + """Update the state of a dynamic function. + + As __closure__ and __globals__ are readonly attributes of a function, we + cannot rely on the native setstate routine of pickle.load_build, that calls + setattr on items of the slotstate. Instead, we have to modify them inplace. + """ + state, slotstate = state + obj.__dict__.update(state) + + obj_globals = slotstate.pop("__globals__") + obj_closure = slotstate.pop("__closure__") + # _cloudpickle_subimports is a set of submodules that must be loaded for + # the pickled function to work correctly at unpickling time. Now that these + # submodules are depickled (hence imported), they can be removed from the + # object's state (the object state only served as a reference holder to + # these submodules) + slotstate.pop("_cloudpickle_submodules") + + obj.__globals__.update(obj_globals) + obj.__globals__["__builtins__"] = __builtins__ + + if obj_closure is not None: + for i, cell in enumerate(obj_closure): + try: + value = cell.cell_contents + except ValueError: # cell is empty + continue + obj.__closure__[i].cell_contents = value + + for k, v in slotstate.items(): + setattr(obj, k, v) + + +def _class_setstate(obj, state): + state, slotstate = state + registry = None + for attrname, attr in state.items(): + if attrname == "_abc_impl": + registry = attr + else: + setattr(obj, attrname, attr) + if registry is not None: + for subclass in registry: + obj.register(subclass) + + return obj + + +# COLLECTION OF DATACLASS UTILITIES +# --------------------------------- +# There are some internal sentinel values whose identity must be preserved when +# unpickling dataclass fields. Each sentinel value has a unique name that we can +# use to retrieve its identity at unpickling time. + + +_DATACLASSE_FIELD_TYPE_SENTINELS = { + dataclasses._FIELD.name: dataclasses._FIELD, + dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR, + dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR, +} + + +def _get_dataclass_field_type_sentinel(name): + return _DATACLASSE_FIELD_TYPE_SENTINELS[name] + + +class Pickler(pickle.Pickler): + # set of reducers defined and used by cloudpickle (private) + _dispatch_table = {} + _dispatch_table[classmethod] = _classmethod_reduce + _dispatch_table[io.TextIOWrapper] = _file_reduce + _dispatch_table[logging.Logger] = _logger_reduce + _dispatch_table[logging.RootLogger] = _root_logger_reduce + _dispatch_table[memoryview] = _memoryview_reduce + _dispatch_table[property] = _property_reduce + _dispatch_table[staticmethod] = _classmethod_reduce + _dispatch_table[CellType] = _cell_reduce + _dispatch_table[types.CodeType] = _code_reduce + _dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce + _dispatch_table[types.ModuleType] = _module_reduce + _dispatch_table[types.MethodType] = _method_reduce + _dispatch_table[types.MappingProxyType] = _mappingproxy_reduce + _dispatch_table[weakref.WeakSet] = _weakset_reduce + _dispatch_table[typing.TypeVar] = _typevar_reduce + _dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce + _dispatch_table[_collections_abc.dict_values] = _dict_values_reduce + _dispatch_table[_collections_abc.dict_items] = _dict_items_reduce + _dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce + _dispatch_table[type(OrderedDict().values())] = _odict_values_reduce + _dispatch_table[type(OrderedDict().items())] = _odict_items_reduce + _dispatch_table[abc.abstractmethod] = _classmethod_reduce + _dispatch_table[abc.abstractclassmethod] = _classmethod_reduce + _dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce + _dispatch_table[abc.abstractproperty] = _property_reduce + _dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce + + dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table) + + # function reducers are defined as instance methods of cloudpickle.Pickler + # objects, as they rely on a cloudpickle.Pickler attribute (globals_ref) + def _dynamic_function_reduce(self, func): + """Reduce a function that is not pickleable via attribute lookup.""" + newargs = self._function_getnewargs(func) + state = _function_getstate(func) + return (_make_function, newargs, state, None, None, _function_setstate) + + def _function_reduce(self, obj): + """Reducer for function objects. + + If obj is a top-level attribute of a file-backed module, this reducer + returns NotImplemented, making the cloudpickle.Pickler fall back to + traditional pickle.Pickler routines to save obj. Otherwise, it reduces + obj using a custom cloudpickle reducer designed specifically to handle + dynamic functions. + """ + if _should_pickle_by_reference(obj): + return NotImplemented + else: + return self._dynamic_function_reduce(obj) + + def _function_getnewargs(self, func): + code = func.__code__ + + # base_globals represents the future global namespace of func at + # unpickling time. Looking it up and storing it in + # cloudpickle.Pickler.globals_ref allow functions sharing the same + # globals at pickling time to also share them once unpickled, at one + # condition: since globals_ref is an attribute of a cloudpickle.Pickler + # instance, and that a new cloudpickle.Pickler is created each time + # cloudpickle.dump or cloudpickle.dumps is called, functions also need + # to be saved within the same invocation of + # cloudpickle.dump/cloudpickle.dumps (for example: + # cloudpickle.dumps([f1, f2])). There is no such limitation when using + # cloudpickle.Pickler.dump, as long as the multiple invocations are + # bound to the same cloudpickle.Pickler instance. + base_globals = self.globals_ref.setdefault(id(func.__globals__), {}) + + if base_globals == {}: + # Add module attributes used to resolve relative imports + # instructions inside func. + for k in ["__package__", "__name__", "__path__", "__file__"]: + if k in func.__globals__: + base_globals[k] = func.__globals__[k] + + # Do not bind the free variables before the function is created to + # avoid infinite recursion. + if func.__closure__ is None: + closure = None + else: + closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars))) + + return code, base_globals, None, None, closure + + def dump(self, obj): + try: + return super().dump(obj) + except RuntimeError as e: + if len(e.args) > 0 and "recursion" in e.args[0]: + msg = "Could not pickle object as excessively deep recursion required." + raise pickle.PicklingError(msg) from e + else: + raise + + def __init__(self, file, protocol=None, buffer_callback=None): + if protocol is None: + protocol = DEFAULT_PROTOCOL + super().__init__(file, protocol=protocol, buffer_callback=buffer_callback) + # map functions __globals__ attribute ids, to ensure that functions + # sharing the same global namespace at pickling time also share + # their global namespace at unpickling time. + self.globals_ref = {} + self.proto = int(protocol) + + if not PYPY: + # pickle.Pickler is the C implementation of the CPython pickler and + # therefore we rely on reduce_override method to customize the pickler + # behavior. + + # `cloudpickle.Pickler.dispatch` is only left for backward + # compatibility - note that when using protocol 5, + # `cloudpickle.Pickler.dispatch` is not an extension of + # `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler` + # subclasses the C-implemented `pickle.Pickler`, which does not expose + # a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler` + # used `cloudpickle.Pickler.dispatch` as a class-level attribute + # storing all reducers implemented by cloudpickle, but the attribute + # name was not a great choice given because it would collide with a + # similarly named attribute in the pure-Python `pickle._Pickler` + # implementation in the standard library. + dispatch = dispatch_table + + # Implementation of the reducer_override callback, in order to + # efficiently serialize dynamic functions and classes by subclassing + # the C-implemented `pickle.Pickler`. + # TODO: decorrelate reducer_override (which is tied to CPython's + # implementation - would it make sense to backport it to pypy? - and + # pickle's protocol 5 which is implementation agnostic. Currently, the + # availability of both notions coincide on CPython's pickle, but it may + # not be the case anymore when pypy implements protocol 5. + + def reducer_override(self, obj): + """Type-agnostic reducing callback for function and classes. + + For performance reasons, subclasses of the C `pickle.Pickler` class + cannot register custom reducers for functions and classes in the + dispatch_table attribute. Reducers for such types must instead + implemented via the special `reducer_override` method. + + Note that this method will be called for any object except a few + builtin-types (int, lists, dicts etc.), which differs from reducers + in the Pickler's dispatch_table, each of them being invoked for + objects of a specific type only. + + This property comes in handy for classes: although most classes are + instances of the ``type`` metaclass, some of them can be instances + of other custom metaclasses (such as enum.EnumMeta for example). In + particular, the metaclass will likely not be known in advance, and + thus cannot be special-cased using an entry in the dispatch_table. + reducer_override, among other things, allows us to register a + reducer that will be called for any class, independently of its + type. + + Notes: + + * reducer_override has the priority over dispatch_table-registered + reducers. + * reducer_override can be used to fix other limitations of + cloudpickle for other types that suffered from type-specific + reducers, such as Exceptions. See + https://github.com/cloudpipe/cloudpickle/issues/248 + """ + t = type(obj) + try: + is_anyclass = issubclass(t, type) + except TypeError: # t is not a class (old Boost; see SF #502085) + is_anyclass = False + + if is_anyclass: + return _class_reduce(obj) + elif isinstance(obj, types.FunctionType): + return self._function_reduce(obj) + else: + # fallback to save_global, including the Pickler's + # dispatch_table + return NotImplemented + + else: + # When reducer_override is not available, hack the pure-Python + # Pickler's types.FunctionType and type savers. Note: the type saver + # must override Pickler.save_global, because pickle.py contains a + # hard-coded call to save_global when pickling meta-classes. + dispatch = pickle.Pickler.dispatch.copy() + + def _save_reduce_pickle5( + self, + func, + args, + state=None, + listitems=None, + dictitems=None, + state_setter=None, + obj=None, + ): + save = self.save + write = self.write + self.save_reduce( + func, + args, + state=None, + listitems=listitems, + dictitems=dictitems, + obj=obj, + ) + # backport of the Python 3.8 state_setter pickle operations + save(state_setter) + save(obj) # simple BINGET opcode as obj is already memoized. + save(state) + write(pickle.TUPLE2) + # Trigger a state_setter(obj, state) function call. + write(pickle.REDUCE) + # The purpose of state_setter is to carry-out an + # inplace modification of obj. We do not care about what the + # method might return, so its output is eventually removed from + # the stack. + write(pickle.POP) + + def save_global(self, obj, name=None, pack=struct.pack): + """Main dispatch method. + + The name of this method is somewhat misleading: all types get + dispatched here. + """ + if obj is type(None): # noqa + return self.save_reduce(type, (None,), obj=obj) + elif obj is type(Ellipsis): + return self.save_reduce(type, (Ellipsis,), obj=obj) + elif obj is type(NotImplemented): + return self.save_reduce(type, (NotImplemented,), obj=obj) + elif obj in _BUILTIN_TYPE_NAMES: + return self.save_reduce( + _builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj + ) + + if name is not None: + super().save_global(obj, name=name) + elif not _should_pickle_by_reference(obj, name=name): + self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj) + else: + super().save_global(obj, name=name) + + dispatch[type] = save_global + + def save_function(self, obj, name=None): + """Registered with the dispatch to handle all function types. + + Determines what kind of function obj is (e.g. lambda, defined at + interactive prompt, etc) and handles the pickling appropriately. + """ + if _should_pickle_by_reference(obj, name=name): + return super().save_global(obj, name=name) + elif PYPY and isinstance(obj.__code__, builtin_code_type): + return self.save_pypy_builtin_func(obj) + else: + return self._save_reduce_pickle5( + *self._dynamic_function_reduce(obj), obj=obj + ) + + def save_pypy_builtin_func(self, obj): + """Save pypy equivalent of builtin functions. + + PyPy does not have the concept of builtin-functions. Instead, + builtin-functions are simple function instances, but with a + builtin-code attribute. + Most of the time, builtin functions should be pickled by attribute. + But PyPy has flaky support for __qualname__, so some builtin + functions such as float.__new__ will be classified as dynamic. For + this reason only, we created this special routine. Because + builtin-functions are not expected to have closure or globals, + there is no additional hack (compared the one already implemented + in pickle) to protect ourselves from reference cycles. A simple + (reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note + also that PyPy improved their support for __qualname__ in v3.6, so + this routing should be removed when cloudpickle supports only PyPy + 3.6 and later. + """ + rv = ( + types.FunctionType, + (obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__), + obj.__dict__, + ) + self.save_reduce(*rv, obj=obj) + + dispatch[types.FunctionType] = save_function + + +# Shorthands similar to pickle.dump/pickle.dumps + + +def dump(obj, file, protocol=None, buffer_callback=None): + """Serialize obj as bytes streamed into file + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj) + + +def dumps(obj, protocol=None, buffer_callback=None): + """Serialize obj as a string of bytes allocated in memory + + protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to + pickle.HIGHEST_PROTOCOL. This setting favors maximum communication + speed between processes running the same Python version. + + Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure + compatibility with older versions of Python (although this is not always + guaranteed to work because cloudpickle relies on some internal + implementation details that can change from one Python version to the + next). + """ + with io.BytesIO() as file: + cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback) + cp.dump(obj) + return file.getvalue() + + +# Include pickles unloading functions in this namespace for convenience. +load, loads = pickle.load, pickle.loads + +# Backward compat alias. +CloudPickler = Pickler \ No newline at end of file diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle_fast.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..52d6732e44ebcc0053b24969943f7c3b742268bb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/cloudpickle_fast.py @@ -0,0 +1,13 @@ +"""Compatibility module. + +It can be necessary to load files generated by previous versions of cloudpickle +that rely on symbols being defined under the `cloudpickle.cloudpickle_fast` +namespace. + +See: tests/test_backward_compat.py +""" +from . import cloudpickle + + +def __getattr__(name): + return getattr(cloudpickle, name) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/compat.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/compat.py new file mode 100644 index 0000000000000000000000000000000000000000..a2eb12e5080b1dd9e0bb7e16e079fbb262678215 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/compat.py @@ -0,0 +1,19 @@ +import logging +import os + +logger = logging.getLogger(__name__) + +RAY_PICKLE_VERBOSE_DEBUG = os.environ.get("RAY_PICKLE_VERBOSE_DEBUG") +verbose_level = int(RAY_PICKLE_VERBOSE_DEBUG) if RAY_PICKLE_VERBOSE_DEBUG else 0 + +if verbose_level > 1: + logger.warning( + "Environmental variable RAY_PICKLE_VERBOSE_DEBUG is set to " + f"'{verbose_level}', this enabled python-based serialization backend " + f"instead of C-Pickle. Serialization would be very slow." + ) + from ray.cloudpickle import py_pickle as pickle + from ray.cloudpickle.py_pickle import Pickler +else: + import pickle # noqa: F401 + from _pickle import Pickler # noqa: F401 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/py_pickle.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/py_pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..b21840702a5167b38a0ff167eccacc8377453677 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/cloudpickle/py_pickle.py @@ -0,0 +1,30 @@ +from pickle import ( + _Pickler, + _Unpickler as Unpickler, + _loads as loads, + _load as load, + PickleError, + PicklingError, + UnpicklingError, + HIGHEST_PROTOCOL, +) + +__all__ = [ + "PickleError", + "PicklingError", + "UnpicklingError", + "Pickler", + "Unpickler", + "load", + "loads", + "HIGHEST_PROTOCOL", +] + + +class Pickler(_Pickler): + def __init__(self, file, protocol=None, *, fix_imports=True, buffer_callback=None): + super().__init__( + file, protocol, fix_imports=fix_imports, buffer_callback=buffer_callback + ) + # avoid being overrided by cloudpickle + self.dispatch = _Pickler.dispatch.copy() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/libjemalloc.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/libjemalloc.so new file mode 100644 index 0000000000000000000000000000000000000000..2ce59e3d65938408578e721d85346d6105cc5b43 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/libjemalloc.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0284919db23f95e692026039838aef89b5964b5cfec4a88acb9b3a9f4a226fd5 +size 885296 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/gcs/gcs_server b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/gcs/gcs_server new file mode 100644 index 0000000000000000000000000000000000000000..38d151fd4574fdbff0a1998bacbd8e242a78fc25 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/gcs/gcs_server @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e4db4571e253b2b338331744912d1f938fe095d34e0a401935cd8973e9c388c2 +size 28210824 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/raylet/raylet b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/raylet/raylet new file mode 100644 index 0000000000000000000000000000000000000000..a9802f1b755bbc05ba01a16e557175573c95b68c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/core/src/ray/raylet/raylet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d1992e4171b4015a1f6ea088008e33ad5a288300f5e72386b88728499038b1f8 +size 31021248 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc9970899cf41e4755e4d6c424b768d2357d78f2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/__init__.py @@ -0,0 +1,46 @@ +from ray.dag.dag_node import DAGNode +from ray.dag.function_node import FunctionNode +from ray.dag.class_node import ( + ClassNode, + ClassMethodNode, +) +from ray.dag.collective_node import CollectiveOutputNode +from ray.dag.input_node import ( + InputNode, + InputAttributeNode, + DAGInputData, +) +from ray.dag.output_node import MultiOutputNode +from ray.dag.dag_operation_future import DAGOperationFuture, GPUFuture +from ray.dag.constants import ( + PARENT_CLASS_NODE_KEY, + PREV_CLASS_METHOD_CALL_KEY, + BIND_INDEX_KEY, + IS_CLASS_METHOD_OUTPUT_KEY, + COLLECTIVE_OPERATION_KEY, + DAGNODE_TYPE_KEY, +) +from ray.dag.vis_utils import plot +from ray.dag.context import DAGContext + +__all__ = [ + "ClassNode", + "ClassMethodNode", + "CollectiveOutputNode", + "DAGNode", + "DAGOperationFuture", + "FunctionNode", + "GPUFuture", + "InputNode", + "InputAttributeNode", + "DAGInputData", + "PARENT_CLASS_NODE_KEY", + "PREV_CLASS_METHOD_CALL_KEY", + "BIND_INDEX_KEY", + "IS_CLASS_METHOD_OUTPUT_KEY", + "COLLECTIVE_OPERATION_KEY", + "DAGNODE_TYPE_KEY", + "plot", + "MultiOutputNode", + "DAGContext", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/__pycache__/compiled_dag_node.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/__pycache__/compiled_dag_node.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a70cbc653f5850e5a6bf8f847cc013253c8d3f2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/__pycache__/compiled_dag_node.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b901b089007e32c3df00169cc13a4afc02b1e524c1531b42761ead04300479e +size 127382 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/base.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/base.py new file mode 100644 index 0000000000000000000000000000000000000000..4153866cdeeba83e32becb86ab42ab2544646028 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/base.py @@ -0,0 +1,8 @@ +"""This module defines the base class for object scanning and gets rid of +reference cycles.""" +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class DAGNodeBase: + """Common base class for a node in a Ray task graph.""" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/class_node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/class_node.py new file mode 100644 index 0000000000000000000000000000000000000000..63d29086d34a0953a22b30aaf8cfd742c71ebe56 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/class_node.py @@ -0,0 +1,321 @@ +from weakref import ReferenceType + +import ray +from ray.dag.dag_node import DAGNode +from ray.dag.input_node import InputNode +from ray.dag.format_utils import get_dag_node_str +from ray.dag.constants import ( + PARENT_CLASS_NODE_KEY, + PREV_CLASS_METHOD_CALL_KEY, + BIND_INDEX_KEY, + IS_CLASS_METHOD_OUTPUT_KEY, +) +from ray.util.annotations import DeveloperAPI + +from typing import Any, Dict, List, Union, Tuple, Optional + + +@DeveloperAPI +class ClassNode(DAGNode): + """Represents an actor creation in a Ray task DAG.""" + + def __init__( + self, + cls, + cls_args, + cls_kwargs, + cls_options, + other_args_to_resolve=None, + ): + self._body = cls + self._last_call: Optional["ClassMethodNode"] = None + super().__init__( + cls_args, + cls_kwargs, + cls_options, + other_args_to_resolve=other_args_to_resolve, + ) + + if self._contains_input_node(): + raise ValueError( + "InputNode handles user dynamic input the DAG, and " + "cannot be used as args, kwargs, or other_args_to_resolve " + "in ClassNode constructor because it is not available at " + "class construction or binding time." + ) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return ClassNode( + self._body, + new_args, + new_kwargs, + new_options, + other_args_to_resolve=new_other_args_to_resolve, + ) + + def _execute_impl(self, *args, **kwargs): + """Executor of ClassNode by ray.remote() + + Args and kwargs are to match base class signature, but not in the + implementation. All args and kwargs should be resolved and replaced + with value in bound_args and bound_kwargs via bottom-up recursion when + current node is executed. + """ + return ( + ray.remote(self._body) + .options(**self._bound_options) + .remote(*self._bound_args, **self._bound_kwargs) + ) + + def _contains_input_node(self) -> bool: + """Check if InputNode is used in children DAGNodes with current node + as the root. + """ + children_dag_nodes = self._get_all_child_nodes() + for child in children_dag_nodes: + if isinstance(child, InputNode): + return True + return False + + def __getattr__(self, method_name: str): + # User trying to call .bind() without a bind class method + if method_name == "bind" and "bind" not in dir(self._body): + raise AttributeError(f".bind() cannot be used again on {type(self)} ") + # Raise an error if the method is invalid. + getattr(self._body, method_name) + call_node = _UnboundClassMethodNode(self, method_name, {}) + return call_node + + def __str__(self) -> str: + return get_dag_node_str(self, str(self._body)) + + +class _UnboundClassMethodNode(object): + def __init__(self, actor: ClassNode, method_name: str, options: dict): + # TODO(sang): Theoretically, We should use weakref cuz it is + # a circular dependency but when I used weakref, it fails + # because we cannot serialize the weakref. + self._actor = actor + self._method_name = method_name + self._options = options + + def bind(self, *args, **kwargs): + other_args_to_resolve = { + PARENT_CLASS_NODE_KEY: self._actor, + PREV_CLASS_METHOD_CALL_KEY: self._actor._last_call, + } + + node = ClassMethodNode( + self._method_name, + args, + kwargs, + self._options, + other_args_to_resolve=other_args_to_resolve, + ) + self._actor._last_call = node + return node + + def __getattr__(self, attr: str): + if attr == "remote": + raise AttributeError( + ".remote() cannot be used on ClassMethodNodes. Use .bind() instead " + "to express an symbolic actor call." + ) + else: + return self.__getattribute__(attr) + + def options(self, **options): + self._options = options + return self + + +class _ClassMethodOutput: + """Represents a class method output in a Ray function DAG.""" + + def __init__(self, class_method_call: "ClassMethodNode", output_idx: int): + # The upstream class method call that returns multiple values. + self._class_method_call = class_method_call + # The output index of the return value from the upstream class method call. + self._output_idx = output_idx + + @property + def class_method_call(self) -> "ClassMethodNode": + return self._class_method_call + + @property + def output_idx(self) -> int: + return self._output_idx + + +@DeveloperAPI +class ClassMethodNode(DAGNode): + """Represents an actor method invocation in a Ray function DAG.""" + + def __init__( + self, + method_name: str, + method_args: Tuple[Any], + method_kwargs: Dict[str, Any], + method_options: Dict[str, Any], + other_args_to_resolve: Dict[str, Any], + ): + self._bound_args = method_args or [] + self._bound_kwargs = method_kwargs or {} + self._bound_options = method_options or {} + self._method_name: str = method_name + # Parse other_args_to_resolve and assign to variables + self._parent_class_node: Union[ + ClassNode, ReferenceType["ray._private.actor.ActorHandle"] + ] = other_args_to_resolve.get(PARENT_CLASS_NODE_KEY) + # Used to track lineage of ClassMethodCall to preserve deterministic + # submission and execution order. + self._prev_class_method_call: Optional[ + ClassMethodNode + ] = other_args_to_resolve.get(PREV_CLASS_METHOD_CALL_KEY, None) + # The index/order when bind() is called on this class method + self._bind_index: Optional[int] = other_args_to_resolve.get( + BIND_INDEX_KEY, None + ) + # Represent if the ClassMethodNode is a class method output. If True, + # the node is a placeholder for a return value from the ClassMethodNode + # that returns multiple values. If False, the node is a class method call. + self._is_class_method_output: bool = other_args_to_resolve.get( + IS_CLASS_METHOD_OUTPUT_KEY, False + ) + # Represents the return value from the upstream ClassMethodNode that + # returns multiple values. If the node is a class method call, this is None. + self._class_method_output: Optional[_ClassMethodOutput] = None + if self._is_class_method_output: + # Set the upstream ClassMethodNode and the output index of the return + # value from `method_args`. + self._class_method_output = _ClassMethodOutput( + method_args[0], method_args[1] + ) + + # The actor creation task dependency is encoded as the first argument, + # and the ordering dependency as the second, which ensures they are + # executed prior to this node. + super().__init__( + method_args, + method_kwargs, + method_options, + other_args_to_resolve=other_args_to_resolve, + ) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return ClassMethodNode( + self._method_name, + new_args, + new_kwargs, + new_options, + other_args_to_resolve=new_other_args_to_resolve, + ) + + def _execute_impl(self, *args, **kwargs): + """Executor of ClassMethodNode by ray.remote() + + Args and kwargs are to match base class signature, but not in the + implementation. All args and kwargs should be resolved and replaced + with value in bound_args and bound_kwargs via bottom-up recursion when + current node is executed. + """ + if self.is_class_method_call: + method_body = getattr(self._parent_class_node, self._method_name) + # Execute with bound args. + return method_body.options(**self._bound_options).remote( + *self._bound_args, + **self._bound_kwargs, + ) + else: + assert self._class_method_output is not None + return self._bound_args[0][self._class_method_output.output_idx] + + def __str__(self) -> str: + return get_dag_node_str(self, f"{self._method_name}()") + + def __repr__(self) -> str: + return self.__str__() + + def get_method_name(self) -> str: + return self._method_name + + def _get_bind_index(self) -> int: + return self._bind_index + + def _get_remote_method(self, method_name): + method_body = getattr(self._parent_class_node, method_name) + return method_body + + def _get_actor_handle(self) -> Optional["ray.actor.ActorHandle"]: + if not isinstance(self._parent_class_node, ray.actor.ActorHandle): + return None + return self._parent_class_node + + @property + def num_returns(self) -> int: + """ + Return the number of return values from the class method call. If the + node is a class method output, return the number of return values from + the upstream class method call. + """ + + if self.is_class_method_call: + num_returns = self._bound_options.get("num_returns", None) + if num_returns is None: + method = self._get_remote_method(self._method_name) + num_returns = method.__getstate__()["num_returns"] + return num_returns + else: + assert self._class_method_output is not None + return self._class_method_output.class_method_call.num_returns + + @property + def is_class_method_call(self) -> bool: + """ + Return True if the node is a class method call, False if the node is a + class method output. + """ + return not self._is_class_method_output + + @property + def is_class_method_output(self) -> bool: + """ + Return True if the node is a class method output, False if the node is a + class method call. + """ + return self._is_class_method_output + + @property + def class_method_call(self) -> Optional["ClassMethodNode"]: + """ + Return the upstream class method call that returns multiple values. If + the node is a class method output, return None. + """ + + if self._class_method_output is None: + return None + return self._class_method_output.class_method_call + + @property + def output_idx(self) -> Optional[int]: + """ + Return the output index of the return value from the upstream class + method call that returns multiple values. If the node is a class method + call, return None. + """ + + if self._class_method_output is None: + return None + return self._class_method_output.output_idx diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/collective_node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/collective_node.py new file mode 100644 index 0000000000000000000000000000000000000000..ad55b8c1a08cb681ab6f2d4ab1afab2802df1cf4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/collective_node.py @@ -0,0 +1,307 @@ +from typing import Any, Dict, List, Union, Tuple, Optional, TYPE_CHECKING + +if TYPE_CHECKING: + import torch + +import ray +from ray.dag import ( + DAGNode, + ClassMethodNode, +) +from ray.dag.constants import COLLECTIVE_OPERATION_KEY, IS_CLASS_METHOD_OUTPUT_KEY +from ray.experimental.channel import ChannelContext +from ray.experimental.channel.torch_tensor_type import Communicator, TorchTensorType +from ray.experimental.util.types import ( + _CollectiveOp, + AllGatherOp, + AllReduceOp, + ReduceScatterOp, +) +from ray.util.annotations import DeveloperAPI + + +class _CollectiveOperation: + """ + Represent metadata for a collective communicator collective operation. + + Args: + inputs: A list of lists of DAGNode. Each nested list inside + of inputs should contain exactly one object per actor. + If multiple nested lists are provided, then the order of + actors should be the same for each nested list. + op: The collective operation to perform. + transport: The transport to use for the collective operation. + + Requirements: + 1. Input nodes are unique. + 2. Actor handles are unique. + 3. Actor handles match the custom communicator group if specified. + """ + + def __init__( + self, + inputs: List[List[DAGNode]], + op: _CollectiveOp, + transport: Optional[Union[str, Communicator]] = None, + ): + self._actor_handles: List["ray.actor.ActorHandle"] = [] + for i, input_nodes in enumerate(inputs): + # Check non-empty input list + if len(input_nodes) == 0: + nested_list_error_msg = f" at index {i}" if len(inputs) > 1 else "" + raise ValueError( + f"Expected non-empty input list{nested_list_error_msg}." + ) + + # Check input nodes are DAGNode + if not all(isinstance(node, DAGNode) for node in input_nodes): + nested_list_error_msg = ( + f" at list at index {i}" if len(inputs) > 1 else "" + ) + raise ValueError( + f"Expected all input nodes to be DAGNode{nested_list_error_msg}, " + f"but got {input_nodes}." + ) + + # Check unique input nodes + if len(set(input_nodes)) != len(input_nodes): + duplicates = [ + input_node + for input_node in input_nodes + if input_nodes.count(input_node) > 1 + ] + nested_list_error_msg = ( + f" at list at index {i}" if len(inputs) > 1 else "" + ) + raise ValueError( + f"Expected unique input nodes{nested_list_error_msg}, but found duplicates: " + f"{duplicates}" + ) + + current_actor_handles = [] + for input_node in input_nodes: + actor_handle = input_node._get_actor_handle() + if actor_handle is None: + nested_list_error_msg = ( + f" at list at index {i}" if len(inputs) > 1 else "" + ) + raise ValueError( + f"Expected an actor handle from the input node{nested_list_error_msg}" + ) + current_actor_handles.append(actor_handle) + + # Check unique actor handles + if len(set(current_actor_handles)) != len(current_actor_handles): + invalid_input_nodes = [ + input_node + for input_node in input_nodes + if current_actor_handles.count(input_node._get_actor_handle()) > 1 + ] + nested_list_error_msg = ( + f" at list at index {i}" if len(inputs) > 1 else "" + ) + raise ValueError( + f"Expected unique actor handles{nested_list_error_msg}, " + "but found duplicate actor handles from input nodes: " + f"{invalid_input_nodes}" + ) + + if i == 0: + first_actor_handles = current_actor_handles + + # Check all lists of DAGNode have the same number of nodes + if len(inputs[0]) != len(inputs[i]): + raise ValueError( + f"Expected all input lists to have the same number of nodes. " + f"List at index 0 has length {len(inputs[0])}, but list at " + f"index {i} has length {len(inputs[i])}." + ) + + # Check all lists of DAGNode have same set of actor handles + if set(first_actor_handles) != set(current_actor_handles): + raise ValueError( + f"Expected all input lists to have the same set of actor handles. " + f"List at index 0 has actors {set(first_actor_handles)}, but list at " + f"index {i} has actors {set(current_actor_handles)}." + ) + + # Check all lists of DAGNode have same order of actor handles + for j, (first, current) in enumerate( + zip(first_actor_handles, current_actor_handles) + ): + if first != current: + raise ValueError( + f"Expected all input lists to have the same order of actor handles. " + f"List at index 0 has actor {first} at position {j}, but list at " + f"index {i} has actor {current} at position {j}." + ) + self._actor_handles = current_actor_handles + + self._op = op + if transport is None: + transport = TorchTensorType.ACCELERATOR + self._type_hint = TorchTensorType(transport=transport, _direct_return=True) + if isinstance(transport, Communicator): + if set(transport.get_actor_handles()) != set(self._actor_handles): + raise ValueError( + "Expected actor handles to match the custom communicator group" + ) + + def __str__(self) -> str: + return ( + f"CollectiveOperation(" + f"_actor_handles={self._actor_handles}, " + f"_op={self._op}, " + f"_type_hint={self._type_hint})" + ) + + @property + def actor_handles(self) -> List["ray.actor.ActorHandle"]: + return self._actor_handles + + @property + def type_hint(self) -> TorchTensorType: + return self._type_hint + + def get_communicator(self) -> Communicator: + if self._type_hint.communicator_id is not None: + ctx = ChannelContext.get_current() + communicator = ctx.communicators[self._type_hint.communicator_id] + elif self._type_hint.get_custom_communicator() is not None: + communicator = self._type_hint.get_custom_communicator() + else: + raise ValueError("Expected a communicator group") + return communicator + + def execute( + self, *send_buf: "torch.Tensor" + ) -> Union["torch.Tensor", Tuple["torch.Tensor", ...]]: + """ + Call the collective operation on the input tensor(s). Output tensor(s) are + allocated and returned. + + Args: + *send_buf: A variable number of torch tensors to send to the collective + operation. The tensors have the same order as the input nodes. + + Returns: + A torch tensor or a tuple of torch tensors containing the results of the + collective operation. The output tensors have the same length and order + as the input node list of the actor of this operation. + """ + import torch + + if not all(isinstance(t, torch.Tensor) for t in send_buf): + raise ValueError("Expected a torch tensor for each input node") + + communicator = self.get_communicator() + if isinstance(self._op, AllGatherOp): + assert len(send_buf) == 1 + t = send_buf[0] + world_size = len(self._actor_handles) + recv_buf = torch.empty( + (t.shape[0] * world_size, *t.shape[1:]), + dtype=t.dtype, + device=t.device, + ) + communicator.allgather(t, recv_buf) + elif isinstance(self._op, AllReduceOp): + if len(send_buf) == 1: + t = send_buf[0] + recv_buf = torch.empty_like(t) + communicator.allreduce(t, recv_buf, self._op.reduceOp) + else: + if not all(t.dtype == send_buf[0].dtype for t in send_buf): + raise ValueError( + "Expected all input tensors to have the same dtype, " + f"but got {[t.dtype for t in send_buf]}" + ) + + def unflatten_from(flat_buf, bufs): + views = [] + offset = 0 + for t in bufs: + numel = t.numel() + t = flat_buf[offset : offset + numel].view(t.shape) + views.append(t) + offset += numel + return tuple(views) + + flat_buf = torch.nn.utils.parameters_to_vector(send_buf) + communicator.allreduce(flat_buf, flat_buf, self._op.reduceOp) + recv_buf = unflatten_from(flat_buf, send_buf) + elif isinstance(self._op, ReduceScatterOp): + assert len(send_buf) == 1 + t = send_buf[0] + world_size = len(self._actor_handles) + if t.shape[0] % world_size != 0: + raise ValueError( + "Expected the first dimension of the input tensor to be divisible " + f"by the world size {world_size}" + ) + recv_buf = torch.empty( + (t.shape[0] // world_size, *t.shape[1:]), + dtype=t.dtype, + device=t.device, + ) + communicator.reducescatter(t, recv_buf, self._op.reduceOp) + return recv_buf + + +@DeveloperAPI +class CollectiveOutputNode(ClassMethodNode): + """Represent an output node from a communicator collective operation in a Ray DAG.""" + + def __init__( + self, + method_name: str, + method_args: Tuple[ + DAGNode, + ], + method_kwargs: Dict[str, Any], + method_options: Dict[str, Any], + other_args_to_resolve: Dict[str, Any], + ): + # Parse the input node(s). + self._inputs = method_args + # Parse the collective operation. + self._collective_op: _CollectiveOperation = other_args_to_resolve.get( + COLLECTIVE_OPERATION_KEY, None + ) + self._is_class_method_output: bool = other_args_to_resolve.get( + IS_CLASS_METHOD_OUTPUT_KEY, False + ) + if self._collective_op is None and not self._is_class_method_output: + raise ValueError("Expected a collective operation") + + super().__init__( + method_name, + method_args, + method_kwargs, + method_options, + other_args_to_resolve, + ) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return CollectiveOutputNode( + self._method_name, + new_args, + new_kwargs, + new_options, + other_args_to_resolve=new_other_args_to_resolve, + ) + + def _execute_impl(self, *args, **kwargs): + raise NotImplementedError( + "CollectiveOutputNode is only supported with dag.experimental_compile()" + ) + + @property + def collective_op(self) -> _CollectiveOperation: + return self._collective_op diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/compiled_dag_node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/compiled_dag_node.py new file mode 100644 index 0000000000000000000000000000000000000000..ce59c2c244da41669edfc800fe9e1073920c2612 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/compiled_dag_node.py @@ -0,0 +1,3316 @@ +import weakref +import asyncio +from collections import defaultdict +from contextlib import nullcontext +from dataclasses import dataclass, asdict +from typing import ( + Any, + Dict, + List, + Tuple, + Union, + Optional, + Set, +) +import logging +import threading +import time +import uuid +import traceback + +from ray.experimental.channel.auto_transport_type import ( + AutoTransportType, + TypeHintResolver, +) +import ray.exceptions +from ray.dag.dag_operation_future import GPUFuture, DAGOperationFuture, ResolvedFuture +from ray.experimental.channel.cached_channel import CachedChannel +from ray.experimental.channel.communicator import Communicator +from ray.dag.constants import ( + RAY_CGRAPH_ENABLE_NVTX_PROFILING, + RAY_CGRAPH_ENABLE_TORCH_PROFILING, + RAY_CGRAPH_VISUALIZE_SCHEDULE, +) +import ray +from ray.exceptions import ( + RayCgraphCapacityExceeded, + RayTaskError, + RayChannelError, + RayChannelTimeoutError, +) +from ray.experimental.compiled_dag_ref import ( + CompiledDAGRef, + CompiledDAGFuture, + _process_return_vals, +) +from ray.experimental.channel import ( + ChannelContext, + ChannelInterface, + ChannelOutputType, + ReaderInterface, + SynchronousReader, + WriterInterface, + SynchronousWriter, + AwaitableBackgroundReader, + AwaitableBackgroundWriter, + CompiledDAGArgs, + CompositeChannel, + IntraProcessChannel, +) +from ray.util.annotations import DeveloperAPI + +from ray.experimental.channel.shared_memory_channel import ( + SharedMemoryType, +) +from ray.experimental.channel.torch_tensor_type import TorchTensorType + +from ray.experimental.channel.torch_tensor_accelerator_channel import ( + _init_communicator, + _destroy_communicator, +) + +from ray.dag.dag_node_operation import ( + _DAGNodeOperation, + _DAGNodeOperationType, + _DAGOperationGraphNode, + _build_dag_node_operation_graph, + _extract_execution_schedule, + _generate_actor_to_execution_schedule, + _generate_overlapped_execution_schedule, + _visualize_execution_schedule, +) + +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +from ray.experimental.channel.accelerator_context import AcceleratorContext + +logger = logging.getLogger(__name__) + +# Keep tracking of every compiled dag created during the lifetime of +# this process. It tracks them as weakref meaning when the compiled dag +# is GC'ed, it is automatically removed from here. It is used to teardown +# compiled dags at interpreter shutdown time. +_compiled_dags = weakref.WeakValueDictionary() + + +# Relying on __del__ doesn't work well upon shutdown because +# the destructor order is not guaranteed. We call this function +# upon `ray.worker.shutdown` which is registered to atexit handler +# so that teardown is properly called before objects are destructed. +def _shutdown_all_compiled_dags(): + global _compiled_dags + for _, compiled_dag in _compiled_dags.items(): + # Kill DAG actors to avoid hanging during shutdown if the actor tasks + # cannot be cancelled. + compiled_dag.teardown(kill_actors=True) + _compiled_dags = weakref.WeakValueDictionary() + + +def _check_unused_dag_input_attributes( + output_node: "ray.dag.MultiOutputNode", input_attributes: Set[str] +) -> Set[str]: + """ + Helper function to check that all input attributes are used in the DAG. + For example, if the user creates an input attribute by calling + InputNode()["x"], we ensure that there is a path from the + InputAttributeNode corresponding to "x" to the DAG's output. If an + input attribute is not used, throw an error. + + Args: + output_node: The starting node for the traversal. + input_attributes: A set of attributes accessed by the InputNode. + """ + from ray.dag import InputAttributeNode + + used_attributes = set() + visited_nodes = set() + stack: List["ray.dag.DAGNode"] = [output_node] + + while stack: + current_node = stack.pop() + if current_node in visited_nodes: + continue + visited_nodes.add(current_node) + + if isinstance(current_node, InputAttributeNode): + used_attributes.add(current_node.key) + + stack.extend(current_node._upstream_nodes) + + unused_attributes = input_attributes - used_attributes + if unused_attributes: + unused_attributes_str = ", ".join(str(key) for key in unused_attributes) + input_attributes_str = ", ".join(str(key) for key in input_attributes) + unused_phrase = "is unused" if len(unused_attributes) == 1 else "are unused" + + raise ValueError( + "Compiled Graph expects input to be accessed " + f"using all of attributes {input_attributes_str}, " + f"but {unused_attributes_str} {unused_phrase}. " + "Ensure all input attributes are used and contribute " + "to the computation of the Compiled Graph output." + ) + + +@DeveloperAPI +def do_allocate_channel( + self, + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]], + typ: ChannelOutputType, + driver_actor_id: Optional[str] = None, +) -> ChannelInterface: + """Generic actor method to allocate an output channel. + + Args: + reader_and_node_list: A list of tuples, where each tuple contains a reader + actor handle and the node ID where the actor is located. + typ: The output type hint for the channel. + driver_actor_id: If this channel is read by a driver and that driver is an + actual actor, this will be the actor ID of that driver actor. + + Returns: + The allocated channel. + """ + # None means it is called from a driver. + writer: Optional["ray.actor.ActorHandle"] = None + try: + writer = ray.get_runtime_context().current_actor + except RuntimeError: + # This is the driver so there is no current actor handle. + pass + + output_channel = typ.create_channel( + writer, + reader_and_node_list, + driver_actor_id, + ) + return output_channel + + +@DeveloperAPI +def do_exec_tasks( + self, + tasks: List["ExecutableTask"], + schedule: List[_DAGNodeOperation], + overlap_gpu_communication: bool = False, +) -> None: + """A generic actor method to begin executing the operations belonging to an + actor. This runs an infinite loop to execute each _DAGNodeOperation in the + order specified by the schedule. It exits only if the actor dies or an + exception is thrown. + + Args: + tasks: the executable tasks corresponding to the actor methods. + schedule: A list of _DAGNodeOperation that should be executed in order. + overlap_gpu_communication: Whether to overlap GPU communication with + computation during DAG execution to improve performance. + """ + try: + for task in tasks: + task.prepare(overlap_gpu_communication=overlap_gpu_communication) + + if RAY_CGRAPH_ENABLE_NVTX_PROFILING: + assert ( + not RAY_CGRAPH_ENABLE_TORCH_PROFILING + ), "NVTX and torch profiling cannot be enabled at the same time." + try: + import nvtx + except ImportError: + raise ImportError( + "Please install nvtx to enable nsight profiling. " + "You can install it by running `pip install nvtx`." + ) + nvtx_profile = nvtx.Profile() + nvtx_profile.enable() + + if RAY_CGRAPH_ENABLE_TORCH_PROFILING: + assert ( + not RAY_CGRAPH_ENABLE_NVTX_PROFILING + ), "NVTX and torch profiling cannot be enabled at the same time." + + import torch + + torch_profile = torch.profiler.profile( + activities=[ + torch.profiler.ProfilerActivity.CPU, + torch.profiler.ProfilerActivity.CUDA, + ], + with_stack=True, + on_trace_ready=torch.profiler.tensorboard_trace_handler( + "compiled_graph_torch_profiles" + ), + ) + torch_profile.start() + logger.info("Torch profiling started") + + done = False + while True: + if done: + break + for operation in schedule: + done = tasks[operation.exec_task_idx].exec_operation( + self, operation.type, overlap_gpu_communication + ) + if done: + break + + if RAY_CGRAPH_ENABLE_NVTX_PROFILING: + nvtx_profile.disable() + + if RAY_CGRAPH_ENABLE_TORCH_PROFILING: + torch_profile.stop() + logger.info("Torch profiling stopped") + except Exception: + logging.exception("Compiled DAG task exited with exception") + raise + + +@DeveloperAPI +def do_profile_tasks( + self, + tasks: List["ExecutableTask"], + schedule: List[_DAGNodeOperation], + overlap_gpu_communication: bool = False, +) -> None: + """A generic actor method similar to `do_exec_tasks`, but with profiling enabled. + + Args: + tasks: the executable tasks corresponding to the actor methods. + schedule: A list of _DAGNodeOperation that should be executed in order. + overlap_gpu_communication: Whether to overlap GPU communication with + computation during DAG execution to improve performance. + """ + try: + for task in tasks: + task.prepare(overlap_gpu_communication=overlap_gpu_communication) + + if not hasattr(self, "__ray_cgraph_events"): + self.__ray_cgraph_events = [] + + done = False + while True: + if done: + break + for operation in schedule: + start_t = time.perf_counter() + task = tasks[operation.exec_task_idx] + done = task.exec_operation( + self, operation.type, overlap_gpu_communication + ) + end_t = time.perf_counter() + + self.__ray_cgraph_events.append( + _ExecutableTaskRecord( + actor_classname=self.__class__.__name__, + actor_name=ray.get_runtime_context().get_actor_name(), + actor_id=ray.get_runtime_context().get_actor_id(), + method_name=task.method_name, + bind_index=task.bind_index, + operation=operation.type.value, + start_t=start_t, + end_t=end_t, + ) + ) + + if done: + break + except Exception: + logging.exception("Compiled DAG task exited with exception") + raise + + +@DeveloperAPI +def do_cancel_executable_tasks(self, tasks: List["ExecutableTask"]) -> None: + # CUDA events should be destroyed before other CUDA resources. + for task in tasks: + task.destroy_cuda_event() + for task in tasks: + task.cancel() + + +def _wrap_exception(exc): + backtrace = ray._private.utils.format_error_message( + "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)), + task_exception=True, + ) + wrapped = RayTaskError( + function_name="do_exec_tasks", + traceback_str=backtrace, + cause=exc, + ) + return wrapped + + +def _get_comm_group_id(type_hint: ChannelOutputType) -> Optional[str]: + """ + Get the communicator group ID from the type hint. If the type hint does not + require communicator, return None. + + Args: + type_hint: The type hint of the channel. + + Returns: + The communicator group ID if the type hint requires communicator, + otherwise None. + """ + if type_hint.requires_accelerator(): + assert isinstance(type_hint, TorchTensorType) + return type_hint.communicator_id + return None + + +def _device_context_manager(): + """ + Return a context manager for executing communication operations + (i.e., READ and WRITE). For accelerator operations, the context manager + uses the proper cuda device from channel context, otherwise, + nullcontext will be returned. + """ + if not ChannelContext.get_current().torch_available: + return nullcontext() + + import torch + from ray.experimental.channel.accelerator_context import AcceleratorContext + + device = ChannelContext.get_current().torch_device + + if device.type == "cuda" and not torch.cuda.is_available(): + # In the case of mocked NCCL, we may get a device with type "cuda" + # but CUDA is not available. We return nullcontext() in that case, + # otherwise torch raises a runtime error if the cuda device context + # manager is used. + # TODO(rui): consider better mocking NCCL to support device context. + return nullcontext() + + return AcceleratorContext.get().get_device_context(device) + + +@DeveloperAPI +class CompiledTask: + """Wraps the normal Ray DAGNode with some metadata.""" + + def __init__(self, idx: int, dag_node: "ray.dag.DAGNode"): + """ + Args: + idx: A unique index into the original DAG. + dag_node: The original DAG node created by the user. + """ + self.idx = idx + self.dag_node = dag_node + + # Dict from task index to actor handle for immediate downstream tasks. + self.downstream_task_idxs: Dict[int, "ray.actor.ActorHandle"] = {} + # Case 1: The task represents a ClassMethodNode. + # + # Multiple return values are written to separate `output_channels`. + # `output_idxs` represents the tuple index of the output value for + # multiple returns in a tuple. If an output index is None, it means + # the complete return value is written to the output channel. + # Otherwise, the return value is a tuple and the index is used + # to extract the value to be written to the output channel. + # + # Case 2: The task represents an InputNode. + # + # `output_idxs` can be an integer or a string to retrieve the + # corresponding value from `args` or `kwargs` in the DAG's input. + self.output_channels: List[ChannelInterface] = [] + self.output_idxs: List[Optional[Union[int, str]]] = [] + # The DAGNodes that are arguments to this task. + # This is used for lazy resolution of the arguments' type hints. + self.arg_nodes: List["ray.dag.DAGNode"] = [] + # idxs of possible ClassMethodOutputNodes if they exist, used for visualization + self.output_node_idxs: List[int] = [] + + @property + def args(self) -> Tuple[Any]: + return self.dag_node.get_args() + + @property + def kwargs(self) -> Dict[str, Any]: + return self.dag_node.get_kwargs() + + @property + def num_readers(self) -> int: + return len(self.downstream_task_idxs) + + @property + def arg_type_hints(self) -> List["ChannelOutputType"]: + return [arg_node.type_hint for arg_node in self.arg_nodes] + + def __str__(self) -> str: + return f""" + Node: {self.dag_node} + Arguments: {self.args} + Output: {self.output_channels} + """ + + +class _ExecutableTaskInput: + """Represents an input to an ExecutableTask. + + Args: + input_variant: either an unresolved input (when type is ChannelInterface) + , or a resolved input value (when type is Any) + channel_idx: if input_variant is an unresolved input, this is the index + into the input channels list. + """ + + def __init__( + self, + input_variant: Union[ChannelInterface, Any], + channel_idx: Optional[int], + ): + self.input_variant = input_variant + self.channel_idx = channel_idx + + def resolve(self, channel_results: Any) -> Any: + """ + Resolve the input value from the channel results. + + Args: + channel_results: The results from reading the input channels. + """ + + if isinstance(self.input_variant, ChannelInterface): + value = channel_results[self.channel_idx] + else: + value = self.input_variant + return value + + +@DeveloperAPI +class ExecutableTask: + """A task that can be executed in a compiled DAG, and it + corresponds to an actor method. + """ + + def __init__( + self, + task: "CompiledTask", + resolved_args: List[Any], + resolved_kwargs: Dict[str, Any], + ): + """ + Args: + task: The CompiledTask that this ExecutableTask corresponds to. + resolved_args: The arguments to the method. Arguments that are + not Channels will get passed through to the actor method. + If the argument is a channel, it will be replaced by the + value read from the channel before the method executes. + resolved_kwargs: The keyword arguments to the method. Currently, we + do not support binding kwargs to other DAG nodes, so the values + of the dictionary cannot be Channels. + """ + from ray.dag import CollectiveOutputNode + + self.method_name = task.dag_node.get_method_name() + self.bind_index = task.dag_node._get_bind_index() + self.output_channels = task.output_channels + self.output_idxs = task.output_idxs + self.input_type_hints: List[ChannelOutputType] = task.arg_type_hints + self.output_type_hint: ChannelOutputType = task.dag_node.type_hint + + # The accelerator collective operation. + self.collective_op: Optional["ray.dag.CollectiveOperation"] = None + if isinstance(task.dag_node, CollectiveOutputNode): + self.collective_op = task.dag_node.collective_op + + self.input_channels: List[ChannelInterface] = [] + self.task_inputs: List[_ExecutableTaskInput] = [] + self.resolved_kwargs: Dict[str, Any] = resolved_kwargs + # A unique index which can be used to index into `idx_to_task` to get + # the corresponding task. + self.task_idx = task.idx + + # Reverse map for input_channels: maps an input channel to + # its index in input_channels. + input_channel_to_idx: dict[ChannelInterface, int] = {} + + for arg in resolved_args: + if isinstance(arg, ChannelInterface): + channel = arg + if channel in input_channel_to_idx: + # The same channel was added before, so reuse the index. + channel_idx = input_channel_to_idx[channel] + else: + # Add a new channel to the list of input channels. + self.input_channels.append(channel) + channel_idx = len(self.input_channels) - 1 + input_channel_to_idx[channel] = channel_idx + + task_input = _ExecutableTaskInput(arg, channel_idx) + else: + task_input = _ExecutableTaskInput(arg, None) + self.task_inputs.append(task_input) + + # Currently DAGs do not support binding kwargs to other DAG nodes. + for val in self.resolved_kwargs.values(): + assert not isinstance(val, ChannelInterface) + + # Input reader to read input data from upstream DAG nodes. + self.input_reader: ReaderInterface = SynchronousReader(self.input_channels) + # Output writer to write output data to downstream DAG nodes. + self.output_writer: WriterInterface = SynchronousWriter( + self.output_channels, self.output_idxs + ) + # The intermediate future for a READ or COMPUTE operation, + # and `wait()` must be called to get the actual result of the operation. + # The result of a READ operation will be used by a COMPUTE operation, + # and the result of a COMPUTE operation will be used by a WRITE operation. + self._intermediate_future: Optional[DAGOperationFuture] = None + + def cancel(self): + """ + Close all the input channels and the output channel. The exact behavior + depends on the type of channel. Typically, it will release the resources + used by the channels. + """ + self.input_reader.close() + self.output_writer.close() + + def destroy_cuda_event(self): + """ + If this executable task has created a GPU future that is not yet waited on, + that future is in the channel context cache. Remove the future from the cache + and destroy its CUDA event. + """ + GPUFuture.remove_gpu_future(self.task_idx) + + def prepare(self, overlap_gpu_communication: bool = False): + """ + Prepare the task for execution. The `exec_operation` function can only + be called after `prepare` has been called. + + Args: + overlap_gpu_communication: Whether to overlap GPU communication with + computation during DAG execution to improve performance + """ + for typ_hint in self.input_type_hints: + typ_hint.register_custom_serializer() + self.output_type_hint.register_custom_serializer() + self.input_reader.start() + self.output_writer.start() + + # Stream context type are different between different accelerators. + # Type hint is not applicable here. + self._send_stream = nullcontext() + self._recv_stream = nullcontext() + if not overlap_gpu_communication: + return + + # Set up send_stream and recv_stream when overlap_gpu_communication + # is configured + if self.output_type_hint.requires_accelerator(): + comm_group_id = _get_comm_group_id(self.output_type_hint) + comm_group = ChannelContext.get_current().communicators.get(comm_group_id) + assert comm_group is not None + self._send_stream = comm_group.send_stream + if self.input_type_hints: + for type_hint in self.input_type_hints: + if type_hint.requires_accelerator(): + comm_group_id = _get_comm_group_id(type_hint) + comm_group = ChannelContext.get_current().communicators.get( + comm_group_id + ) + assert comm_group is not None + if not isinstance(self._recv_stream, nullcontext): + assert self._recv_stream == comm_group.recv_stream, ( + "Currently all torch tensor input channels of a " + "Compiled Graph task should use the same recv cuda stream." + ) + self._recv_stream = comm_group.recv_stream + + def wrap_and_set_intermediate_future( + self, val: Any, wrap_in_gpu_future: bool + ) -> None: + """ + Wrap the value in a `DAGOperationFuture` and store to the intermediate future. + The value corresponds to result of a READ or COMPUTE operation. + + If wrap_in_gpu_future is True, the value will be wrapped in a GPUFuture, + Otherwise, the future will be a ResolvedFuture. + + Args: + val: The value to wrap in a future. + wrap_in_gpu_future: Whether to wrap the value in a GPUFuture. + """ + assert self._intermediate_future is None + + if wrap_in_gpu_future: + future = GPUFuture(val, self.task_idx) + else: + future = ResolvedFuture(val) + self._intermediate_future = future + + def reset_and_wait_intermediate_future(self) -> Any: + """ + Reset the intermediate future and wait for the result. + + The wait does not block the CPU because: + - If the future is a ResolvedFuture, the result is immediately returned. + - If the future is a GPUFuture, the result is only waited by the current + CUDA stream, and the CPU is not blocked. + + Returns: + The result of a READ or COMPUTE operation from the intermediate future. + """ + future = self._intermediate_future + self._intermediate_future = None + return future.wait() + + def _read(self, overlap_gpu_communication: bool) -> bool: + """ + Read input data from upstream DAG nodes and cache the intermediate result. + + Args: + overlap_gpu_communication: Whether to overlap GPU communication with + computation during DAG execution to improve performance. + + Returns: + True if system error occurs and exit the loop; otherwise, False. + """ + assert self._intermediate_future is None + exit = False + try: + input_data = self.input_reader.read() + # When overlap_gpu_communication is enabled, wrap the result in + # a GPUFuture so that this read operation (communication) can + # be overlapped with computation. + self.wrap_and_set_intermediate_future( + input_data, + wrap_in_gpu_future=overlap_gpu_communication, + ) + except RayChannelError: + # Channel closed. Exit the loop. + exit = True + return exit + + def _compute( + self, + overlap_gpu_communication: bool, + class_handle, + ) -> bool: + """ + Retrieve the intermediate result from the READ operation and perform the + computation. Then, cache the new intermediate result. The caller must ensure + that the last operation executed is READ so that the function retrieves the + correct intermediate result. + + Args: + overlap_gpu_communication: Whether to overlap GPU communication with + computation during DAG execution to improve performance. + class_handle: An instance of the class to which the actor belongs. For + example, the type of `class_handle` is if the + actor belongs to the `class Worker` class. + Returns: + True if system error occurs and exit the loop; otherwise, False. + """ + input_data = self.reset_and_wait_intermediate_future() + try: + _process_return_vals(input_data, return_single_output=False) + except Exception as exc: + # Previous task raised an application-level exception. + # Propagate it and skip the actual task. We don't need to wrap the + # exception in a RayTaskError here because it has already been wrapped + # by the previous task. + self.wrap_and_set_intermediate_future( + exc, wrap_in_gpu_future=overlap_gpu_communication + ) + return False + + resolved_inputs = [] + for task_input in self.task_inputs: + resolved_inputs.append(task_input.resolve(input_data)) + + if self.collective_op is not None: + # Run an accelerator collective operation. + method = self.collective_op.execute + else: + # Run an actor method. + method = getattr(class_handle, self.method_name) + try: + output_val = method(*resolved_inputs, **self.resolved_kwargs) + except Exception as exc: + output_val = _wrap_exception(exc) + + # When overlap_gpu_communication is enabled, wrap the result in a GPUFuture + # so that this compute operation can be overlapped with communication. + self.wrap_and_set_intermediate_future( + output_val, wrap_in_gpu_future=overlap_gpu_communication + ) + return False + + def _write(self) -> bool: + """ + Retrieve the intermediate result from the COMPUTE operation and write to its + downstream DAG nodes. The caller must ensure that the last operation executed + is COMPUTE so that the function retrieves the correct intermediate result. + + Returns: + True if system error occurs and exit the loop; otherwise, False. + """ + output_val = self.reset_and_wait_intermediate_future() + exit = False + try: + self.output_writer.write(output_val) + except RayChannelError: + # Channel closed. Exit the loop. + exit = True + return exit + + def exec_operation( + self, + class_handle, + op_type: _DAGNodeOperationType, + overlap_gpu_communication: bool = False, + ) -> bool: + """ + An ExecutableTask corresponds to a DAGNode. It consists of three + operations: READ, COMPUTE, and WRITE, which should be executed in + order to ensure that each operation can read the correct intermediate + result. + Args: + class_handle: The handle of the class to which the actor belongs. + op_type: The type of the operation. Possible types are READ, + COMPUTE, and WRITE. + overlap_gpu_communication: Whether to overlap GPU communication with + computation during DAG execution to improve performance. + Returns: + True if the next operation should not be executed; otherwise, False. + """ + if op_type == _DAGNodeOperationType.READ: + with _device_context_manager(): + with self._recv_stream: + return self._read(overlap_gpu_communication) + elif op_type == _DAGNodeOperationType.COMPUTE: + return self._compute(overlap_gpu_communication, class_handle) + elif op_type == _DAGNodeOperationType.WRITE: + with _device_context_manager(): + with self._send_stream: + return self._write() + + +@dataclass +class _ExecutableTaskRecord: + actor_classname: str + actor_name: str + actor_id: str + method_name: str + bind_index: int + operation: str + start_t: float + end_t: float + + def to_dict(self): + return asdict(self) + + +@DeveloperAPI +class CompiledDAG: + """Experimental class for accelerated execution. + + This class should not be called directly. Instead, create + a ray.dag and call experimental_compile(). + + See REP https://github.com/ray-project/enhancements/pull/48 for more + information. + """ + + @ray.remote(num_cpus=0) + class DAGDriverProxyActor: + """ + To support the driver as a reader, the output writer needs to be able to invoke + remote functions on the driver. This is necessary so that the output writer can + create a reader ref on the driver node, and later potentially create a larger + reader ref on the driver node if the channel backing store needs to be resized. + However, remote functions cannot be invoked on the driver. + + A Compiled Graph creates an actor from this class when the DAG is initialized. + The actor is on the same node as the driver. This class has an empty + implementation, though it serves as a way for the output writer to invoke remote + functions on the driver node. + """ + + pass + + def __init__( + self, + submit_timeout: Optional[float] = None, + buffer_size_bytes: Optional[int] = None, + enable_asyncio: bool = False, + max_inflight_executions: Optional[int] = None, + max_buffered_results: Optional[int] = None, + overlap_gpu_communication: Optional[bool] = None, + default_communicator: Optional[Union[Communicator, str]] = "create", + ): + """ + Args: + submit_timeout: The maximum time in seconds to wait for execute() calls. + None means using default timeout (DAGContext.submit_timeout), + 0 means immediate timeout (immediate success or timeout without + blocking), -1 means infinite timeout (block indefinitely). + buffer_size_bytes: The initial buffer size in bytes for messages + that can be passed between tasks in the DAG. The buffers will + be automatically resized if larger messages are written to the + channel. + enable_asyncio: Whether to enable asyncio. If enabled, caller must + be running in an event loop and must use `execute_async` to + invoke the DAG. Otherwise, the caller should use `execute` to + invoke the DAG. + max_inflight_executions: The maximum number of in-flight executions that + can be submitted via `execute` or `execute_async` before consuming + the output using `ray.get()`. If the caller submits more executions, + `RayCgraphCapacityExceeded` is raised. + max_buffered_results: The maximum number of results that can be + buffered at the driver. If more results are buffered, + `RayCgraphCapacityExceeded` is raised. Note that + when result corresponding to an execution is retrieved + (by calling `ray.get()` on a `CompiledDAGRef` or + `CompiledDAGRef` or await on a `CompiledDAGFuture), results + corresponding to earlier executions that have not been retrieved + yet are buffered. + overlap_gpu_communication: (experimental) Whether to overlap GPU + communication with computation during DAG execution. If True, the + communication and computation can be overlapped, which can improve + the performance of the DAG execution. If None, the default value + will be used. + _default_communicator: The default communicator to use to transfer + tensors. Three types of values are valid. (1) Communicator: + For p2p operations, this is the default communicator + to use for nodes annotated with `with_tensor_transport()` and when + shared memory is not the desired option (e.g., when transport="accelerator", + or when transport="auto" for communication between two different GPUs). + For collective operations, this is the default communicator to use + when a custom communicator is not specified. + (2) "create": for each collective operation without a custom communicator + specified, a communicator is created and initialized on its involved actors, + or an already created communicator is reused if the set of actors is the same. + For all p2p operations without a custom communicator specified, it reuses + an already created collective communicator if the p2p actors are a subset. + Otherwise, a new communicator is created. + (3) None: a ValueError will be thrown if a custom communicator is not specified. + + Returns: + Channel: A wrapper around ray.ObjectRef. + """ + from ray.dag import DAGContext + + ctx = DAGContext.get_current() + + self._enable_asyncio: bool = enable_asyncio + self._fut_queue = asyncio.Queue() + self._max_inflight_executions = max_inflight_executions + if self._max_inflight_executions is None: + self._max_inflight_executions = ctx.max_inflight_executions + self._max_buffered_results = max_buffered_results + if self._max_buffered_results is None: + self._max_buffered_results = ctx.max_buffered_results + self._dag_id = uuid.uuid4().hex + self._submit_timeout: Optional[float] = submit_timeout + if self._submit_timeout is None: + self._submit_timeout = ctx.submit_timeout + self._get_timeout: Optional[float] = ctx.get_timeout + self._buffer_size_bytes: Optional[int] = buffer_size_bytes + if self._buffer_size_bytes is None: + self._buffer_size_bytes = ctx.buffer_size_bytes + self._overlap_gpu_communication: Optional[bool] = overlap_gpu_communication + if self._overlap_gpu_communication is None: + self._overlap_gpu_communication = ctx.overlap_gpu_communication + self._create_default_communicator = False + if isinstance(default_communicator, str): + if default_communicator == "create": + self._create_default_communicator = True + default_communicator = None + else: + raise ValueError( + "The only allowed string for default_communicator is 'create', " + f"got {default_communicator}" + ) + elif default_communicator is not None and not isinstance( + default_communicator, Communicator + ): + raise ValueError( + "The default_communicator must be None, a string, or a Communicator, " + f"got {type(default_communicator)}" + ) + self._default_communicator: Optional[Communicator] = default_communicator + + # Dict from passed-in communicator to set of type hints that refer to it. + self._communicator_to_type_hints: Dict[ + Communicator, + Set["ray.experimental.channel.torch_tensor_type.TorchTensorType"], + ] = defaultdict(set) + # Dict from set of actors to created communicator ID. + # These communicators are created by Compiled Graph, rather than passed in. + # Communicators are only created when self._create_default_communicator is True. + self._actors_to_created_communicator_id: Dict[ + Tuple["ray.actor.ActorHandle"], str + ] = {} + + # Set of actors involved in P2P communication using an unresolved communicator. + self._p2p_actors_with_unresolved_communicators: Set[ + "ray.actor.ActorHandle" + ] = set() + # Set of DAG nodes involved in P2P communication using an unresolved communicator. + self._p2p_dag_nodes_with_unresolved_communicators: Set[ + "ray.dag.DAGNode" + ] = set() + # Set of collective operations using an unresolved communicator. + self._collective_ops_with_unresolved_communicators: Set[ + "ray.dag.collective_node._CollectiveOperation" + ] = set() + + self._default_type_hint: ChannelOutputType = SharedMemoryType( + buffer_size_bytes=self._buffer_size_bytes, + # We conservatively set num_shm_buffers to _max_inflight_executions. + # It means that the DAG can be underutilized, but it guarantees there's + # no false positive timeouts. + num_shm_buffers=self._max_inflight_executions, + ) + if not isinstance(self._buffer_size_bytes, int) or self._buffer_size_bytes <= 0: + raise ValueError( + "`buffer_size_bytes` must be a positive integer, found " + f"{self._buffer_size_bytes}" + ) + + # Used to ensure that the future returned to the + # caller corresponds to the correct DAG output. I.e. + # order of futures added to fut_queue should match the + # order of inputs written to the DAG. + self._dag_submission_lock = asyncio.Lock() + + # idx -> CompiledTask. + self.idx_to_task: Dict[int, "CompiledTask"] = {} + # DAGNode -> idx. + self.dag_node_to_idx: Dict["ray.dag.DAGNode", int] = {} + # idx counter. + self.counter: int = 0 + + # Attributes that are set during preprocessing. + # Preprocessing identifies the input node and output node. + self.input_task_idx: Optional[int] = None + self.output_task_idx: Optional[int] = None + # List of task indices that are input attribute nodes. + self.input_attr_task_idxs: List[int] = [] + # Denotes whether execute/execute_async returns a list of refs/futures. + self._returns_list: bool = False + # Number of expected positional args and kwargs that may be passed to + # dag.execute. + self._input_num_positional_args: Optional[int] = None + self._input_kwargs: Tuple[str, ...] = None + + # Cached attributes that are set during compilation. + self.dag_input_channels: Optional[List[ChannelInterface]] = None + self.dag_output_channels: Optional[List[ChannelInterface]] = None + self._dag_submitter: Optional[WriterInterface] = None + self._dag_output_fetcher: Optional[ReaderInterface] = None + + # ObjectRef for each worker's task. The task is an infinite loop that + # repeatedly executes the method specified in the DAG. + self.worker_task_refs: Dict["ray.actor.ActorHandle", "ray.ObjectRef"] = {} + self.actor_to_tasks: Dict[ + "ray.actor.ActorHandle", List["CompiledTask"] + ] = defaultdict(list) + # Mapping from actor handle to its GPU IDs. + # This is used for type hint resolution for with_tensor_transport("auto"). + self.actor_to_gpu_ids: Dict["ray.actor.ActorHandle", List[str]] = {} + self.actor_to_executable_tasks: Dict[ + "ray.actor.ActorHandle", List["ExecutableTask"] + ] = {} + # Mapping from the actor handle to the execution schedule which is a list + # of operations to be executed. + self.actor_to_execution_schedule: Dict[ + "ray.actor.ActorHandle", List[_DAGNodeOperation] + ] = defaultdict(list) + # Mapping from the actor handle to the node ID that the actor is on. + # A None actor handle means the actor is the driver. + self.actor_to_node_id: Dict[Optional["ray.actor.ActorHandle"], str] = {} + # The index of the current execution. It is incremented each time + # the DAG is executed. + self._execution_index: int = -1 + # The maximum index of finished executions. + # All results with higher indexes have not been generated yet. + self._max_finished_execution_index: int = -1 + # execution_index -> {channel_index -> result} + self._result_buffer: Dict[int, Dict[int, Any]] = defaultdict(dict) + # channel to possible inner channel + self._channel_dict: Dict[ChannelInterface, ChannelInterface] = {} + + def _create_proxy_actor() -> "ray.actor.ActorHandle": + # Creates the driver actor on the same node as the driver. + # + # To support the driver as a reader, the output writer needs to be able to + # invoke remote functions on the driver (e.g., to create the reader ref, to + # create a reader ref for a larger object when the channel backing store is + # resized, etc.). The driver actor serves as a way for the output writer + # to invoke remote functions on the driver node. + return CompiledDAG.DAGDriverProxyActor.options( + scheduling_strategy=NodeAffinitySchedulingStrategy( + ray.get_runtime_context().get_node_id(), soft=False + ) + ).remote() + + self._proxy_actor = _create_proxy_actor() + # Set to True when `teardown` API is called. + self._is_teardown = False + # Execution index to set of channel indices for CompiledDAGRefs + # or CompiledDAGFuture whose destructor has been called. A "None" + # channel index means there is only one channel, and its destructor + # has been called. + self._destructed_ref_idxs: Dict[int, Set[Optional[int]]] = dict() + # Execution index to set of channel indices for CompiledDAGRefs + # or CompiledDAGFuture whose get() has been called. A "None" + # channel index means there is only one channel, and its get() + # has been called. + self._got_ref_idxs: Dict[int, Set[Optional[int]]] = dict() + + @property + def is_teardown(self) -> bool: + return self._is_teardown + + def get_id(self) -> str: + """ + Get the unique ID of the compiled DAG. + """ + return self._dag_id + + def __str__(self) -> str: + return f"CompiledDAG({self._dag_id})" + + def _add_node(self, node: "ray.dag.DAGNode") -> None: + idx = self.counter + self.idx_to_task[idx] = CompiledTask(idx, node) + self.dag_node_to_idx[node] = idx + self.counter += 1 + + def _preprocess(self) -> None: + """Before compiling, preprocess the DAG to build an index from task to + upstream and downstream tasks, and to set the input and output node(s) + of the DAG. + + This function is idempotent. + """ + from ray.dag import ( + DAGNode, + ClassMethodNode, + CollectiveOutputNode, + FunctionNode, + InputAttributeNode, + InputNode, + MultiOutputNode, + ) + + self.input_task_idx, self.output_task_idx = None, None + + input_attributes: Set[str] = set() + # Find the input node and input attribute nodes in the DAG. + for idx, task in self.idx_to_task.items(): + if isinstance(task.dag_node, InputNode): + assert self.input_task_idx is None, "More than one InputNode found" + self.input_task_idx = idx + # handle_unused_attributes: + # Save input attributes in a set. + input_node = task.dag_node + input_attributes.update(input_node.input_attribute_nodes.keys()) + elif isinstance(task.dag_node, InputAttributeNode): + self.input_attr_task_idxs.append(idx) + + # Find the (multi-)output node to the DAG. + for idx, task in self.idx_to_task.items(): + if idx == self.input_task_idx or isinstance( + task.dag_node, InputAttributeNode + ): + continue + if ( + len(task.downstream_task_idxs) == 0 + and task.dag_node.is_cgraph_output_node + ): + assert self.output_task_idx is None, "More than one output node found" + self.output_task_idx = idx + + assert self.output_task_idx is not None + output_node = self.idx_to_task[self.output_task_idx].dag_node + # Add an MultiOutputNode to the end of the DAG if it's not already there. + if not isinstance(output_node, MultiOutputNode): + output_node = MultiOutputNode([output_node]) + self._add_node(output_node) + self.output_task_idx = self.dag_node_to_idx[output_node] + else: + self._returns_list = True + + # TODO: Support no-input DAGs (use an empty object to signal). + if self.input_task_idx is None: + raise NotImplementedError( + "Compiled DAGs currently require exactly one InputNode" + ) + + # Whether the DAG binds directly to the InputNode(), versus binding to + # a positional arg or kwarg of the input. For example, a.foo.bind(inp) + # instead of a.foo.bind(inp[0]) or a.foo.bind(inp.key). + direct_input: Optional[bool] = None + # Collect the set of InputNode keys bound to DAG node args. + input_positional_args: Set[int] = set() + input_kwargs: Set[str] = set() + # Set of tasks with annotation of with_tensor_transport("auto"). + # These only correspond to ClassMethodNodes, but not InputNodes + # or InputAttributeNodes. + auto_transport_tasks: Set["CompiledTask"] = set() + + # For each task node, set its upstream and downstream task nodes. + # Also collect the set of tasks that produce torch.tensors. + for task_idx, task in self.idx_to_task.items(): + dag_node = task.dag_node + if not ( + isinstance(dag_node, InputNode) + or isinstance(dag_node, InputAttributeNode) + or isinstance(dag_node, MultiOutputNode) + or isinstance(dag_node, ClassMethodNode) + ): + if isinstance(dag_node, FunctionNode): + # TODO(swang): Support non-actor tasks. + raise NotImplementedError( + "Compiled DAGs currently only support actor method nodes" + ) + else: + raise ValueError(f"Found unsupported node of type {type(dag_node)}") + + if isinstance(dag_node, ClassMethodNode) and dag_node.is_class_method_call: + actor_handle = dag_node._get_actor_handle() + if actor_handle is None: + raise ValueError( + "Compiled DAGs can only bind methods to an actor " + "that is already created with Actor.remote()" + ) + + if actor_handle not in self.actor_to_gpu_ids: + self.actor_to_gpu_ids[actor_handle] = CompiledDAG._get_gpu_ids( + actor_handle + ) + + if isinstance(dag_node.type_hint, AutoTransportType): + auto_transport_tasks.add(task) + + # Collect actors for accelerator P2P methods. + if dag_node.type_hint.requires_accelerator(): + self._track_communicator_usage(dag_node, {actor_handle}) + # Collect accelerator collective operations. + if isinstance(dag_node, CollectiveOutputNode): + self._track_communicator_usage( + dag_node, + set(dag_node._collective_op.actor_handles), + collective_op=True, + ) + assert not self._overlap_gpu_communication, ( + "Currently, the overlap_gpu_communication option is not " + "supported for accelerator collective operations. Please set " + "overlap_gpu_communication=False." + ) + elif isinstance(dag_node, InputNode) or isinstance( + dag_node, InputAttributeNode + ): + if dag_node.type_hint.requires_accelerator(): + raise ValueError( + "DAG inputs cannot be transferred via accelerator because " + "the driver cannot participate in the communicator group" + ) + if isinstance(dag_node.type_hint, AutoTransportType): + # Currently driver on GPU is not supported, so we always + # use shared memory to transfer tensors. + dag_node.type_hint = TorchTensorType( + device=dag_node.type_hint.device + ) + + if type(dag_node.type_hint) is ChannelOutputType: + # No type hint specified by the user. Replace + # with the default type hint for this DAG. + dag_node.type_hint = self._default_type_hint + + for _, val in task.kwargs.items(): + if isinstance(val, DAGNode): + raise ValueError( + "Compiled DAG currently does not support binding to " + "other DAG nodes as kwargs" + ) + + for _, arg in enumerate(task.args): + if not isinstance(arg, DAGNode): + continue + upstream_node_idx = self.dag_node_to_idx[arg] + upstream_task = self.idx_to_task[upstream_node_idx] + downstream_actor_handle = None + if ( + isinstance(dag_node, ClassMethodNode) + and dag_node.is_class_method_call + ): + downstream_actor_handle = dag_node._get_actor_handle() + + # Add upstream node as the argument nodes of this task, whose + # type hints may be updated when resolved lazily. + task.arg_nodes.append(upstream_task.dag_node) + + if isinstance(upstream_task.dag_node, InputAttributeNode): + # Record all of the keys used to index the InputNode. + # During execution, we will check that the user provides + # the same args and kwargs. + if isinstance(upstream_task.dag_node.key, int): + input_positional_args.add(upstream_task.dag_node.key) + elif isinstance(upstream_task.dag_node.key, str): + input_kwargs.add(upstream_task.dag_node.key) + else: + raise ValueError( + "InputNode() can only be indexed using int " + "for positional args or str for kwargs." + ) + + if direct_input is not None and direct_input: + raise ValueError( + "All tasks must either use InputNode() " + "directly, or they must index to specific args or " + "kwargs." + ) + direct_input = False + + # If the upstream node is an InputAttributeNode, treat the + # DAG's input node as the actual upstream node + upstream_task = self.idx_to_task[self.input_task_idx] + + elif isinstance(upstream_task.dag_node, InputNode): + if direct_input is not None and not direct_input: + raise ValueError( + "All tasks must either use InputNode() directly, " + "or they must index to specific args or kwargs." + ) + direct_input = True + + upstream_task.downstream_task_idxs[task_idx] = downstream_actor_handle + + if upstream_task.dag_node.type_hint.requires_accelerator(): + # Here we are processing the args of the DAGNode, so track + # downstream actors only, upstream actor is already tracked + # when processing the DAGNode itself. + self._track_communicator_usage( + upstream_task.dag_node, + {downstream_actor_handle}, + ) + # Check that all specified input attributes, e.g., InputNode()["x"], + # are used in the DAG. + _check_unused_dag_input_attributes(output_node, input_attributes) + + self._check_leaf_nodes() + + self._resolve_auto_transport(auto_transport_tasks) + + self._init_communicators() + + if direct_input: + self._input_num_positional_args = 1 + elif not input_positional_args: + self._input_num_positional_args = 0 + else: + self._input_num_positional_args = max(input_positional_args) + 1 + self._input_kwargs = tuple(input_kwargs) + + def _init_communicators(self) -> None: + """ + Initialize communicators for the DAG. + """ + + # First, initialize communicators that are passed in by the user. + for communicator, type_hints in self._communicator_to_type_hints.items(): + communicator_id = _init_communicator( + communicator.get_actor_handles(), + communicator, + self._overlap_gpu_communication, + ) + for type_hint in type_hints: + type_hint.set_communicator_id(communicator_id) + + # Second, get registered accelerator context if any. + accelerator_module_name = AcceleratorContext.get().module_name + accelerator_communicator_cls = AcceleratorContext.get().communicator_cls + + # Then, create communicators for collective operations. + # Reuse an already created communicator for the same set of actors. + for collective_op in self._collective_ops_with_unresolved_communicators: + if not self._create_default_communicator: + raise ValueError( + "Communicator creation is not allowed for collective operations." + ) + # using tuple to preserve the order of actors for collective operations + actors = tuple(collective_op.actor_handles) + if actors in self._actors_to_created_communicator_id: + communicator_id = self._actors_to_created_communicator_id[actors] + else: + communicator_id = _init_communicator( + list(actors), + None, + self._overlap_gpu_communication, + accelerator_module_name, + accelerator_communicator_cls, + ) + self._actors_to_created_communicator_id[actors] = communicator_id + collective_op.type_hint.set_communicator_id(communicator_id) + + # Finally, create a communicator for P2P operations. + # Reuse an already created collective op communicator when p2p actors + # are a subset of the actors in the collective op communicator. + p2p_communicator_id = None + if self._p2p_actors_with_unresolved_communicators: + for ( + actors, + communicator_id, + ) in self._actors_to_created_communicator_id.items(): + if self._p2p_actors_with_unresolved_communicators.issubset(actors): + p2p_communicator_id = communicator_id + break + if p2p_communicator_id is None: + p2p_communicator_id = _init_communicator( + list(self._p2p_actors_with_unresolved_communicators), + None, + self._overlap_gpu_communication, + accelerator_module_name, + accelerator_communicator_cls, + ) + for dag_node in self._p2p_dag_nodes_with_unresolved_communicators: + dag_node.type_hint.set_communicator_id(p2p_communicator_id) + + def _track_communicator_usage( + self, + dag_node: "ray.dag.DAGNode", + actors: Set["ray.actor.ActorHandle"], + collective_op: bool = False, + ) -> None: + """ + Track the usage of a communicator. + + This method first determines the communicator to use: if a custom + communicator is specified, use it; if not and a default communicator + is available, use it; otherwise, it records necessary information to + create a new communicator later. + + This method also performs validation checks on the passed-in communicator. + + Args: + dag_node: The DAG node that uses the communicator, this is the node + that has the `with_tensor_transport()` type hint for p2p communication, + or a `CollectiveOutputNode` for collective operations. + actors: The full or partial set of actors that use the communicator. + This method should be called one or multiple times so that all actors + of the communicator are tracked. + collective_op: Whether the communicator is used for a collective operation. + """ + if None in actors: + raise ValueError("Driver cannot participate in the communicator group.") + if collective_op: + type_hint = dag_node._collective_op.type_hint + else: + type_hint = dag_node.type_hint + communicator = type_hint.get_custom_communicator() + + if communicator is None: + if ( + self._default_communicator is None + and not self._create_default_communicator + ): + if dag_node._original_type_hint is not None: + assert isinstance(dag_node._original_type_hint, AutoTransportType) + raise ValueError( + f"with_tensor_transport(transport='auto') is used for DAGNode {dag_node}, " + "This requires specifying a default communicator or 'create' for " + "_default_communicator when calling experimental_compile()." + ) + raise ValueError( + f"DAGNode {dag_node} has no custom communicator specified. " + "Please specify a custom communicator for the DAGNode using " + "`with_tensor_transport()`, or specify a communicator or 'create' for " + "_default_communicator when calling experimental_compile()." + ) + communicator = self._default_communicator + + if communicator is None: + if collective_op: + self._collective_ops_with_unresolved_communicators.add( + dag_node._collective_op + ) + else: + self._p2p_dag_nodes_with_unresolved_communicators.add(dag_node) + self._p2p_actors_with_unresolved_communicators.update(actors) + else: + if collective_op: + if set(communicator.get_actor_handles()) != actors: + raise ValueError( + "The passed-in communicator must have the same set " + "of actors as the collective operation. " + f"The passed-in communicator has actors {communicator.get_actor_handles()} " + f"while the collective operation has actors {actors}." + ) + else: + if not actors.issubset(set(communicator.get_actor_handles())): + raise ValueError( + "The passed-in communicator must include all of the actors " + "used in the P2P operation. " + f"The passed-in communicator has actors {communicator.get_actor_handles()} " + f"while the P2P operation has actors {actors}." + ) + self._communicator_to_type_hints[communicator].add(type_hint) + + def _resolve_auto_transport( + self, + auto_transport_tasks: Set["CompiledTask"], + ) -> None: + """ + Resolve the auto transport type hint for the DAG. + """ + type_hint_resolver = TypeHintResolver(self.actor_to_gpu_ids) + # Resolve AutoChannelType type hints and track the actors that use accelerator. + # This is needed so that the communicator group can be initialized for + # these actors that use accelerator. + for task in auto_transport_tasks: + writer = task.dag_node._get_actor_handle() + readers = task.downstream_task_idxs.values() + writer_and_node = (writer, self._get_node_id(writer)) + reader_and_node_list = [ + (reader, self._get_node_id(reader)) for reader in readers + ] + # Update the type hint to the resolved one. This is needed because + # the resolved type hint's `register_custom_serializer` will be called + # in preparation for channel I/O. + task.dag_node.type_hint = type_hint_resolver.resolve( + task.dag_node.type_hint, + writer_and_node, + reader_and_node_list, + ) + if task.dag_node.type_hint.requires_accelerator(): + self._track_communicator_usage( + task.dag_node, + set(readers).union({writer}), + ) + + def _check_leaf_nodes(self) -> None: + """ + Check if there are leaf nodes in the DAG and raise an error if there are. + """ + from ray.dag import ( + DAGNode, + ClassMethodNode, + ) + + leaf_nodes: List[DAGNode] = [] + for _, task in self.idx_to_task.items(): + if not isinstance(task.dag_node, ClassMethodNode): + continue + if ( + len(task.downstream_task_idxs) == 0 + and not task.dag_node.is_cgraph_output_node + ): + leaf_nodes.append(task.dag_node) + # Leaf nodes are not allowed because the exception thrown by the leaf + # node will not be propagated to the driver. + if len(leaf_nodes) != 0: + raise ValueError( + "Compiled DAG doesn't support leaf nodes, i.e., nodes that don't have " + "downstream nodes and are not output nodes. There are " + f"{len(leaf_nodes)} leaf nodes in the DAG. Please add the outputs of " + f"{[leaf_node.get_method_name() for leaf_node in leaf_nodes]} to the " + f"the MultiOutputNode." + ) + + @staticmethod + def _get_gpu_ids(actor_handle: "ray.actor.ActorHandle") -> List[str]: + """ + Get the GPU IDs of an actor handle. + """ + accelerator_ids = ray.get( + actor_handle.__ray_call__.remote( + lambda self: ray.get_runtime_context().get_accelerator_ids() + ) + ) + return accelerator_ids.get("GPU", []) + + def _get_node_id(self, actor_handle: Optional["ray.actor.ActorHandle"]) -> str: + """ + Get the node ID of an actor handle and cache it. + + Args: + actor_handle: The actor handle, or None if the actor handle is the + driver. + Returns: + The node ID of the actor handle or driver. + """ + if actor_handle in self.actor_to_node_id: + return self.actor_to_node_id[actor_handle] + node_id = None + if actor_handle == self._proxy_actor or actor_handle is None: + node_id = ray.get_runtime_context().get_node_id() + else: + node_id = ray.get( + actor_handle.__ray_call__.remote( + lambda self: ray.get_runtime_context().get_node_id() + ) + ) + self.actor_to_node_id[actor_handle] = node_id + return node_id + + def _get_or_compile( + self, + ) -> None: + """Compile an execution path. This allocates channels for adjacent + tasks to send/receive values. An infinite task is submitted to each + actor in the DAG that repeatedly receives from input channel(s) and + sends to output channel(s). + + This function is idempotent and will cache the previously allocated + channels. After calling this function, _dag_submitter and + _dag_output_fetcher will be set and can be used to invoke and fetch + outputs for the DAG. + """ + from ray.dag import ( + DAGNode, + InputNode, + InputAttributeNode, + MultiOutputNode, + ClassMethodNode, + ) + + if self.input_task_idx is None: + self._preprocess() + assert self.input_task_idx is not None + + if self._dag_submitter is not None: + assert self._dag_output_fetcher is not None + return + + frontier = [self.input_task_idx] + visited = set() + # Create output buffers. This loop does a breadth-first search through the DAG. + while frontier: + cur_idx = frontier.pop(0) + if cur_idx in visited: + continue + visited.add(cur_idx) + + task = self.idx_to_task[cur_idx] + if ( + isinstance(task.dag_node, ClassMethodNode) + and task.dag_node.is_class_method_call + ): + # Create output buffers for the actor method. + assert len(task.output_channels) == 0 + # `output_to_readers` stores the reader tasks for each output of + # the current node. If the current node returns one output, the + # readers are the downstream nodes of the current node. If the + # current node returns multiple outputs, the readers of each + # output are the downstream nodes of the ClassMethodNode that + # is a class method output. + output_to_readers: Dict[CompiledTask, List[CompiledTask]] = defaultdict( + list + ) + for idx in task.downstream_task_idxs: + downstream_task = self.idx_to_task[idx] + downstream_node = downstream_task.dag_node + if ( + isinstance(downstream_node, ClassMethodNode) + and downstream_node.is_class_method_output + ): + output_to_readers[downstream_task] = [ + self.idx_to_task[idx] + for idx in downstream_task.downstream_task_idxs + ] + else: + if task not in output_to_readers: + output_to_readers[task] = [] + output_to_readers[task].append(downstream_task) + fn = task.dag_node._get_remote_method("__ray_call__") + for output, readers in output_to_readers.items(): + reader_and_node_list: List[Tuple["ray.actor.ActorHandle", str]] = [] + # Use reader_handles_set to deduplicate readers on the + # same actor, because with CachedChannel each actor will + # only read from the upstream channel once. + reader_handles_set = set() + read_by_multi_output_node = False + for reader in readers: + if isinstance(reader.dag_node, MultiOutputNode): + read_by_multi_output_node = True + # inserting at 0 to make sure driver is first reader as + # expected by CompositeChannel read + reader_and_node_list.insert( + 0, + ( + self._proxy_actor, + self._get_node_id(self._proxy_actor), + ), + ) + else: + reader_handle = reader.dag_node._get_actor_handle() + if reader_handle not in reader_handles_set: + reader_handle = reader.dag_node._get_actor_handle() + reader_and_node_list.append( + (reader_handle, self._get_node_id(reader_handle)) + ) + reader_handles_set.add(reader_handle) + + # if driver is an actual actor, gets driver actor id + driver_actor_id = ( + ray.get_runtime_context().get_actor_id() + if read_by_multi_output_node + else None + ) + # Create an output channel for each output of the current node. + output_channel = ray.get( + fn.remote( + do_allocate_channel, + reader_and_node_list, + task.dag_node.type_hint, + driver_actor_id, + ) + ) + output_idx = None + downstream_node = output.dag_node + if ( + isinstance(downstream_node, ClassMethodNode) + and downstream_node.is_class_method_output + ): + output_idx = downstream_node.output_idx + task.output_channels.append(output_channel) + task.output_idxs.append(output_idx) + task.output_node_idxs.append(self.dag_node_to_idx[downstream_node]) + actor_handle = task.dag_node._get_actor_handle() + assert actor_handle is not None + self.actor_to_tasks[actor_handle].append(task) + elif ( + isinstance(task.dag_node, ClassMethodNode) + and task.dag_node.is_class_method_output + ): + task_node = task.dag_node + upstream_node = task_node.class_method_call + assert upstream_node + upstream_task = self.idx_to_task[self.dag_node_to_idx[upstream_node]] + for i in range(len(upstream_task.output_channels)): + if upstream_task.output_idxs[i] == task_node.output_idx: + task.output_channels.append(upstream_task.output_channels[i]) + task.output_idxs.append(upstream_task.output_idxs[i]) + assert len(task.output_channels) == 1 + elif isinstance(task.dag_node, InputNode): + # A dictionary that maps an InputNode or InputAttributeNode to its + # readers and the node on which the reader is running. Use `set` to + # deduplicate readers on the same actor because with CachedChannel + # each actor will only read from the shared memory once. + input_node_to_reader_and_node_set: Dict[ + Union[InputNode, InputAttributeNode], + Set[Tuple["ray.actor.ActorHandle", str]], + ] = defaultdict(set) + + for idx in task.downstream_task_idxs: + reader_task = self.idx_to_task[idx] + assert isinstance(reader_task.dag_node, ClassMethodNode) + reader_handle = reader_task.dag_node._get_actor_handle() + reader_node_id = self._get_node_id(reader_handle) + for arg in reader_task.args: + if isinstance(arg, InputAttributeNode) or isinstance( + arg, InputNode + ): + input_node_to_reader_and_node_set[arg].add( + (reader_handle, reader_node_id) + ) + + # A single channel is responsible for sending the same data to + # corresponding consumers. Therefore, we create a channel for + # each InputAttributeNode, or a single channel for the entire + # input data if there are no InputAttributeNodes. + task.output_channels = [] + for input_dag_node in input_node_to_reader_and_node_set: + reader_and_node_list = list( + input_node_to_reader_and_node_set[input_dag_node] + ) + + output_channel = do_allocate_channel( + self, + reader_and_node_list, + input_dag_node.type_hint, + None, + ) + task.output_channels.append(output_channel) + task.output_idxs.append( + None + if isinstance(input_dag_node, InputNode) + else input_dag_node.key + ) + + # Update the InputAttributeNode's `output_channels`, which is + # used to determine whether to create a CachedChannel. + if isinstance(input_dag_node, InputAttributeNode): + input_attr_idx = self.dag_node_to_idx[input_dag_node] + input_attr_task = self.idx_to_task[input_attr_idx] + input_attr_task.output_channels.append(output_channel) + assert len(input_attr_task.output_channels) == 1 + else: + assert isinstance(task.dag_node, InputAttributeNode) or isinstance( + task.dag_node, MultiOutputNode + ) + + for idx in task.downstream_task_idxs: + frontier.append(idx) + + # Validate input channels for tasks that have not been visited + for node_idx, task in self.idx_to_task.items(): + if ( + node_idx == self.input_task_idx + or node_idx == self.output_task_idx + or isinstance(task.dag_node, InputAttributeNode) + ): + continue + if node_idx not in visited: + has_at_least_one_channel_input = False + for arg in task.args: + if isinstance(arg, DAGNode): + has_at_least_one_channel_input = True + if not has_at_least_one_channel_input: + raise ValueError( + "Compiled DAGs require each task to take a ray.dag.InputNode " + "or at least one other DAGNode as an input. " + "Invalid task node:\n" + f"{task.dag_node}\n" + "Please bind the task to proper DAG nodes." + ) + + from ray.dag.constants import RAY_CGRAPH_ENABLE_DETECT_DEADLOCK + + if RAY_CGRAPH_ENABLE_DETECT_DEADLOCK and self._detect_deadlock(): + raise ValueError( + "This DAG cannot be compiled because it will deadlock on accelerator " + "calls. If you believe this is a false positive, please disable " + "the graph verification by setting the environment variable " + "RAY_CGRAPH_ENABLE_DETECT_DEADLOCK to 0 and file an issue at " + "https://github.com/ray-project/ray/issues/new/." + ) + + input_task = self.idx_to_task[self.input_task_idx] + self.dag_input_channels = input_task.output_channels + assert self.dag_input_channels is not None + + # Create executable tasks for each actor + for actor_handle, tasks in self.actor_to_tasks.items(): + # Dict from arg to the set of tasks that consume it. + arg_to_consumers: Dict[DAGNode, Set[CompiledTask]] = defaultdict(set) + + # Step 1: populate `arg_to_consumers` and perform some validation. + for task in tasks: + has_at_least_one_channel_input = False + for arg in task.args: + if isinstance(arg, DAGNode): + has_at_least_one_channel_input = True + arg_to_consumers[arg].add(task) + arg_idx = self.dag_node_to_idx[arg] + upstream_task = self.idx_to_task[arg_idx] + assert len(upstream_task.output_channels) == 1 + arg_channel = upstream_task.output_channels[0] + assert arg_channel is not None + # TODO: Support no-input DAGs (use an empty object to signal). + if not has_at_least_one_channel_input: + raise ValueError( + "Compiled DAGs require each task to take a " + "ray.dag.InputNode or at least one other DAGNode as an " + "input" + ) + + # Step 2: create cached channels if needed + + # Dict from original channel to the channel to be used in execution. + # The value of this dict is either the original channel or a newly + # created CachedChannel (if the original channel is read more than once). + for arg, consumers in arg_to_consumers.items(): + arg_idx = self.dag_node_to_idx[arg] + upstream_task = self.idx_to_task[arg_idx] + assert len(upstream_task.output_channels) == 1 + arg_channel = upstream_task.output_channels[0] + assert arg_channel is not None + if len(consumers) > 1: + self._channel_dict[arg_channel] = CachedChannel( + len(consumers), + arg_channel, + ) + else: + self._channel_dict[arg_channel] = arg_channel + + # Step 3: create executable tasks for the actor + executable_tasks = [] + for task in tasks: + resolved_args: List[Any] = [] + for arg in task.args: + if isinstance(arg, DAGNode): + arg_idx = self.dag_node_to_idx[arg] + upstream_task = self.idx_to_task[arg_idx] + assert len(upstream_task.output_channels) == 1 + arg_channel = upstream_task.output_channels[0] + assert arg_channel is not None + arg_channel = self._channel_dict[arg_channel] + resolved_args.append(arg_channel) + else: + # Constant arg + resolved_args.append(arg) + executable_task = ExecutableTask( + task, + resolved_args, + task.kwargs, + ) + executable_tasks.append(executable_task) + # Sort executable tasks based on their bind index, i.e., submission order + # so that they will be executed in that order. + executable_tasks.sort(key=lambda task: task.bind_index) + self.actor_to_executable_tasks[actor_handle] = executable_tasks + + from ray.dag.constants import RAY_CGRAPH_ENABLE_PROFILING + + if RAY_CGRAPH_ENABLE_PROFILING: + exec_task_func = do_profile_tasks + else: + exec_task_func = do_exec_tasks + + # Build an execution schedule for each actor + self.actor_to_execution_schedule = self._build_execution_schedule() + for actor_handle, executable_tasks in self.actor_to_executable_tasks.items(): + self.worker_task_refs[actor_handle] = actor_handle.__ray_call__.options( + concurrency_group="_ray_system" + ).remote( + exec_task_func, + executable_tasks, + self.actor_to_execution_schedule[actor_handle], + self._overlap_gpu_communication, + ) + + assert self.output_task_idx is not None + self.dag_output_channels = [] + for output in self.idx_to_task[self.output_task_idx].args: + assert isinstance(output, DAGNode) + output_idx = self.dag_node_to_idx[output] + task = self.idx_to_task[output_idx] + assert len(task.output_channels) == 1 + self.dag_output_channels.append(task.output_channels[0]) + + # Register custom serializers for input, input attribute, and output nodes. + self._register_input_output_custom_serializer() + + assert self.dag_input_channels + assert self.dag_output_channels + assert [ + output_channel is not None for output_channel in self.dag_output_channels + ] + # If no MultiOutputNode was specified during the DAG creation, there is only + # one output. Return a single output channel instead of a list of + # channels. + if not self._returns_list: + assert len(self.dag_output_channels) == 1 + + # Driver should ray.put on input, ray.get/release on output + self._monitor = self._monitor_failures() + input_task = self.idx_to_task[self.input_task_idx] + if self._enable_asyncio: + self._dag_submitter = AwaitableBackgroundWriter( + self.dag_input_channels, + input_task.output_idxs, + is_input=True, + ) + self._dag_output_fetcher = AwaitableBackgroundReader( + self.dag_output_channels, + self._fut_queue, + ) + else: + self._dag_submitter = SynchronousWriter( + self.dag_input_channels, input_task.output_idxs, is_input=True + ) + self._dag_output_fetcher = SynchronousReader(self.dag_output_channels) + + self._dag_submitter.start() + self._dag_output_fetcher.start() + + def _generate_dag_operation_graph_node( + self, + ) -> Dict["ray.actor.ActorHandle", List[List[_DAGOperationGraphNode]]]: + """ + Generate READ, COMPUTE, and WRITE operations for each DAG node. + + Returns: + A dictionary that maps an actor handle to a list of lists of + _DAGOperationGraphNode. For the same actor, the index of the + outer list corresponds to the index of the ExecutableTask in + the list of `executable_tasks` in `actor_to_executable_tasks`, + i.e. `exec_task_idx`. In the inner list, the order of operations + is READ, COMPUTE, and WRITE. + + Example: + { + actor1: [ + [READ COMPUTE WRITE] # exec_task_idx 0 + [READ COMPUTE WRITE] # exec_task_idx 1 + ] + } + """ + from ray.dag.collective_node import CollectiveOutputNode + + assert self.idx_to_task + assert self.actor_to_executable_tasks + + actor_to_operation_nodes: Dict[ + "ray.actor.ActorHandle", List[List[_DAGOperationGraphNode]] + ] = defaultdict(list) + + for actor_handle, executable_tasks in self.actor_to_executable_tasks.items(): + for exec_task_idx, exec_task in enumerate(executable_tasks): + # Divide a DAG node into three _DAGOperationGraphNodes: READ, COMPUTE, + # and WRITE. Each _DAGOperationGraphNode has a _DAGNodeOperation. + task_idx = exec_task.task_idx + dag_node = self.idx_to_task[task_idx].dag_node + method_name = exec_task.method_name + actor_handle = dag_node._get_actor_handle() + requires_accelerator_read = False + for upstream_node in dag_node._upstream_nodes: + if upstream_node.type_hint.requires_accelerator(): + requires_accelerator_read = True + break + requires_accelerator_compute = isinstance( + dag_node, CollectiveOutputNode + ) + requires_accelerator_write = dag_node.type_hint.requires_accelerator() + + read_node = _DAGOperationGraphNode( + _DAGNodeOperation( + exec_task_idx, _DAGNodeOperationType.READ, method_name + ), + task_idx, + actor_handle, + requires_accelerator_read, + ) + compute_node = _DAGOperationGraphNode( + _DAGNodeOperation( + exec_task_idx, _DAGNodeOperationType.COMPUTE, method_name + ), + task_idx, + actor_handle, + requires_accelerator_compute, + ) + write_node = _DAGOperationGraphNode( + _DAGNodeOperation( + exec_task_idx, _DAGNodeOperationType.WRITE, method_name + ), + task_idx, + actor_handle, + requires_accelerator_write, + ) + + actor_to_operation_nodes[actor_handle].append( + [read_node, compute_node, write_node] + ) + + return actor_to_operation_nodes + + def _build_execution_schedule( + self, + ) -> Dict["ray.actor.ActorHandle", List[_DAGNodeOperation]]: + """ + Generate an execution schedule for each actor. The schedule is a list of + _DAGNodeOperation. + + Step 1: Generate a DAG node operation graph. Refer to the functions + `_generate_dag_operation_graph_node` and `_build_dag_node_operation_graph` + for more details. + + Step 2: Topological sort + + It is possible to have multiple _DAGOperationGraphNodes with zero in-degree. + Refer to the function `_select_next_nodes` for the logic of selecting nodes. + + Then, put the selected nodes into the corresponding actors' schedules. + + The schedule should be intuitive to users, meaning that the execution should + perform operations in ascending order of `bind_index` as much as possible. + + [Example]: + + See `test_execution_schedule` for more examples. + + Returns: + actor_to_execution_schedule: A dictionary that maps an actor handle to + the execution schedule which is a list of operations to be executed. + """ + # Step 1: Build a graph of _DAGOperationGraphNode + actor_to_operation_nodes = self._generate_dag_operation_graph_node() + graph = _build_dag_node_operation_graph( + self.idx_to_task, actor_to_operation_nodes + ) + # Step 2: Generate an execution schedule for each actor using topological sort + actor_to_execution_schedule = _generate_actor_to_execution_schedule(graph) + + # Step 3: Overlap GPU communication for the execution schedule if configured + actor_to_overlapped_schedule = None + if self._overlap_gpu_communication: + actor_to_overlapped_schedule = _generate_overlapped_execution_schedule( + actor_to_execution_schedule + ) + + if RAY_CGRAPH_VISUALIZE_SCHEDULE: + _visualize_execution_schedule( + actor_to_execution_schedule, actor_to_overlapped_schedule, graph + ) + + if actor_to_overlapped_schedule is not None: + return _extract_execution_schedule(actor_to_overlapped_schedule) + else: + return _extract_execution_schedule(actor_to_execution_schedule) + + def _detect_deadlock(self) -> bool: + """ + TODO (kevin85421): Avoid false negatives. + + Currently, a compiled graph may deadlock if there are accelerator channels, + and the readers have control dependencies on the same actor. For example: + + actor1.a ---> actor2.f1 + | + ---> actor2.f2 + + The control dependency between `actor2.f1` and `actor2.f2` is that `f1` should + run before `f2`. If `actor1.a` writes to `actor2.f2` before `actor2.f1`, a + deadlock will occur. + + Currently, the execution schedule is not granular enough to detect this + deadlock. + + Returns: + True if a deadlock is detected; otherwise, False. + """ + logger.debug("Deadlock detection has not been implemented yet.") + return False + + def _monitor_failures(self): + get_outer = weakref.ref(self) + + class Monitor(threading.Thread): + def __init__(self): + super().__init__(daemon=True) + self.name = "CompiledGraphMonitorThread" + # Lock to make sure that we only perform teardown for this DAG + # once. + self._in_teardown_lock = threading.Lock() + self._teardown_done = False + + def _outer_ref_alive(self) -> bool: + if get_outer() is None: + logger.error( + "CompiledDAG has been destructed before teardown. " + "This should not occur please report an issue at " + "https://github.com/ray-project/ray/issues/new/.", + stack_info=True, + ) + return False + return True + + def wait_teardown(self, kill_actors: bool = False): + outer = get_outer() + if not self._outer_ref_alive(): + return + + from ray.dag import DAGContext + + ctx = DAGContext.get_current() + teardown_timeout = ctx.teardown_timeout + for actor, ref in outer.worker_task_refs.items(): + timeout = False + try: + ray.get(ref, timeout=teardown_timeout) + except ray.exceptions.GetTimeoutError: + msg = ( + f"Compiled DAG actor {actor} is still running " + f"{teardown_timeout}s after teardown()." + ) + if kill_actors: + msg += ( + " Force-killing actor. " + "Increase RAY_CGRAPH_teardown_timeout if you want " + "teardown to wait longer." + ) + ray.kill(actor) + else: + msg += ( + " Teardown may hang. " + "Call teardown with kill_actors=True if force kill " + "is desired." + ) + + logger.warning(msg) + timeout = True + except Exception: + # We just want to check that the task has finished so + # we don't care if the actor task ended in an + # exception. + pass + + if not timeout: + continue + + try: + ray.get(ref) + except Exception: + pass + + if kill_actors: + # In the previous loop, we allow the actor tasks to exit first. + # Now, we force kill the actors if not yet. + for actor in outer.worker_task_refs: + logger.info(f"Killing actor: {actor}") + ray.kill(actor) + + def teardown(self, kill_actors: bool = False): + with self._in_teardown_lock: + if self._teardown_done: + return + + outer = get_outer() + if not self._outer_ref_alive(): + return + + logger.info("Tearing down compiled DAG") + outer._dag_submitter.close() + outer._dag_output_fetcher.close() + + for actor in outer.actor_to_executable_tasks.keys(): + logger.info(f"Cancelling compiled worker on actor: {actor}") + # Cancel all actor loops in parallel. + cancel_refs = [ + actor.__ray_call__.remote(do_cancel_executable_tasks, tasks) + for actor, tasks in outer.actor_to_executable_tasks.items() + ] + for cancel_ref in cancel_refs: + try: + ray.get(cancel_ref, timeout=30) + except RayChannelError: + # Channel error happens when a channel is closed + # or timed out. In this case, do not log. + pass + except Exception: + logger.exception("Error cancelling worker task") + pass + + for ( + communicator_id + ) in outer._actors_to_created_communicator_id.values(): + _destroy_communicator(communicator_id) + + logger.info("Waiting for worker tasks to exit") + self.wait_teardown(kill_actors=kill_actors) + + logger.info("Teardown complete") + self._teardown_done = True + + def run(self): + try: + outer = get_outer() + if not self._outer_ref_alive(): + return + ray.get(list(outer.worker_task_refs.values())) + except KeyboardInterrupt: + logger.info( + "Received KeyboardInterrupt, tearing down with kill_actors=True" + ) + self.teardown(kill_actors=True) + except Exception as e: + logger.debug(f"Handling exception from worker tasks: {e}") + self.teardown() + + monitor = Monitor() + monitor.start() + return monitor + + def _raise_if_too_many_inflight_executions(self): + num_inflight_executions = ( + self._execution_index - self._max_finished_execution_index + ) + if num_inflight_executions >= self._max_inflight_executions: + raise ray.exceptions.RayCgraphCapacityExceeded( + "The compiled graph can't have more than " + f"{self._max_inflight_executions} in-flight executions, and you " + f"currently have {num_inflight_executions} in-flight executions. " + "Retrieve an output using ray.get before submitting more requests or " + "increase `_max_inflight_executions`. " + "`dag.experimental_compile(_max_inflight_executions=...)`" + ) + + def _has_execution_results( + self, + execution_index: int, + ) -> bool: + """Check whether there are results corresponding to the given execution + index stored in self._result_buffer. This helps avoid fetching and + caching results again. + + Args: + execution_index: The execution index corresponding to the result. + + Returns: + Whether the result for the given index has been fetched and cached. + """ + return execution_index in self._result_buffer + + def _cache_execution_results( + self, + execution_index: int, + result: Any, + ): + """Cache execution results in self._result_buffer. Results are converted + to dictionary format to allow efficient element removal and calculation of + the buffer size. This can only be called once per execution index. + + Args: + execution_index: The execution index corresponding to the result. + result: The results from all channels to be cached. + """ + if not self._has_execution_results(execution_index): + for chan_idx, res in enumerate(result): + # avoid caching for any CompiledDAGRef that has already been destructed. + if not ( + execution_index in self._destructed_ref_idxs + and chan_idx in self._destructed_ref_idxs[execution_index] + ): + self._result_buffer[execution_index][chan_idx] = res + + def _get_execution_results( + self, execution_index: int, channel_index: Optional[int] + ) -> List[Any]: + """Retrieve execution results from self._result_buffer and return the result. + Results are converted back to original list format ordered by output channel + index. + + Args: + execution_index: The execution index to retrieve results from. + channel_index: The index of the output channel corresponding to the result. + Channel indexing is consistent with the order of + self.dag_output_channels. None means that the result wraps outputs from + all output channels. + + Returns: + The execution result corresponding to the given execution index and channel + index. + """ + # Although CompiledDAGRef and CompiledDAGFuture guarantee that the same + # execution index and channel index combination will not be requested multiple + # times and therefore self._result_buffer will always have execution_index as + # a key, we still do a sanity check to avoid misuses. + assert execution_index in self._result_buffer + + if channel_index is None: + # Convert results stored in self._result_buffer back to original + # list representation + result = [ + kv[1] + for kv in sorted( + self._result_buffer.pop(execution_index).items(), + key=lambda kv: kv[0], + ) + ] + else: + result = [self._result_buffer[execution_index].pop(channel_index)] + + if execution_index not in self._got_ref_idxs: + self._got_ref_idxs[execution_index] = set() + self._got_ref_idxs[execution_index].add(channel_index) + self._clean_up_buffers(execution_index) + return result + + def _delete_execution_results(self, execution_index: int, channel_index: int): + """ + Delete the execution results for the given execution index and channel index. + This method should be called when a CompiledDAGRef or CompiledDAGFuture is + destructed. + + Note that this method maintains metadata for the deleted execution results, + and only actually deletes the buffers lazily when the buffer is not needed + anymore. + + Args: + execution_index: The execution index to destruct results from. + channel_index: The index of the output channel corresponding to the result. + """ + if execution_index not in self._destructed_ref_idxs: + self._destructed_ref_idxs[execution_index] = set() + self._destructed_ref_idxs[execution_index].add(channel_index) + self._clean_up_buffers(execution_index) + + def _try_release_result_buffer(self, execution_index: int): + """ + Try to release the result buffer for the given execution index. + """ + + should_release = False + got_channel_idxs = self._got_ref_idxs.get(execution_index, set()) + if None in got_channel_idxs: + assert len(got_channel_idxs) == 1, ( + "when None exists in got_channel_idxs, it means all channels, and " + "it should be the only value in the set", + ) + should_release = True + else: + destructed_channel_idxs = self._destructed_ref_idxs.get( + execution_index, set() + ) + processed_channel_idxs = got_channel_idxs.union(destructed_channel_idxs) + # No more processing is needed for this execution index. + should_release = processed_channel_idxs == set( + range(len(self.dag_output_channels)) + ) + + if not should_release: + return False + + self._result_buffer.pop(execution_index, None) + self._destructed_ref_idxs.pop(execution_index, None) + self._got_ref_idxs.pop(execution_index, None) + return True + + def _try_release_native_buffer( + self, idx_to_release: int, timeout: Optional[float] = None + ) -> bool: + """ + Try to release the native buffer for the given execution index. + + Args: + idx_to_release: The execution index to release buffers from. + timeout: The maximum time in seconds to wait for the release. + + Returns: + Whether the buffers have been released. + """ + if idx_to_release != self._max_finished_execution_index + 1: + # Native buffer can only be released for the next execution index. + return False + + destructed_channel_idxs = self._destructed_ref_idxs.get(idx_to_release, set()) + should_release = False + if None in destructed_channel_idxs: + assert len(destructed_channel_idxs) == 1, ( + "when None exists in destructed_channel_idxs, it means all channels, " + "and it should be the only value in the set", + ) + should_release = True + elif len(destructed_channel_idxs) == len(self.dag_output_channels): + should_release = True + + if not should_release: + return False + + # refs corresponding to idx_to_release are all destructed, + # and they are never fetched or cached. + assert idx_to_release not in self._result_buffer + assert idx_to_release not in self._got_ref_idxs + + try: + self._dag_output_fetcher.release_channel_buffers(timeout) + except RayChannelTimeoutError as e: + raise RayChannelTimeoutError( + "Releasing native buffers corresponding to a stale CompiledDAGRef " + "is taking a long time. If this is expected, increase " + f"RAY_CGRAPH_get_timeout which is currently {self._get_timeout} " + "seconds. Otherwise, this may indicate that the execution " + "is hanging." + ) from e + self._destructed_ref_idxs.pop(idx_to_release) + + return True + + def _try_release_buffer( + self, idx_to_release: int, timeout: Optional[float] = None + ) -> bool: + """ + Try to release the buffer for the given execution index. + First try to release the native buffer, then try to release the result buffer. + + Args: + idx_to_release: The execution index to release buffers from. + timeout: The maximum time in seconds to wait for the release. + + Returns: + Whether the native buffer or result buffer has been released. + """ + if self._try_release_native_buffer(idx_to_release, timeout): + # Releasing native buffer means the corresponding execution result + # is consumed (and discarded). + self._max_finished_execution_index += 1 + return True + return self._try_release_result_buffer(idx_to_release) + + def _try_release_buffers(self): + """ + Repeatedly release buffer if possible. + + This method starts from _max_finished_execution_index + 1 and tries to release + as many buffers as possible. If a native buffer is released, + _max_finished_execution_index will be incremented. + """ + timeout = self._get_timeout + while True: + start_time = time.monotonic() + if not self._try_release_buffer( + self._max_finished_execution_index + 1, timeout + ): + break + + if timeout != -1: + timeout -= time.monotonic() - start_time + timeout = max(timeout, 0) + + def _clean_up_buffers(self, idx_to_release: int): + """ + Clean up native and result buffers. + + This method: + 1. Tries to release the buffer for the given execution index. + This index is the specific one that requires a clean up, + e.g., right after get() is called or a CompiledDAGRef/CompiledDAGFuture + is destructed. + 2. Tries to release all buffers starting from _max_finished_execution_index + 1. + This step is to clean up buffers that are no longer needed. + + Args: + idx_to_release: The execution index that requires a clean up, + e.g., right after get() is called or a CompiledDAGRef/CompiledDAGFuture + is destructed. + """ + self._try_release_buffer(idx_to_release) + self._try_release_buffers() + + def _execute_until( + self, + execution_index: int, + channel_index: Optional[int] = None, + timeout: Optional[float] = None, + ): + """Repeatedly execute this DAG until the given execution index and + buffer results for all CompiledDagRef's. + If the DAG has already been executed up to the given index, it will do nothing. + + Note: If this comes across execution indices for which the corresponding + CompiledDAGRef's have been destructed, it will release the buffer and not + cache the result. + + Args: + execution_index: The execution index to execute until. + channel_index: The index of the output channel to get the result from. + Channel indexing is consistent with the order of + self.dag_output_channels. None means wrapping results from all output + channels into a single list. + timeout: The maximum time in seconds to wait for the execution. + None means using default timeout (DAGContext.get_timeout), + 0 means immediate timeout (immediate success or timeout without + blocking), -1 means infinite timeout (block indefinitely). + + TODO(rui): catch the case that user holds onto the CompiledDAGRefs + """ + if timeout is None: + timeout = self._get_timeout + while self._max_finished_execution_index < execution_index: + if len(self._result_buffer) >= self._max_buffered_results: + raise RayCgraphCapacityExceeded( + "The compiled graph can't have more than " + f"{self._max_buffered_results} buffered results, and you " + f"currently have {len(self._result_buffer)} buffered results. " + "Call `ray.get()` on CompiledDAGRef's (or await on " + "CompiledDAGFuture's) to retrieve results, or increase " + f"`_max_buffered_results` if buffering is desired, note that " + "this will increase driver memory usage." + ) + start_time = time.monotonic() + + # Fetch results from each output channel up to execution_index and cache + # them separately to enable individual retrieval + # If a CompiledDagRef for a specific execution index has been destructed, + # release the channel buffers for that execution index instead of caching + try: + if not self._try_release_native_buffer( + self._max_finished_execution_index + 1, timeout + ): + result = self._dag_output_fetcher.read(timeout) + self._cache_execution_results( + self._max_finished_execution_index + 1, + result, + ) + # We have either released the native buffer or fetched and + # cached the result buffer, therefore we always increment + # _max_finished_execution_index. + self._max_finished_execution_index += 1 + except RayChannelTimeoutError as e: + raise RayChannelTimeoutError( + "If the execution is expected to take a long time, increase " + f"RAY_CGRAPH_get_timeout which is currently {self._get_timeout} " + "seconds. Otherwise, this may indicate that the execution is " + "hanging." + ) from e + + if timeout != -1: + timeout -= time.monotonic() - start_time + timeout = max(timeout, 0) + + def execute( + self, + *args, + **kwargs, + ) -> Union[CompiledDAGRef, List[CompiledDAGRef]]: + """Execute this DAG using the compiled execution path. + + Args: + args: Args to the InputNode. + kwargs: Kwargs to the InputNode + + Returns: + A list of Channels that can be used to read the DAG result. + + Raises: + RayChannelTimeoutError: If the execution does not complete within + self._submit_timeout seconds. + + NOTE: Not thread-safe due to _execution_index etc. + """ + if self._enable_asyncio: + raise ValueError("Use execute_async if enable_asyncio=True") + + self._get_or_compile() + + self._check_inputs(args, kwargs) + if len(args) == 1 and len(kwargs) == 0: + # When serializing a tuple, the Ray serializer invokes pickle5, which adds + # several microseconds of overhead. One common case for Compiled Graphs is + # passing a single argument (oftentimes of of type `bytes`, which requires + # no serialization). To avoid imposing this overhead on this common case, we + # create a fast path for this case that avoids pickle5. + inp = args[0] + else: + inp = CompiledDAGArgs(args=args, kwargs=kwargs) + + # We want to release any buffers we can at this point based on the + # max_finished_execution_index so that the number of inflight executions + # is up to date. + self._try_release_buffers() + self._raise_if_too_many_inflight_executions() + try: + self._dag_submitter.write(inp, self._submit_timeout) + except RayChannelTimeoutError as e: + raise RayChannelTimeoutError( + "If the execution is expected to take a long time, increase " + f"RAY_CGRAPH_submit_timeout which is currently {self._submit_timeout} " + "seconds. Otherwise, this may indicate that execution is hanging." + ) from e + + self._execution_index += 1 + + if self._returns_list: + ref = [ + CompiledDAGRef(self, self._execution_index, channel_index) + for channel_index in range(len(self.dag_output_channels)) + ] + else: + ref = CompiledDAGRef(self, self._execution_index) + + return ref + + def _check_inputs(self, args: Tuple[Any, ...], kwargs: Dict[str, Any]) -> None: + """ + Helper method to check that the DAG args provided by the user during + execution are valid according to the defined DAG. + """ + if len(args) != self._input_num_positional_args: + raise ValueError( + "dag.execute() or dag.execute_async() must be " + f"called with {self._input_num_positional_args} positional args, got " + f"{len(args)}" + ) + + for kwarg in self._input_kwargs: + if kwarg not in kwargs: + raise ValueError( + "dag.execute() or dag.execute_async() " + f"must be called with kwarg `{kwarg}`" + ) + + async def execute_async( + self, + *args, + **kwargs, + ) -> Union[CompiledDAGFuture, List[CompiledDAGFuture]]: + """Execute this DAG using the compiled execution path. + + NOTE: Not thread-safe. + + Args: + args: Args to the InputNode. + kwargs: Kwargs to the InputNode. + + Returns: + A list of Channels that can be used to read the DAG result. + """ + if not self._enable_asyncio: + raise ValueError("Use execute if enable_asyncio=False") + + self._get_or_compile() + self._check_inputs(args, kwargs) + async with self._dag_submission_lock: + if len(args) == 1 and len(kwargs) == 0: + # When serializing a tuple, the Ray serializer invokes pickle5, which + # adds several microseconds of overhead. One common case for accelerated + # DAGs is passing a single argument (oftentimes of of type `bytes`, + # which requires no serialization). To avoid imposing this overhead on + # this common case, we create a fast path for this case that avoids + # pickle5. + inp = args[0] + else: + inp = CompiledDAGArgs(args=args, kwargs=kwargs) + + self._raise_if_too_many_inflight_executions() + await self._dag_submitter.write(inp) + # Allocate a future that the caller can use to get the result. + fut = asyncio.Future() + await self._fut_queue.put(fut) + + self._execution_index += 1 + + if self._returns_list: + fut = [ + CompiledDAGFuture(self, self._execution_index, fut, channel_index) + for channel_index in range(len(self.dag_output_channels)) + ] + else: + fut = CompiledDAGFuture(self, self._execution_index, fut) + + return fut + + def _visualize_ascii(self) -> str: + """ + Visualize the compiled graph in + ASCII format with directional markers. + + This function generates an ASCII visualization of a Compiled Graph, + where each task node is labeled, + and edges use `<` and `>` markers to show data flow direction. + + This method is called by: + - `compiled_dag.visualize(format="ascii")` + + + + High-Level Algorithm: + - Topological Sorting: Sort nodes topologically to organize + them into layers based on dependencies. + - Grid Initialization: Set up a 2D grid canvas with dimensions based + on the number of layers and the maximum number of nodes per layer. + - Node Placement: Position each node on the grid according to its + layer and relative position within that layer. + Spacing is added for readability, and directional markers (`<` and `>`) + are added to edges to show input/output flow clearly. + + This method should be called + **after** compiling the graph with `experimental_compile()`. + + Returns: + ASCII representation of the CG with Nodes Information, + Edges Information and Graph Built. + + Limitations: + - Note: This is only used for quick visualization for small graphs. + For complex graph (i.e. more than 20 tasks), please use graphviz. + - Scale: Works best for smaller CGs (typically fewer than 20 tasks). + Larger CGs may result in dense, less readable ASCII + outputs due to limited space for node and edge rendering. + - Shape: Ideal for relatively shallow CGs with clear dependency paths. + For deep, highly branched or densely connected CGs, + readability may suffer. + - Edge Overlap: In cases with high fan-out (i.e., nodes with many children) + or fan-in (nodes with many parents), edge lines may intersect or overlap + in the ASCII visualization, potentially obscuring some connections. + - Multi-output Tasks: Multi-output tasks can be visualized, but positioning + may cause line breaks or overlap when a task has multiple outputs that + feed into nodes at varying depths. + + Example: + Basic Visualization: + ```python + # Print the CG structure in ASCII format + print(compiled_dag.visualize(format="ascii")) + ``` + + Example of Ordered Visualization (task is build in order + to reduce line intersection): + ```python + with InputNode() as i: + o1, o2, o3 = a.return_three.bind(i) + o4 = b.echo.bind(o1) + o5 = b.echo.bind(o2) + o6, o7 = b.return_two.bind(o3) + dag = MultiOutputNode([o4, o5, o6, o7]) + + compiled_dag = dag.experimental_compile() + compiled_dag.visualize(format="ascii",view=True) + + + # Output: + # 0:InputNode + # | + # 1:Actor_54777d:return_three + # |---------------------------->|---------------------------->| # noqa + # 2:Output[0] 3:Output[1] 4:Output[2] # noqa + # | | | # noqa + # 5:Actor_c927c9:echo 6:Actor_c927c9:echo 7:Actor_c927c9:return_two # noqa + # | | |---------------------------->| # noqa + # | | 9:Output[0] 10:Output[1] # noqa + # |<----------------------------|-----------------------------|-----------------------------| # noqa + # 8:MultiOutputNode + ``` + + Example of Anti-pattern Visualization (There are intersections): + # We can swtich the nodes ordering to reduce intersections, i.e. swap o2 and o3 + ```python + with InputNode() as i: + o1, o2, o3 = a.return_three.bind(i) + o4 = b.echo.bind(o1) + o5 = b.echo.bind(o3) + o6, o7 = b.return_two.bind(o2) + dag = MultiOutputNode([o4, o5, o6, o7]) + compiled_dag = dag.experimental_compile() + compiled_dag.visualize(format="ascii",view=True) + + # Output (Nodes 5, 7, 9, 10 should connect to Node 8): + # 0:InputNode + # | + # 1:Actor_84835a:return_three + # |---------------------------->|---------------------------->| # noqa + # 2:Output[0] 3:Output[1] 4:Output[2] # noqa + # | | | # noqa + # 5:Actor_02a6a1:echo 6:Actor_02a6a1:return_two 7:Actor_02a6a1:echo # noqa + # | |---------------------------->| # noqa + # | 9:Output[0] 10:Output[1] # noqa + # |<----------------------------------------------------------| # noqa + # 8:MultiOutputNode + ``` + """ + + from ray.dag import ( + InputAttributeNode, + InputNode, + MultiOutputNode, + ClassMethodNode, + DAGNode, + ) + + # Check that the DAG has been compiled + if not hasattr(self, "idx_to_task") or not self.idx_to_task: + raise ValueError( + "The DAG must be compiled before calling 'visualize()'. " + "Please call 'experimental_compile()' first." + ) + + # Check that each CompiledTask has a valid dag_node + for idx, task in self.idx_to_task.items(): + if not hasattr(task, "dag_node") or not isinstance(task.dag_node, DAGNode): + raise ValueError( + f"Task at index {idx} does not have a valid 'dag_node'. " + "Ensure that 'experimental_compile()' completed successfully." + ) + + from collections import defaultdict, deque + + # Create adjacency list representation of the DAG + # Adjacency list for DAG; maps a node index to its downstream nodes. + adj_list: Dict[int, List[int]] = defaultdict(list) + # Indegree count for topological sorting; maps a node index to its indegree. + indegree: Dict[int, int] = defaultdict(int) + + # Tracks whether a node is a multi-output node. + is_multi_output: Dict[int, bool] = defaultdict(bool) + # Maps child node indices to their parent node indices. + child2parent: Dict[int, int] = defaultdict(int) + ascii_visualization = "" + # Node information; maps a node index to its descriptive label. + node_info: Dict[int, str] = {} + # Edge information; tuples of (upstream_index, downstream_index, edge_label). + edge_info: List[Tuple[int, int, str]] = [] + + for idx, task in self.idx_to_task.items(): + dag_node = task.dag_node + label = f"Task {idx} " + + # Determine the type and label of the node + if isinstance(dag_node, InputNode): + label += "InputNode" + elif isinstance(dag_node, InputAttributeNode): + label += f"InputAttributeNode[{dag_node.key}]" + elif isinstance(dag_node, MultiOutputNode): + label += "MultiOutputNode" + elif isinstance(dag_node, ClassMethodNode): + if dag_node.is_class_method_call: + method_name = dag_node.get_method_name() + actor_handle = dag_node._get_actor_handle() + actor_id = ( + actor_handle._actor_id.hex()[:6] if actor_handle else "unknown" + ) + label += f"Actor: {actor_id}... Method: {method_name}" + elif dag_node.is_class_method_output: + label += f"ClassMethodOutputNode[{dag_node.output_idx}]" + else: + label += "ClassMethodNode" + else: + label += type(dag_node).__name__ + + node_info[idx] = label + + for arg_index, arg in enumerate(dag_node.get_args()): + if isinstance(arg, DAGNode): + upstream_task_idx = self.dag_node_to_idx[arg] + + # Get the type hint for this argument + if arg_index < len(task.arg_type_hints): + if task.arg_type_hints[arg_index].requires_accelerator(): + type_hint = "Accelerator" + else: + type_hint = type(task.arg_type_hints[arg_index]).__name__ + else: + type_hint = "UnknownType" + + adj_list[upstream_task_idx].append(idx) + indegree[idx] += 1 + edge_info.append((upstream_task_idx, idx, type_hint)) + + width_adjust = 0 + for upstream_task_idx, child_idx_list in adj_list.items(): + # Mark as multi-output if the node has more than one output path + if len(child_idx_list) > 1: + for child in child_idx_list: + is_multi_output[child] = True + child2parent[child] = upstream_task_idx + width_adjust = max(width_adjust, len(child_idx_list)) + + # Topological sort to determine layers + layers = defaultdict(list) + zero_indegree = deque([idx for idx in self.idx_to_task if indegree[idx] == 0]) + layer_index = 0 + + while zero_indegree: + next_layer = deque() + while zero_indegree: + task_idx = zero_indegree.popleft() + layers[layer_index].append(task_idx) + for downstream in adj_list[task_idx]: + indegree[downstream] -= 1 + if indegree[downstream] == 0: + next_layer.append(downstream) + zero_indegree = next_layer + layer_index += 1 + + # Print detailed node information + ascii_visualization += "Nodes Information:\n" + for idx, info in node_info.items(): + ascii_visualization += f'{idx} [label="{info}"] \n' + + # Print edges + ascii_visualization += "\nEdges Information:\n" + for upstream_task, downstream_task, type_hint in edge_info: + if type_hint == "Accelerator": + edgs_channel = "+++" + else: + edgs_channel = "---" + ascii_visualization += ( + f"{upstream_task} {edgs_channel}>" f" {downstream_task}\n" + ) + + # Add the legend to the output + ascii_visualization += "\nLegend:\n" + ascii_visualization += "+++> : Represents Accelerator-type data channels\n" + ascii_visualization += "---> : Represents Shared Memory data channels\n" + + # Find the maximum width (number of nodes in any layer) + max_width = max(len(layer) for layer in layers.values()) + width_adjust + height = len(layers) + + # Build grid for ASCII visualization + grid = [[" " for _ in range(max_width * 20)] for _ in range(height * 2 - 1)] + + # Place nodes in the grid with more details + task_to_pos = {} + for layer_num, layer_tasks in layers.items(): + layer_y = layer_num * 2 # Every second row is for nodes + for col_num, task_idx in enumerate(layer_tasks): + task = self.idx_to_task[task_idx] + task_info = f"{task_idx}:" + + # Determine if it's an actor method or a regular task + if isinstance(task.dag_node, ClassMethodNode): + if task.dag_node.is_class_method_call: + method_name = task.dag_node.get_method_name() + actor_handle = task.dag_node._get_actor_handle() + actor_id = ( + actor_handle._actor_id.hex()[:6] + if actor_handle + else "unknown" + ) + task_info += f"Actor_{actor_id}:{method_name}" + elif task.dag_node.is_class_method_output: + task_info += f"Output[{task.dag_node.output_idx}]" + else: + task_info += "UnknownMethod" + else: + task_info += type(task.dag_node).__name__ + + adjust_col_num = 0 + if task_idx in is_multi_output: + adjust_col_num = layers[layer_num - 1].index(child2parent[task_idx]) + col_x = (col_num + adjust_col_num) * 30 # Every 30th column for spacing + # Place the task information into the grid + for i, char in enumerate(task_info): + if col_x + i < len(grid[0]): # Ensure we don't overflow the grid + grid[layer_y][col_x + i] = char + + task_to_pos[task_idx] = (layer_y, col_x) + + # Connect the nodes with lines + for upstream_task, downstream_tasks in adj_list.items(): + upstream_y, upstream_x = task_to_pos[upstream_task] + for downstream_task in downstream_tasks: + downstream_y, downstream_x = task_to_pos[downstream_task] + + # Draw vertical line + for y in range(upstream_y + 1, downstream_y): + if grid[y][upstream_x] == " ": + grid[y][upstream_x] = "|" + + # Draw horizontal line with directional arrows + if upstream_x != downstream_x: + for x in range( + min(upstream_x, downstream_x) + 1, + max(upstream_x, downstream_x), + ): + grid[downstream_y - 1][x] = ( + "-" + if grid[downstream_y - 1][x] == " " + else grid[downstream_y - 1][x] + ) + + # Add arrows to indicate flow direction + if downstream_x > upstream_x: + grid[downstream_y - 1][downstream_x - 1] = ">" + else: + grid[downstream_y - 1][downstream_x + 1] = "<" + + # Draw connection to the next task + grid[downstream_y - 1][downstream_x] = "|" + + # Ensure proper multi-output task connection + for idx, task in self.idx_to_task.items(): + if isinstance(task.dag_node, MultiOutputNode): + output_tasks = task.dag_node.get_args() + for i, output_task in enumerate(output_tasks): + if isinstance(output_task, DAGNode): + output_task_idx = self.dag_node_to_idx[output_task] + if output_task_idx in task_to_pos: + output_y, output_x = task_to_pos[output_task_idx] + grid[output_y - 1][output_x] = "|" + + # Convert grid to string for printing + ascii_visualization += "\nGraph Built:\n" + ascii_visualization += "\n".join("".join(row) for row in grid) + + return ascii_visualization + + def get_channel_details( + self, channel: ChannelInterface, downstream_actor_id: str + ) -> str: + """ + Get details about outer and inner channel types and channel ids + based on the channel and the downstream actor ID. + Used for graph visualization. + Args: + channel: The channel to get details for. + downstream_actor_id: The downstream actor ID. + Returns: + A string with details about the channel based on its connection + to the actor provided. + """ + channel_details = type(channel).__name__ + # get outer channel + if channel in self._channel_dict and self._channel_dict[channel] != channel: + channel = self._channel_dict[channel] + channel_details += f"\n{type(channel).__name__}" + if type(channel) is CachedChannel: + channel_details += f", {channel._channel_id[:6]}..." + # get inner channel + if ( + type(channel) is CompositeChannel + and downstream_actor_id in channel._channel_dict + ): + inner_channel = channel._channel_dict[downstream_actor_id] + channel_details += f"\n{type(inner_channel).__name__}" + if type(inner_channel) is IntraProcessChannel: + channel_details += f", {inner_channel._channel_id[:6]}..." + return channel_details + + def visualize( + self, + filename="compiled_graph", + format="png", + view=False, + channel_details=False, + ) -> str: + """ + Visualize the compiled graph by showing tasks and their dependencies. + This method should be called **after** the graph has been compiled using + `experimental_compile()`. + + Args: + filename: For non-ASCII formats, the output file name (without extension). + For ASCII format, the visualization will be printed to the console, + and this argument is ignored. + format: The format of the output file (e.g., 'png', 'pdf', 'ascii'). + view: For non-ASCII formats: Whether to open the file with the default + viewer. For ASCII format: Whether to print the visualization and return + None or return the ascii visualization string directly. + channel_details: If True, adds channel details to edges. + + Returns: + The string representation of the compiled graph. For Graphviz-based formats + (e.g., 'png', 'pdf', 'jpeg'), returns the Graphviz DOT string representation + of the compiled graph. For ASCII format, returns the ASCII string + representation of the compiled graph. + + Raises: + ValueError: If the graph is empty or not properly compiled. + ImportError: If the `graphviz` package is not installed. + + """ + if format == "ascii": + if channel_details: + raise ValueError( + "Parameters 'channel_details' are" + " not compatible with 'ascii' format." + ) + ascii_visualiztion_str = self._visualize_ascii() + if view: + print(ascii_visualiztion_str) + return ascii_visualiztion_str + try: + import graphviz + except ImportError: + raise ImportError( + "Please install graphviz to visualize the compiled graph. " + "You can install it by running `pip install graphviz`." + ) + from ray.dag import ( + InputAttributeNode, + InputNode, + MultiOutputNode, + ClassMethodNode, + DAGNode, + ) + + # Check that the DAG has been compiled + if not hasattr(self, "idx_to_task") or not self.idx_to_task: + raise ValueError( + "The DAG must be compiled before calling 'visualize()'. " + "Please call 'experimental_compile()' first." + ) + + # Check that each CompiledTask has a valid dag_node + for idx, task in self.idx_to_task.items(): + if not hasattr(task, "dag_node") or not isinstance(task.dag_node, DAGNode): + raise ValueError( + f"Task at index {idx} does not have a valid 'dag_node'. " + "Ensure that 'experimental_compile()' completed successfully." + ) + + # Dot file for debugging + dot = graphviz.Digraph(name="compiled_graph", format=format) + # Give every actor a unique color, colors between 24k -> 40k tested as readable + # other colors may be too dark, especially when wrapping back around to 0 + actor_id_to_color = defaultdict( + lambda: f"#{((len(actor_id_to_color) * 2000 + 24000) % 0xFFFFFF):06X}" + ) + # Add nodes with task information + for idx, task in self.idx_to_task.items(): + dag_node = task.dag_node + # Initialize the label and attributes + label = f"Task {idx}\n" + shape = "oval" # Default shape + style = "filled" + fillcolor = "" + + # Handle different types of dag_node + if isinstance(dag_node, InputNode): + label += "InputNode" + shape = "rectangle" + fillcolor = "lightblue" + elif isinstance(dag_node, InputAttributeNode): + label += f"InputAttributeNode[{dag_node.key}]" + shape = "rectangle" + fillcolor = "lightblue" + elif isinstance(dag_node, MultiOutputNode): + label += "MultiOutputNode" + shape = "rectangle" + fillcolor = "yellow" + elif isinstance(dag_node, ClassMethodNode): + if dag_node.is_class_method_call: + # Class Method Call Node + method_name = dag_node.get_method_name() + actor = dag_node._get_actor_handle() + if actor: + class_name = ( + actor._ray_actor_creation_function_descriptor.class_name + ) + actor_id = actor._actor_id.hex() + label += f"Actor: {class_name}\n" + label += f"ID: {actor_id[:6]}...\n" + label += f"Method: {method_name}" + fillcolor = actor_id_to_color[actor_id] + else: + label += f"Method: {method_name}" + fillcolor = "lightgreen" + shape = "oval" + elif dag_node.is_class_method_output: + # Class Method Output Node + label += f"ClassMethodOutputNode[{dag_node.output_idx}]" + shape = "rectangle" + fillcolor = "orange" + else: + # Unexpected ClassMethodNode + label += "ClassMethodNode" + shape = "diamond" + fillcolor = "red" + else: + # Unexpected node type + label += type(dag_node).__name__ + shape = "diamond" + fillcolor = "red" + + # Add the node to the graph with attributes + dot.node(str(idx), label, shape=shape, style=style, fillcolor=fillcolor) + channel_type_str = ( + ( + type(dag_node.type_hint).__name__ + if dag_node.type_hint + else "UnknownType" + ) + + "\n" + if channel_details + else None + ) + + # This logic is built on the assumption that there will only be multiple + # output channels if the task has multiple returns + # case: task with one output + if len(task.output_channels) == 1: + for downstream_node in task.dag_node._downstream_nodes: + downstream_idx = self.dag_node_to_idx[downstream_node] + edge_label = None + if channel_details: + edge_label = channel_type_str + edge_label += self.get_channel_details( + task.output_channels[0], + ( + downstream_node._get_actor_handle()._actor_id.hex() + if type(downstream_node) is ClassMethodNode + else self._proxy_actor._actor_id.hex() + ), + ) + dot.edge(str(idx), str(downstream_idx), label=edge_label) + # case: multi return, output channels connect to class method output nodes + elif len(task.output_channels) > 1: + assert len(task.output_idxs) == len(task.output_channels) + for output_channel, downstream_idx in zip( + task.output_channels, task.output_node_idxs + ): + edge_label = None + if channel_details: + edge_label = channel_type_str + edge_label += self.get_channel_details( + output_channel, + task.dag_node._get_actor_handle()._actor_id.hex(), + ) + dot.edge(str(idx), str(downstream_idx), label=edge_label) + if type(task.dag_node) is InputAttributeNode: + # Add an edge from the InputAttributeNode to the InputNode + dot.edge(str(self.input_task_idx), str(idx)) + dot.render(filename, view=view) + return dot.source + + def _register_input_output_custom_serializer(self): + """ + Register custom serializers for input, input attribute, and output nodes. + """ + assert self.input_task_idx is not None + assert self.output_task_idx is not None + + # Register custom serializers for input node. + input_task = self.idx_to_task[self.input_task_idx] + input_task.dag_node.type_hint.register_custom_serializer() + + # Register custom serializers for input attribute nodes. + for input_attr_task_idx in self.input_attr_task_idxs: + input_attr_task = self.idx_to_task[input_attr_task_idx] + input_attr_task.dag_node.type_hint.register_custom_serializer() + + # Register custom serializers for output nodes. + for output in self.idx_to_task[self.output_task_idx].args: + output.type_hint.register_custom_serializer() + + def teardown(self, kill_actors: bool = False): + """ + Teardown and cancel all actor tasks for this DAG. After this + function returns, the actors should be available to execute new tasks + or compile a new DAG. + + Note: This method is automatically called when the CompiledDAG is destructed + or the script exits. However, this should be explicitly called before compiling + another graph on the same actors. Python may not garbage collect the + CompiledDAG object immediately when you may expect. + """ + if self._is_teardown: + return + + monitor = getattr(self, "_monitor", None) + if monitor is not None: + from ray.dag import DAGContext + + ctx = DAGContext.get_current() + monitor.teardown(kill_actors=kill_actors) + monitor.join(timeout=ctx.teardown_timeout) + # We do not log a warning here if the thread is still alive because + # wait_teardown already logs upon teardown_timeout. + + self._is_teardown = True + + def __del__(self): + self.teardown() + + +@DeveloperAPI +def build_compiled_dag_from_ray_dag( + dag: "ray.dag.DAGNode", + submit_timeout: Optional[float] = None, + buffer_size_bytes: Optional[int] = None, + enable_asyncio: bool = False, + max_inflight_executions: Optional[int] = None, + max_buffered_results: Optional[int] = None, + overlap_gpu_communication: Optional[bool] = None, + default_communicator: Optional[Union[Communicator, str]] = "create", +) -> "CompiledDAG": + compiled_dag = CompiledDAG( + submit_timeout, + buffer_size_bytes, + enable_asyncio, + max_inflight_executions, + max_buffered_results, + overlap_gpu_communication, + default_communicator, + ) + + def _build_compiled_dag(node): + compiled_dag._add_node(node) + return node + + root = dag._find_root() + root.traverse_and_apply(_build_compiled_dag) + compiled_dag._get_or_compile() + global _compiled_dags + _compiled_dags[compiled_dag.get_id()] = compiled_dag + return compiled_dag diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/conftest.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..a350eb5be2d7b70a2647be9df26f53d02fa93a6f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/conftest.py @@ -0,0 +1,16 @@ +import os +import pytest + +import ray + +TEST_NAMESPACE = "ray_dag_test_namespace" + + +@pytest.fixture(scope="session") +def shared_ray_instance(): + # Remove ray address for test ray cluster in case we have + # lingering RAY_ADDRESS="http://127.0.0.1:8265" from previous local job + # submissions. + if "RAY_ADDRESS" in os.environ: + del os.environ["RAY_ADDRESS"] + yield ray.init(num_cpus=16, namespace=TEST_NAMESPACE, log_to_driver=True) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..8e35e1140f1eab2b08d5aca52b81f11f00ef2ad9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/constants.py @@ -0,0 +1,40 @@ +import os + +# Reserved keys used to handle ClassMethodNode in Ray DAG building. +PARENT_CLASS_NODE_KEY = "parent_class_node" +PREV_CLASS_METHOD_CALL_KEY = "prev_class_method_call" +BIND_INDEX_KEY = "bind_index" +IS_CLASS_METHOD_OUTPUT_KEY = "is_class_method_output" + +# Reserved keys used to handle CollectiveOutputNode in Ray DAG building. +COLLECTIVE_OPERATION_KEY = "collective_operation" + +# Reserved key to distinguish DAGNode type and avoid collision with user dict. +DAGNODE_TYPE_KEY = "__dag_node_type__" + +# Feature flag to turn off the deadlock detection. +RAY_CGRAPH_ENABLE_DETECT_DEADLOCK = ( + os.environ.get("RAY_CGRAPH_ENABLE_DETECT_DEADLOCK", "1") == "1" +) + +# Feature flag to turn on profiling. +RAY_CGRAPH_ENABLE_PROFILING = os.environ.get("RAY_CGRAPH_ENABLE_PROFILING", "0") == "1" + +# Feature flag to turn on NVTX (NVIDIA Tools Extension Library) profiling. +# With this flag, Compiled Graph uses nvtx to automatically annotate and profile +# function calls during each actor's execution loop. +# This cannot be used together with RAY_CGRAPH_ENABLE_TORCH_PROFILING. +RAY_CGRAPH_ENABLE_NVTX_PROFILING = ( + os.environ.get("RAY_CGRAPH_ENABLE_NVTX_PROFILING", "0") == "1" +) + +# Feature flag to turn on torch profiling. +# This cannot be used together with RAY_CGRAPH_ENABLE_NVTX_PROFILING. +RAY_CGRAPH_ENABLE_TORCH_PROFILING = ( + os.environ.get("RAY_CGRAPH_ENABLE_TORCH_PROFILING", "0") == "1" +) + +# Feature flag to turn on visualization of the execution schedule. +RAY_CGRAPH_VISUALIZE_SCHEDULE = ( + os.environ.get("RAY_CGRAPH_VISUALIZE_SCHEDULE", "0") == "1" +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/context.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/context.py new file mode 100644 index 0000000000000000000000000000000000000000..37e29521603c8e9271fff2491a3590a2f658f89c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/context.py @@ -0,0 +1,107 @@ +from dataclasses import dataclass +import os +import threading +from typing import Optional +from ray.util.annotations import DeveloperAPI + +# The context singleton on this process. +_default_context: "Optional[DAGContext]" = None +_context_lock = threading.Lock() + +DEFAULT_SUBMIT_TIMEOUT_S = int(os.environ.get("RAY_CGRAPH_submit_timeout", 10)) +DEFAULT_GET_TIMEOUT_S = int(os.environ.get("RAY_CGRAPH_get_timeout", 10)) +DEFAULT_TEARDOWN_TIMEOUT_S = int(os.environ.get("RAY_CGRAPH_teardown_timeout", 30)) +DEFAULT_READ_ITERATION_TIMEOUT_S = float( + os.environ.get("RAY_CGRAPH_read_iteration_timeout_s", 0.1) +) +# Default buffer size is 1MB. +DEFAULT_BUFFER_SIZE_BYTES = int(os.environ.get("RAY_CGRAPH_buffer_size_bytes", 1e6)) +# The default number of in-flight executions that can be submitted before consuming the +# output. +DEFAULT_MAX_INFLIGHT_EXECUTIONS = int( + os.environ.get("RAY_CGRAPH_max_inflight_executions", 10) +) + +# The default number of results that can be buffered at the driver. +DEFAULT_MAX_BUFFERED_RESULTS = int( + os.environ.get("RAY_CGRAPH_max_buffered_results", 1000) +) + +DEFAULT_OVERLAP_GPU_COMMUNICATION = bool( + os.environ.get("RAY_CGRAPH_overlap_gpu_communication", 0) +) + + +@DeveloperAPI +@dataclass +class DAGContext: + """Global settings for Ray DAG. + + You can configure parameters in the DAGContext by setting the environment + variables, `RAY_CGRAPH_` (e.g., `RAY_CGRAPH_buffer_size_bytes`) or Python. + + Examples: + >>> from ray.dag import DAGContext + >>> DAGContext.get_current().buffer_size_bytes + 1000000 + >>> DAGContext.get_current().buffer_size_bytes = 500 + >>> DAGContext.get_current().buffer_size_bytes + 500 + + Args: + submit_timeout: The maximum time in seconds to wait for execute() + calls. + get_timeout: The maximum time in seconds to wait when retrieving + a result from the DAG during `ray.get`. This should be set to a + value higher than the expected time to execute the entire DAG. + teardown_timeout: The maximum time in seconds to wait for the DAG to + cleanly shut down. + read_iteration_timeout: The timeout in seconds for each read iteration + that reads one of the input channels. If the timeout is reached, the + read operation will be interrupted and will try to read the next + input channel. It must be less than or equal to `get_timeout`. + buffer_size_bytes: The initial buffer size in bytes for messages + that can be passed between tasks in the DAG. The buffers will + be automatically resized if larger messages are written to the + channel. + max_inflight_executions: The maximum number of in-flight executions that + can be submitted via `execute` or `execute_async` before consuming + the output using `ray.get()`. If the caller submits more executions, + `RayCgraphCapacityExceeded` is raised. + overlap_gpu_communication: (experimental) Whether to overlap GPU + communication with computation during DAG execution. If True, the + communication and computation can be overlapped, which can improve + the performance of the DAG execution. + """ + + submit_timeout: int = DEFAULT_SUBMIT_TIMEOUT_S + get_timeout: int = DEFAULT_GET_TIMEOUT_S + teardown_timeout: int = DEFAULT_TEARDOWN_TIMEOUT_S + read_iteration_timeout: float = DEFAULT_READ_ITERATION_TIMEOUT_S + buffer_size_bytes: int = DEFAULT_BUFFER_SIZE_BYTES + max_inflight_executions: int = DEFAULT_MAX_INFLIGHT_EXECUTIONS + max_buffered_results: int = DEFAULT_MAX_BUFFERED_RESULTS + overlap_gpu_communication: bool = DEFAULT_OVERLAP_GPU_COMMUNICATION + + def __post_init__(self): + if self.read_iteration_timeout > self.get_timeout: + raise ValueError( + "RAY_CGRAPH_read_iteration_timeout_s " + f"({self.read_iteration_timeout}) must be less than or equal to " + f"RAY_CGRAPH_get_timeout ({self.get_timeout})" + ) + + @staticmethod + def get_current() -> "DAGContext": + """Get or create a singleton context. + + If the context has not yet been created in this process, it will be + initialized with default settings. + """ + global _default_context + + with _context_lock: + if _default_context is None: + _default_context = DAGContext() + + return _default_context diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_node.py new file mode 100644 index 0000000000000000000000000000000000000000..8c43a7bf5f22f2548381ab45ec998d1565d33b38 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_node.py @@ -0,0 +1,706 @@ +import copy +from ray.experimental.channel.auto_transport_type import AutoTransportType +from ray.experimental.channel.torch_tensor_type import TorchTensorType +import ray +from ray.dag.base import DAGNodeBase +from ray.dag.py_obj_scanner import _PyObjScanner +from ray.util.annotations import DeveloperAPI + +from itertools import chain + +from typing import ( + Optional, + Union, + List, + Tuple, + Dict, + Any, + TypeVar, + Callable, + Literal, +) +import uuid +import asyncio + +from ray.dag.compiled_dag_node import build_compiled_dag_from_ray_dag +from ray.experimental.channel import ChannelOutputType +from ray.experimental.channel.communicator import Communicator +from ray.experimental.util.types import Device + +T = TypeVar("T") + + +@DeveloperAPI +class DAGNode(DAGNodeBase): + """Abstract class for a node in a Ray task graph. + + A node has a type (e.g., FunctionNode), data (e.g., function options and + body), arguments (Python values, DAGNodes, and DAGNodes nested within Python + argument values) and options (Ray API .options() used for function, class + or class method) + """ + + def __init__( + self, + args: Tuple[Any], + kwargs: Dict[str, Any], + options: Dict[str, Any], + other_args_to_resolve: Dict[str, Any], + ): + """ + args: + args (Tuple[Any]): Bound node arguments. + ex: func_or_class.bind(1) + kwargs (Dict[str, Any]): Bound node keyword arguments. + ex: func_or_class.bind(a=1) + options (Dict[str, Any]): Bound node options arguments. + ex: func_or_class.options(num_cpus=2) + other_args_to_resolve (Dict[str, Any]): Bound kwargs to resolve + that's specific to subclass implementation without exposing + as args in base class, example: ClassMethodNode + """ + self._bound_args: Tuple[Any] = args or [] + self._bound_kwargs: Dict[str, Any] = kwargs or {} + self._bound_options: Dict[str, Any] = options or {} + self._bound_other_args_to_resolve: Optional[Dict[str, Any]] = ( + other_args_to_resolve or {} + ) + + # The list of nodes that use this DAG node as an argument. + self._downstream_nodes: List["DAGNode"] = [] + + # UUID that is not changed over copies of this node. + self._stable_uuid = uuid.uuid4().hex + + # Indicates whether this DAG node contains nested DAG nodes. + # Nested DAG nodes are allowed in traditional DAGs but not + # in Ray Compiled Graphs, except for MultiOutputNode. + self._args_contain_nested_dag_node = False + + # The list of nodes that this DAG node uses as an argument. + self._upstream_nodes: List["DAGNode"] = self._collect_upstream_nodes() + + # Cached values from last call to execute() + self.cache_from_last_execute = {} + + self._type_hint: ChannelOutputType = ChannelOutputType() + + # If the original type hint is an AutoTransportType, we make a copy + # here when it is resolved to the actual type, as additional debugging + # information. Otherwise, it is None. + self._original_type_hint: Optional[ChannelOutputType] = None + + # Whether this node calls `experimental_compile`. + self.is_cgraph_output_node = False + + def _collect_upstream_nodes(self) -> List["DAGNode"]: + """ + Retrieve upstream nodes and update their downstream dependencies. + + Currently, the DAG assumes that all DAGNodes in `args`, `kwargs`, and + `other_args_to_resolve` are upstream nodes. However, Ray Compiled Graphs + builds the upstream/downstream relationship based only on args. Be cautious + when persisting DAGNodes in `other_args_to_resolve` and kwargs in the future. + + TODO (kevin85421): Currently, the upstream nodes and downstream nodes have + circular references. Therefore, it relies on the garbage collector to clean + them up instead of reference counting. We should consider using weak references + to avoid circular references. + """ + upstream_nodes: List["DAGNode"] = [] + + # Ray Compiled Graphs do not allow nested DAG nodes in arguments. + # Specifically, a DAGNode should not be placed inside any type of + # container. However, we only know if this is a compiled graph + # when calling `experimental_compile`. Therefore, we need to check + # in advance if the arguments contain nested DAG nodes and raise + # an error after compilation. + assert hasattr(self._bound_args, "__iter__") + for arg in self._bound_args: + if isinstance(arg, DAGNode): + upstream_nodes.append(arg) + else: + scanner = _PyObjScanner() + dag_nodes = scanner.find_nodes(arg) + upstream_nodes.extend(dag_nodes) + scanner.clear() + self._args_contain_nested_dag_node = len(dag_nodes) > 0 + + scanner = _PyObjScanner() + other_upstream_nodes: List["DAGNode"] = scanner.find_nodes( + [ + self._bound_kwargs, + self._bound_other_args_to_resolve, + ] + ) + upstream_nodes.extend(other_upstream_nodes) + scanner.clear() + # Update dependencies. + for upstream_node in upstream_nodes: + upstream_node._downstream_nodes.append(self) + return upstream_nodes + + def with_tensor_transport( + self, + transport: Optional[Union[str, Communicator]] = "auto", + device: Literal["default", "cpu", "gpu", "cuda"] = "default", + _static_shape: bool = False, + _direct_return: bool = False, + ): + """ + Configure the torch tensor transport for this node. + + Args: + transport: Specifies the tensor transport mechanism. + - "accelerator": Tensors are communicated using accelerator-specific backends + (e.g., NCCL, XLA, or vendor-provided transport). This is the recommended option + for most use cases, as it supports extensibility and future hardware backends. + - "nccl": Tensors are passed explicitly via NCCL. This option is kept for + backwards compatibility and may be removed in the future. Use "accelerator" + instead unless you have legacy requirements. + - "shm": Tensors are passed via host shared memory and gRPC. Typically used + when accelerator-based transport is unavailable or not suitable. + - "auto" (default): The system automatically selects the appropriate transport + mechanism based on the sender and receiver, usually preferring accelerator-based + transport when available. + device: The target device to use for the tensor transport. + "default": The tensor will maintain its original device placement from the sender + "cpu": The tensor will be explicitly moved to CPU device in the receiver + "gpu" or "cuda": The tensor will be explicitly moved to GPU device in the receiver + _static_shape: A hint indicating whether the shape(s) and dtype(s) + of tensor(s) contained in this value always remain the same + across different executions of the DAG. If this is True, the + transport will be more efficient. + _direct_return: Whether the tensor is sent directly or inside of + other data. If a "nccl" transport is used, this allows the + sender and receiver to eliminate performance overhead from + an additional data transfer. + """ + try: + device = Device(device) + except ValueError: + valid_devices = ", ".join(f"'{d.value}'" for d in Device) + raise ValueError( + f"Invalid device '{device}'. Valid options are: {valid_devices}." + ) + if transport == "auto": + self._type_hint = AutoTransportType( + device=device, + _static_shape=_static_shape, + _direct_return=_direct_return, + ) + elif transport == "nccl": + self._type_hint = TorchTensorType( + transport="accelerator", + device=device, + _static_shape=_static_shape, + _direct_return=_direct_return, + ) + elif transport == "accelerator": + self._type_hint = TorchTensorType( + transport == "accelerator", + device=device, + _static_shape=_static_shape, + _direct_return=_direct_return, + ) + elif transport == "shm": + self._type_hint = TorchTensorType( + device=device, + _static_shape=_static_shape, + _direct_return=_direct_return, + ) + else: + if not isinstance(transport, Communicator): + raise ValueError( + "transport must be 'auto', 'nccl', 'shm', 'accelerator' or " + "a Communicator type" + ) + self._type_hint = TorchTensorType( + transport=transport, + device=device, + _static_shape=_static_shape, + _direct_return=_direct_return, + ) + return self + + @property + def type_hint(self) -> ChannelOutputType: + return self._type_hint + + @type_hint.setter + def type_hint(self, type_hint: ChannelOutputType) -> None: + if isinstance(self._type_hint, AutoTransportType): + self._original_type_hint = self._type_hint + self._type_hint = type_hint + + def get_args(self) -> Tuple[Any]: + """Return the tuple of arguments for this node.""" + + return self._bound_args + + def get_kwargs(self) -> Dict[str, Any]: + """Return the dict of keyword arguments for this node.""" + + return self._bound_kwargs.copy() + + def get_options(self) -> Dict[str, Any]: + """Return the dict of options arguments for this node.""" + + return self._bound_options.copy() + + def get_other_args_to_resolve(self) -> Dict[str, Any]: + """Return the dict of other args to resolve arguments for this node.""" + return self._bound_other_args_to_resolve.copy() + + def get_stable_uuid(self) -> str: + """Return stable uuid for this node. + 1) Generated only once at first instance creation + 2) Stable across pickling, replacement and JSON serialization. + """ + return self._stable_uuid + + async def get_object_refs_from_last_execute(self) -> Dict[str, Any]: + """Gets cached object refs from the last call to execute(). + + After this DAG is executed through execute(), retrieves a map between node + UUID to a reference to the return value of the default executor on that node. + """ + cache = {} + for node_uuid, value in self.cache_from_last_execute.items(): + if isinstance(value, asyncio.Task): + cache[node_uuid] = await value + else: + cache[node_uuid] = value + + return cache + + def clear_cache(self): + self.cache_from_last_execute = {} + + def experimental_compile( + self, + _submit_timeout: Optional[float] = None, + _buffer_size_bytes: Optional[int] = None, + enable_asyncio: bool = False, + _max_inflight_executions: Optional[int] = None, + _max_buffered_results: Optional[int] = None, + _overlap_gpu_communication: Optional[bool] = None, + _default_communicator: Optional[Union[Communicator, str]] = "create", + ) -> "ray.dag.CompiledDAG": + """Compile an accelerated execution path for this DAG. + + Args: + _submit_timeout: The maximum time in seconds to wait for execute() calls. + None means using default timeout, 0 means immediate timeout + (immediate success or timeout without blocking), -1 means + infinite timeout (block indefinitely). + _buffer_size_bytes: The initial buffer size in bytes for messages + that can be passed between tasks in the DAG. The buffers will + be automatically resized if larger messages are written to the + channel. + enable_asyncio: Whether to enable asyncio for this DAG. + _max_inflight_executions: The maximum number of in-flight executions that + can be submitted via `execute` or `execute_async` before consuming + the output using `ray.get()`. If the caller submits more executions, + `RayCgraphCapacityExceeded` is raised. + _max_buffered_results: The maximum number of results that can be + buffered at the driver. If more than this number of results + are buffered, `RayCgraphCapacityExceeded` is raised. Note that + when result corresponding to an execution is retrieved + (by calling `ray.get()` on a `CompiledDAGRef` or + `CompiledDAGRef` or await on a `CompiledDAGFuture`), results + corresponding to earlier executions that have not been retrieved + yet are buffered. + _overlap_gpu_communication: (experimental) Whether to overlap GPU + communication with computation during DAG execution. If True, the + communication and computation can be overlapped, which can improve + the performance of the DAG execution. If None, the default value + will be used. + _default_communicator: The default communicator to use to transfer + tensors. Three types of values are valid. (1) Communicator: + For p2p operations, this is the default communicator + to use for nodes annotated with `with_tensor_transport()` and when + shared memory is not the desired option (e.g., when transport="nccl", + or when transport="auto" for communication between two different GPUs). + For collective operations, this is the default communicator to use + when a custom communicator is not specified. + (2) "create": for each collective operation without a custom communicator + specified, a communicator is created and initialized on its involved actors, + or an already created communicator is reused if the set of actors is the same. + For all p2p operations without a custom communicator specified, it reuses + an already created collective communicator if the p2p actors are a subset. + Otherwise, a new communicator is created. + (3) None: a ValueError will be thrown if a custom communicator is not specified. + + Returns: + A compiled DAG. + """ + from ray.dag import DAGContext + + ctx = DAGContext.get_current() + if _buffer_size_bytes is None: + _buffer_size_bytes = ctx.buffer_size_bytes + + # Validate whether this DAG node has already been compiled. + if self.is_cgraph_output_node: + raise ValueError( + "It is not allowed to call `experimental_compile` on the same DAG " + "object multiple times no matter whether `teardown` is called or not. " + "Please reuse the existing compiled DAG or create a new one." + ) + # Whether this node is an output node in the DAG. We cannot determine + # this in the constructor because the output node is determined when + # `experimental_compile` is called. + self.is_cgraph_output_node = True + return build_compiled_dag_from_ray_dag( + self, + _submit_timeout, + _buffer_size_bytes, + enable_asyncio, + _max_inflight_executions, + _max_buffered_results, + _overlap_gpu_communication, + _default_communicator, + ) + + def execute( + self, *args, _ray_cache_refs: bool = False, **kwargs + ) -> Union[ray.ObjectRef, "ray.actor.ActorHandle"]: + """Execute this DAG using the Ray default executor _execute_impl(). + + Args: + _ray_cache_refs: If true, stores the default executor's return values + on each node in this DAG in a cache. These should be a mix of: + - ray.ObjectRefs pointing to the outputs of method and function nodes + - Serve handles for class nodes + - resolved values representing user input at runtime + """ + + def executor(node): + return node._execute_impl(*args, **kwargs) + + result = self.apply_recursive(executor) + if _ray_cache_refs: + self.cache_from_last_execute = executor.cache + return result + + def _get_toplevel_child_nodes(self) -> List["DAGNode"]: + """Return the list of nodes specified as top-level args. + + For example, in `f.remote(a, [b])`, only `a` is a top-level arg. + + This list of nodes are those that are typically resolved prior to + task execution in Ray. This does not include nodes nested within args. + For that, use ``_get_all_child_nodes()``. + """ + + # we use List instead of Set here because the hash key of the node + # object changes each time we create it. So if using Set here, the + # order of returned children can be different if we create the same + # nodes and dag one more time. + children = [] + for a in self.get_args(): + if isinstance(a, DAGNode): + if a not in children: + children.append(a) + for a in self.get_kwargs().values(): + if isinstance(a, DAGNode): + if a not in children: + children.append(a) + for a in self.get_other_args_to_resolve().values(): + if isinstance(a, DAGNode): + if a not in children: + children.append(a) + return children + + def _get_all_child_nodes(self) -> List["DAGNode"]: + """Return the list of nodes referenced by the args, kwargs, and + args_to_resolve in current node, even they're deeply nested. + + Examples: + f.remote(a, [b]) -> [a, b] + f.remote(a, [b], key={"nested": [c]}) -> [a, b, c] + """ + + scanner = _PyObjScanner() + # we use List instead of Set here, reason explained + # in `_get_toplevel_child_nodes`. + children = [] + for n in scanner.find_nodes( + [ + self._bound_args, + self._bound_kwargs, + self._bound_other_args_to_resolve, + ] + ): + if n not in children: + children.append(n) + scanner.clear() + return children + + def _apply_and_replace_all_child_nodes( + self, fn: "Callable[[DAGNode], T]" + ) -> "DAGNode": + """Apply and replace all immediate child nodes using a given function. + + This is a shallow replacement only. To recursively transform nodes in + the DAG, use ``apply_recursive()``. + + Args: + fn: Callable that will be applied once to each child of this node. + + Returns: + New DAGNode after replacing all child nodes. + """ + + replace_table = {} + # CloudPickler scanner object for current layer of DAGNode. Same + # scanner should be use for a full find & replace cycle. + scanner = _PyObjScanner() + # Find all first-level nested DAGNode children in args. + # Update replacement table and execute the replace. + for node in scanner.find_nodes( + [ + self._bound_args, + self._bound_kwargs, + self._bound_other_args_to_resolve, + ] + ): + if node not in replace_table: + replace_table[node] = fn(node) + new_args, new_kwargs, new_other_args_to_resolve = scanner.replace_nodes( + replace_table + ) + scanner.clear() + + # Return updated copy of self. + return self._copy( + new_args, new_kwargs, self.get_options(), new_other_args_to_resolve + ) + + def apply_recursive(self, fn: "Callable[[DAGNode], T]") -> T: + """Apply callable on each node in this DAG in a bottom-up tree walk. + + Args: + fn: Callable that will be applied once to each node in the + DAG. It will be applied recursively bottom-up, so nodes can + assume the fn has been applied to their args already. + + Returns: + Return type of the fn after application to the tree. + """ + + if not type(fn).__name__ == "_CachingFn": + + class _CachingFn: + def __init__(self, fn): + self.cache = {} + self.fn = fn + self.fn.cache = self.cache + self.input_node_uuid = None + + def __call__(self, node: "DAGNode"): + from ray.dag.input_node import InputNode + + if node._stable_uuid not in self.cache: + self.cache[node._stable_uuid] = self.fn(node) + if isinstance(node, InputNode): + if not self.input_node_uuid: + self.input_node_uuid = node._stable_uuid + elif self.input_node_uuid != node._stable_uuid: + raise AssertionError( + "Each DAG should only have one unique InputNode." + ) + return self.cache[node._stable_uuid] + + fn = _CachingFn(fn) + else: + if self._stable_uuid in fn.cache: + return fn.cache[self._stable_uuid] + + return fn( + self._apply_and_replace_all_child_nodes( + lambda node: node.apply_recursive(fn) + ) + ) + + def traverse_and_apply(self, fn: "Callable[[DAGNode], T]"): + """ + Traverse all nodes in the connected component of the DAG that contains + the `self` node, and apply the given function to each node. + """ + visited = set() + queue = [self] + cgraph_output_node: Optional[DAGNode] = None + + while queue: + node = queue.pop(0) + if node._args_contain_nested_dag_node: + self._raise_nested_dag_node_error(node._bound_args) + + if node not in visited: + if node.is_cgraph_output_node: + # Validate whether there are multiple nodes that call + # `experimental_compile`. + if cgraph_output_node is not None: + raise ValueError( + "The DAG was compiled more than once. The following two " + "nodes call `experimental_compile`: " + f"(1) {cgraph_output_node}, (2) {node}" + ) + cgraph_output_node = node + fn(node) + visited.add(node) + """ + Add all unseen downstream and upstream nodes to the queue. + This function should be called by the root of the DAG. However, + in some invalid cases, some nodes may not be descendants of the + root. Therefore, we also add upstream nodes to the queue so that + a meaningful error message can be raised when the DAG is compiled. + + ``` + with InputNode() as inp: + dag = MultiOutputNode([a1.inc.bind(inp), a2.inc.bind(1)]) + ``` + + In the above example, `a2.inc` is not a descendant of inp. If we only + add downstream nodes to the queue, the `a2.inc` node will not be visited + , and the error message will be hard to understand, such as a key error + in the compiled DAG. + """ + for neighbor in chain.from_iterable( + [node._downstream_nodes, node._upstream_nodes] + ): + if neighbor not in visited: + queue.append(neighbor) + + def _raise_nested_dag_node_error(self, args): + """ + Raise an error for nested DAGNodes in Ray Compiled Graphs. + + Args: + args: The arguments of the DAGNode. + """ + for arg in args: + if isinstance(arg, DAGNode): + continue + else: + scanner = _PyObjScanner() + dag_nodes = scanner.find_nodes([arg]) + scanner.clear() + if len(dag_nodes) > 0: + raise ValueError( + f"Found {len(dag_nodes)} DAGNodes from the arg {arg} " + f"in {self}. Please ensure that the argument is a " + "single DAGNode and that a DAGNode is not allowed to " + "be placed inside any type of container." + ) + raise AssertionError( + "A DAGNode's args should contain nested DAGNodes as args, " + "but none were found during the compilation process. This is a " + "Ray internal error. Please report this issue to the Ray team." + ) + + def _find_root(self) -> "DAGNode": + """ + Return the root node of the DAG. The root node must be an InputNode. + """ + from ray.dag.input_node import InputNode + + node = self + while not isinstance(node, InputNode): + if len(node._upstream_nodes) == 0: + raise ValueError( + "No InputNode found in the DAG: when traversing upwards, " + f"no upstream node was found for {node}." + ) + node = node._upstream_nodes[0] + return node + + def apply_functional( + self, + source_input_list: Any, + predicate_fn: Callable, + apply_fn: Callable, + ): + """ + Apply a given function to DAGNodes in source_input_list, and return + the replaced inputs without mutating or coping any DAGNode. + + Args: + source_input_list: Source inputs to extract and apply function on + all children DAGNode instances. + predicate_fn: Applied on each DAGNode instance found and determine + if we should apply function to it. Can be used to filter node + types. + apply_fn: Function to apply on the node on bound attributes. Example:: + + apply_fn = lambda node: node._get_serve_deployment_handle( + node._deployment, node._bound_other_args_to_resolve + ) + + Returns: + replaced_inputs: Outputs of apply_fn on DAGNodes in + source_input_list that passes predicate_fn. + """ + replace_table = {} + scanner = _PyObjScanner() + for node in scanner.find_nodes(source_input_list): + if predicate_fn(node) and node not in replace_table: + replace_table[node] = apply_fn(node) + + replaced_inputs = scanner.replace_nodes(replace_table) + scanner.clear() + + return replaced_inputs + + def _execute_impl( + self, *args, **kwargs + ) -> Union[ray.ObjectRef, "ray.actor.ActorHandle"]: + """Execute this node, assuming args have been transformed already.""" + raise NotImplementedError + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ) -> "DAGNode": + """Return a copy of this node with the given new args.""" + raise NotImplementedError + + def _copy( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ) -> "DAGNode": + """Return a copy of this node with the given new args.""" + instance = self._copy_impl( + new_args, new_kwargs, new_options, new_other_args_to_resolve + ) + instance._stable_uuid = self._stable_uuid + instance._type_hint = copy.deepcopy(self._type_hint) + instance._original_type_hint = copy.deepcopy(self._original_type_hint) + return instance + + def __getstate__(self): + """Required due to overriding `__getattr__` else pickling fails.""" + return self.__dict__ + + def __setstate__(self, d: Dict[str, Any]): + """Required due to overriding `__getattr__` else pickling fails.""" + self.__dict__.update(d) + + def __getattr__(self, attr: str): + if attr == "bind": + raise AttributeError(f".bind() cannot be used again on {type(self)} ") + elif attr == "remote": + raise AttributeError( + f".remote() cannot be used on {type(self)}. To execute the task " + "graph for this node, use .execute()." + ) + else: + return self.__getattribute__(attr) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_node_operation.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_node_operation.py new file mode 100644 index 0000000000000000000000000000000000000000..52072eec12e98a56efaf359cc73419343a5be911 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_node_operation.py @@ -0,0 +1,853 @@ +from functools import total_ordering +from enum import Enum +from typing import Set, Tuple, List, Dict, Optional +import copy +import logging +import ray +import heapq +from collections import defaultdict + + +logger = logging.getLogger(__name__) + + +class _DAGNodeOperationType(Enum): + """ + There are three types of operations that a DAG node can perform: + 1. READ: Read from an input channel. + 2. COMPUTE: Execute the method corresponding to the node. + 3. WRITE: Write to an output channel. + """ + + READ = "READ" + COMPUTE = "COMPUTE" + WRITE = "WRITE" + + def viz_str(self): + """ + A string representation of the operation type to be used in visualization. + + The result string is a single character because conciseness is preferred. + """ + if self == _DAGNodeOperationType.READ: + return "R" + elif self == _DAGNodeOperationType.COMPUTE: + return "C" + elif self == _DAGNodeOperationType.WRITE: + return "W" + assert False, f"Unknown operation type: {self}" + + +class _DAGNodeOperation: + def __init__( + self, + exec_task_idx: int, + operation_type: _DAGNodeOperationType, + method_name: Optional[str] = None, + ): + """ + Args: + exec_task_idx: The index of the task that this operation belongs to + in the actor's ExecutableTask list. The index is not the same + as bind_index because there may be more tasks bound to an actor + than tasks that appear in the current compiled DAG. + operation_type: The type of operation to perform. + method_name: The name of the method that this operation originates + from. This is only for visualization and debugging purposes. + """ + self.exec_task_idx = exec_task_idx + self.type = operation_type + self.method_name = method_name + + def __repr__(self): + return ( + f"_DAGNodeOperation(" + f"exec_task_idx: {self.exec_task_idx}, " + f"type: {self.type}, " + f"method_name: {self.method_name})" + ) + + def viz_str(self): + """ + A string representation of the node to be used in visualization. + """ + return f"[{self.exec_task_idx}] {self.method_name} {self.type.viz_str()}" + + def __hash__(self): + return hash((self.exec_task_idx, self.type)) + + def __eq__(self, other): + # An operation is uniquely identified by its `exec_task_idx` and type. + # `method_name` is only for debugging purposes. + return self.exec_task_idx == other.exec_task_idx and self.type == other.type + + +@total_ordering +class _DAGOperationGraphNode: + def __init__( + self, + operation: _DAGNodeOperation, + task_idx: int, + actor_handle: "ray.actor.ActorHandle", + requires_accelerator: bool, + ): + """ + _DAGOperationGraphNode represents a node in the DAG operation graph. + It contains information about the node's in-degree, out-degree, edges, + and the operation it performs. + + Args: + operation: The operation that this node performs. The operation + can be a READ, COMPUTE, or WRITE operation. + task_idx: A unique index which can be used to index into + `CompiledDAG.idx_to_task` to get the corresponding task. + actor_handle: The actor handle to which this operation belongs. + requires_accelerator: Whether this operation requires accelerator. + """ + self.operation = operation + self.task_idx = task_idx + self.actor_handle = actor_handle + self.requires_accelerator = requires_accelerator + # The in_edges and out_edges are dicts of tuples to strings. + # Each tuple (the key) contains an integer `task_idx`, which can be + # used to index into `idx_to_task` to get the corresponding task, + # and a `_DAGNodeOperationType`, which can be READ, COMPUTE, or WRITE. + # The string (the value) is the visualization information of the edge, + # it is a tuple of a label of the edge and a boolean indicating whether + # the edge is a control dependency. + self.in_edges: Dict[Tuple[int, _DAGNodeOperationType], Tuple[str, bool]] = {} + self.out_edges: Dict[Tuple[int, _DAGNodeOperationType], Tuple[str, bool]] = {} + # The synchronous nodes are all the nodes that belong to the same accelerator + # operation. Each node is represented by a tuple of its task idx and type. + self.sync_idxs: Set[Tuple[int, _DAGNodeOperationType]] = set() + # The pending synchronous nodes are the nodes that are pending to be executed, + # i.e., their in-degrees are zero. When a synchronous node is pending, it + # will be added to the pending synchronous nodes of all the nodes in the + # accelerator operation. + self.pending_sync_idxs: Set[Tuple[int, _DAGNodeOperationType]] = set() + + def __repr__(self): + return ( + f"_DAGOperationGraphNode(" + f"operation: {self.operation}, " + f"task_idx: {self.task_idx}, " + f"actor_id: {self.actor_handle._ray_actor_id}, " + f"requires_accelerator: {self.requires_accelerator})" + ) + + def __lt__(self, other: "_DAGOperationGraphNode"): + """ + This function defines the order of the nodes in the priority queue used in + `_select_next_nodes`. The priority queue is a min-heap, so the node with + higher priority is considered "less than" the other node. + """ + if self.is_accelerator_op != other.is_accelerator_op: + # When one node is an accelerator operation and the other is not, + # prioritize the accelerator operation. + return self.is_accelerator_op + else: + # When either both nodes are accelerator operations or both nodes + # are not accelerator operations, prioritize the earlier task within + # the same actor and load balance tasks across actors. The tie is + # broken by the `task_idx`. + return (self.operation.exec_task_idx, self.task_idx) < ( + other.operation.exec_task_idx, + other.task_idx, + ) + + def __eq__(self, other: "_DAGOperationGraphNode"): + """ + Two operations are equal only when they have the same `exec_task_idx` and `type` + and belong to the same actor. + """ + return ( + self.actor_handle == other.actor_handle + and self.operation.exec_task_idx == other.operation.exec_task_idx + and self.operation.type == other.operation.type + ) + + def __hash__(self): + """ + An operation is uniquely identified by its `task_idx` and type. + """ + return hash((self.operation, self.task_idx)) + + @property + def in_degree(self) -> int: + return len(self.in_edges) + + @property + def is_ready(self) -> bool: + """ + If a node is not an accelerator operation, it is ready when it has a zero + in-degree. + If it is an accelerator operation, it is ready when all the nodes in the + operation have zero in-degrees. + """ + return self.in_degree == 0 and ( + len(self.pending_sync_idxs) == len(self.sync_idxs) + ) + + @property + def is_read(self) -> bool: + return self.operation.type == _DAGNodeOperationType.READ + + @property + def is_accelerator_read(self) -> bool: + """ + A node is an accelerator read if it is a read node and requires accelerator. + """ + return ( + self.operation.type == _DAGNodeOperationType.READ + and self.requires_accelerator + ) + + @property + def is_accelerator_compute(self) -> bool: + """ + A node is an accelerator compute if it is a compute node and requires accelerator. + """ + return ( + self.operation.type == _DAGNodeOperationType.COMPUTE + and self.requires_accelerator + ) + + @property + def is_accelerator_write(self) -> bool: + """ + A node is an accelerator write if it is a write node and requires accelerator. + """ + return ( + self.operation.type == _DAGNodeOperationType.WRITE + and self.requires_accelerator + ) + + @property + def is_accelerator_op(self) -> bool: + return ( + self.is_accelerator_read + or self.is_accelerator_compute + or self.is_accelerator_write + ) + + def viz_str(self): + """ + A string representation of the node to be used in visualization. + """ + return self.operation.viz_str() + + @property + def _actor_id(self): + return self.actor_handle._ray_actor_id.hex() + + +def _add_edge( + from_node: _DAGOperationGraphNode, + to_node: _DAGOperationGraphNode, + label: str = "", + control_dependency: bool = False, +): + """ + Add an edge from `from_node` to `to_node`. + + Args: + from_node: The node from which the edge originates. + to_node: The node to which the edge points. + label: The label of the edge. This will be used to annotate the edge + in the visualization of the execution schedule. + """ + from_node.out_edges[(to_node.task_idx, to_node.operation.type)] = ( + label, + control_dependency, + ) + to_node.in_edges[(from_node.task_idx, from_node.operation.type)] = ( + label, + control_dependency, + ) + + +def _update_pending_sync_idxs( + graph: Dict[int, Dict[_DAGNodeOperationType, _DAGOperationGraphNode]], + node: _DAGOperationGraphNode, +) -> None: + """ + Update the node as pending for its synchronous nodes. + """ + idx = (node.task_idx, node.operation.type) + for task_idx, op_type in node.sync_idxs: + sync_node = graph[task_idx][op_type] + sync_node.pending_sync_idxs.add(idx) + + +def _push_candidate_node_if_ready( + actor_to_candidates: Dict["ray._raylet.ActorID", List[_DAGOperationGraphNode]], + graph: Dict[int, Dict[_DAGNodeOperationType, _DAGOperationGraphNode]], + node: _DAGOperationGraphNode, +) -> None: + """ + Push the node with a zero in-degree to the candidates if its operation is ready. + If it has synchronous nodes, its accelerator operation is not ready until all + the nodes are pending, then all the nodes will be pushed to the candidates. + """ + assert node.in_degree == 0, "Expected to have a zero in-degree" + # For the accelerator write node, update the in-degrees of the downstream + # accelerator read nodes and update them as pending. This is necessary because + # the data dependency edges between accelerator write and read nodes are only + # updated here. The accelerator P2P operation becomes ready after both the write + # and read nodes are marked as pending. + if node.is_accelerator_write: + for task_idx, op_type in node.out_edges: + read_node = graph[task_idx][op_type] + read_node.in_edges.pop((node.task_idx, node.operation.type)) + assert read_node.is_accelerator_read and len(read_node.in_edges) == 0 + _update_pending_sync_idxs(graph, read_node) + # For the accelerator operation node, update it as pending. + if len(node.sync_idxs) != 0: + _update_pending_sync_idxs(graph, node) + # The accelerator operation is ready when all the nodes have zero in-degrees. + # When the last node in the operation is updated as pending, push all the nodes + # to the candidates. + if node.is_ready: + if len(node.sync_idxs) == 0: + heapq.heappush( + actor_to_candidates[node.actor_handle._actor_id], + node, + ) + else: + for task_idx, op_type in node.sync_idxs: + sync_node = graph[task_idx][op_type] + heapq.heappush( + actor_to_candidates[sync_node.actor_handle._actor_id], + sync_node, + ) + + +def _select_next_nodes( + actor_to_candidates: Dict["ray._raylet.ActorID", List[_DAGOperationGraphNode]], + graph: Dict[int, Dict[_DAGNodeOperationType, _DAGOperationGraphNode]], +) -> Optional[List[_DAGOperationGraphNode]]: + """ + This function selects the next nodes for the topological sort to generate + execution schedule. If there are multiple candidate _DAGOperationGraphNodes, + select the node with the top priority. The priority is defined in + `_DAGOperationGraphNode.__lt__`. + + For the implementation details, we maintain a priority queue for each actor, + where the head of the priority queue is the node with the smallest `exec_task_idx`. + When a node has a zero in-degree, it is added to the corresponding actor's + priority queue. For a node other than an accelerator collective node, it is ready to be + executed if it has a zero in-degree. For an accelerator collective node, it is ready to + be executed when all the nodes in its collective operation have zero in-degrees. + + If a node is an accelerator collective node, it updates the `ready_collective_nodes` of + all the nodes in its collective operation. Unless all the nodes in its collective + group have zero in-degrees, this node is removed from the candidate list. + Eventually, exactly one accelerator collective node from its collective operation is + selected from the candidate list. + + If the selected node is an accelerator write node, select all the downstream accelerator + read nodes. If the selected node is an accelerator collective node, select all the accelerator + compute nodes in its collective operation. + + Args: + actor_to_candidates: A dictionary mapping an actor id to a list of + candidate nodes. The list is maintained as a priority queue, so + the head of the queue, i.e., `candidates[0]`, is the node with + the smallest `bind_index`. + graph: A dictionary mapping the index of a task to a dictionary of its + _DAGOperationGraphNodes for different operations. + + Returns: + A list of _DAGOperationGraphNodes to be placed into the corresponding + execution schedules. + """ + top_priority_node = None + for candidates in actor_to_candidates.values(): + if len(candidates) == 0: + continue + if top_priority_node is None or candidates[0] < top_priority_node: + top_priority_node = candidates[0] + + if top_priority_node is None: + return None + next_nodes = [top_priority_node] + + # Select all the synchronous nodes in the accelerator operation. + if len(top_priority_node.sync_idxs) != 0: + for task_idx, op_type in top_priority_node.sync_idxs: + node = graph[task_idx][op_type] + if node != top_priority_node: + next_nodes.append(node) + + # Remove the selected nodes from the candidates. + for node in next_nodes: + candidates = actor_to_candidates[node.actor_handle._actor_id] + candidates.remove(node) + heapq.heapify(candidates) + + # Remove the selected nodes from the candidates. + for node in next_nodes: + candidates = actor_to_candidates[node.actor_handle._actor_id] + # The accelerator read nodes are not added to the candidates. + if node in candidates: + candidates.remove(node) + heapq.heapify(candidates) + + return next_nodes + + +def _build_dag_node_operation_graph( + idx_to_task: Dict[int, "ray.dag.compiled_dag_node.CompiledTask"], + actor_to_operation_nodes: Dict[ + "ray.actor.ActorHandle", List[List[_DAGOperationGraphNode]] + ], +) -> Dict[int, Dict[_DAGNodeOperationType, _DAGOperationGraphNode]]: + """ + Generate a DAG node operation graph by adding edges based on the + following rules: + + #1 Add edges from READ to COMPUTE, and from COMPUTE to WRITE, which + belong to the same task. + #2 Add an edge from COMPUTE with bind_index i to COMPUTE with bind_index + i+1 if they belong to the same actor. + #3 Add an edge from WRITE of the writer task to READ of the reader task. + + This is the step one of building an execution schedule for each actor. + + Args: + idx_to_task: A dictionary that maps the `task_idx` to the `CompiledTask`. + `CompiledTask` contains information about a DAGNode and its downstream + nodes. + + actor_to_operation_nodes: A dictionary that maps an actor handle to + a list of lists of _DAGOperationGraphNode. For the same actor, the + index of the outer list corresponds to the index of the ExecutableTask + in the list of `executable_tasks` in `actor_to_executable_tasks`. In + the inner list, the order of operations is READ, COMPUTE, and WRITE. + + Returns: + A graph where each node is a _DAGOperationGraphNode. The key is `task_idx`, + the index to retrieve its task from `idx_to_task`, and the value is a + dictionary that maps the _DAGNodeOperationType (READ, COMPUTE, or WRITE) + to the corresponding _DAGOperationGraphNode + """ + assert idx_to_task + graph: Dict[int, Dict[_DAGNodeOperationType, _DAGOperationGraphNode]] = {} + + for _, operation_nodes_list in actor_to_operation_nodes.items(): + prev_compute_node = None + for operation_nodes in operation_nodes_list: + task_idx = operation_nodes[0].task_idx + read_node, compute_node, write_node = ( + operation_nodes[0], + operation_nodes[1], + operation_nodes[2], + ) + # Add edges from READ to COMPUTE, and from COMPUTE to WRITE, which + # belong to the same task. + _add_edge(read_node, compute_node) + _add_edge(compute_node, write_node) + # Add an edge from COMPUTE with `bind_index` i to COMPUTE with + # `bind_index` i+1 if they belong to the same actor. + if prev_compute_node is not None: + _add_edge(prev_compute_node, compute_node, "", True) + prev_compute_node = compute_node + assert task_idx not in graph + graph[task_idx] = { + _DAGNodeOperationType.READ: read_node, + _DAGNodeOperationType.COMPUTE: compute_node, + _DAGNodeOperationType.WRITE: write_node, + } + + # Import `ray.dag` here to avoid circular import. + from ray.dag import ClassMethodNode, CollectiveOutputNode, MultiOutputNode + from ray.dag.collective_node import _CollectiveOperation + + # Add an edge from WRITE of the writer task to READ of the reader task. + # Set synchronous nodes for accelerator P2P operations. + for task_idx, task in idx_to_task.items(): + if not ( + isinstance(task.dag_node, ClassMethodNode) + or isinstance(task.dag_node, CollectiveOutputNode) + ): + # The graph is used to generate an execution schedule for each actor. + # The edge from the InputNode has no impact on the final execution + # schedule. + continue + if ( + isinstance(task.dag_node, ClassMethodNode) + and task.dag_node.is_class_method_output + ): + # Class method output node dependencies are handled at its upstream: + # i.e., class method node + continue + for downstream_task_idx in task.downstream_task_idxs: + downstream_dag_node = idx_to_task[downstream_task_idx].dag_node + if isinstance(downstream_dag_node, MultiOutputNode): + continue + write_node = graph[task_idx][_DAGNodeOperationType.WRITE] + if ( + isinstance(downstream_dag_node, ClassMethodNode) + and downstream_dag_node.is_class_method_output + ): + consumer_idxs = idx_to_task[downstream_task_idx].downstream_task_idxs + for consumer_idx in consumer_idxs: + if consumer_idx in graph: + read_node = graph[consumer_idx][_DAGNodeOperationType.READ] + _add_edge( + write_node, + read_node, + "accelerator" if write_node.requires_accelerator else "shm", + ) + if write_node.requires_accelerator: + idxs = { + (task_idx, _DAGNodeOperationType.WRITE), + (consumer_idx, _DAGNodeOperationType.READ), + } + for node in [write_node, read_node]: + node.sync_idxs.update(idxs) + continue + read_node = graph[downstream_task_idx][_DAGNodeOperationType.READ] + _add_edge( + write_node, + read_node, + "accelerator" if write_node.requires_accelerator else "shm", + ) + if write_node.requires_accelerator: + idxs = { + (task_idx, _DAGNodeOperationType.WRITE), + (downstream_task_idx, _DAGNodeOperationType.READ), + } + for node in [write_node, read_node]: + node.sync_idxs.update(idxs) + + # Set synchronous nodes for accelerator collective operations. + collective_op_to_idxs: Dict[ + _CollectiveOperation, Set[Tuple[int, _DAGNodeOperationType]] + ] = defaultdict(set) + for task_idx, task in idx_to_task.items(): + if ( + isinstance(task.dag_node, CollectiveOutputNode) + and not task.dag_node.is_class_method_output + ): + collective_op_to_idxs[task.dag_node.collective_op].add( + (task_idx, _DAGNodeOperationType.COMPUTE) + ) + for idxs in collective_op_to_idxs.values(): + for task_idx, op_type in idxs: + graph[task_idx][op_type].sync_idxs = idxs + + return graph + + +def _actor_viz_label(actor: "ray.actor.ActorHandle"): + """ + Returns the label of an actor in the visualization of the execution schedule. + + Args: + actor: The actor to be represented. + """ + class_name = actor._ray_actor_creation_function_descriptor.class_name + actor_id = actor._ray_actor_id.hex() + return f"Actor class name: {class_name}\nActor ID: {actor_id}" + + +def _node_viz_id_and_label( + node: _DAGOperationGraphNode, idx: int, optimized_index: int +): + """ + Returns the visualization id and label of a node. The visualization id is unique + across all nodes. + + Args: + node: The node to be represented. + idx: The index of the node in the execution schedule. + optimized_index: The index of the node in the optimized execution schedule. + """ + node_viz_label = node.viz_str() + f" {idx},{optimized_index}" + node_viz_id = f"{node._actor_id}_{node_viz_label}" + return node_viz_id, node_viz_label + + +def _visualize_execution_schedule( + actor_to_execution_schedule: Dict[ + "ray.actor.ActorHandle", List[_DAGOperationGraphNode] + ], + actor_to_overlapped_schedule: Optional[ + Dict["ray.actor.ActorHandle", List[_DAGOperationGraphNode]] + ], + graph: Dict[int, Dict[_DAGNodeOperationType, _DAGOperationGraphNode]], +): + """ + Visualize the execution schedule for each actor. + + The visualization will be saved as a PNG file named `compiled_graph_schedule.png`. + Details of the visualization: # noqa + + Node description format: + [] , + + Node description fields: + operation: is R(READ), C(COMPUTE), or W(WRITE) + orig_index: the index in the original execution schedule + overlap_index: the index in the overlap-communication optimized execution schedule + If this is different from orig_index, the node is highlighted in red color + + Node grouping: + The nodes belonging to the same actor are grouped in the same rectangle + The actor class name and the actor id are shown in the rectangle + + Edges: + black color (without label): data dependency + black color (annotated with "shm"): shared memory channel + blue color (annotated with "accelerator): accelerator channel + dashed edge: control dependency between compute operations + + Args: + actor_to_execution_schedule: A dictionary that maps an actor handle to + the execution schedule which is a list of operation nodes. + actor_to_overlapped_schedule: A dictionary that maps an actor handle to the + optimized execution schedule which is a list of operation nodes. + graph: A graph where each node is a _DAGOperationGraphNode. The key is + `task_idx`, the index to retrieve its task from `idx_to_task`, and + the value is a dictionary that maps the _DAGNodeOperationType (READ, + COMPUTE, or WRITE) to the corresponding _DAGOperationGraphNode. It is + generated by `_build_dag_node_operation_graph`. + """ + try: + import graphviz + except ImportError: + raise ImportError( + "Please install graphviz to visualize the execution schedule. " + "You can install it by running `pip install graphviz`." + ) + + dot = graphviz.Digraph(comment="DAG") + # A dictionary that maps a node to its visualization id + node_to_viz_id: Dict[_DAGOperationGraphNode, str] = {} + + if actor_to_overlapped_schedule is None: + # TODO(rui): make the visualization more concise by only displaying + # the original schedule + actor_to_overlapped_schedule = actor_to_execution_schedule + for actor, execution_nodes in actor_to_execution_schedule.items(): + overlapped_schedule = actor_to_overlapped_schedule[actor] + node_to_optimized_index = { + node: i for i, node in enumerate(overlapped_schedule) + } + + actor_id = actor._ray_actor_id.hex() + with dot.subgraph(name=f"cluster_{actor_id}") as subgraph: + subgraph.attr(rank=actor_id, label=_actor_viz_label(actor)) + for i, node in enumerate(execution_nodes): + optimized_index = node_to_optimized_index.get(node) + node_viz_id, node_viz_label = _node_viz_id_and_label( + node, i, optimized_index + ) + color = "red" if optimized_index != i else "black" + subgraph.node(node_viz_id, node_viz_label, color=color) + node_to_viz_id[node] = node_viz_id + + for actor, execution_nodes in actor_to_execution_schedule.items(): + for i, node in enumerate(execution_nodes): + node_viz_id = node_to_viz_id[node] + for out_edge, viz_info in node.out_edges.items(): + label, control_dependency = viz_info + out_task_idx, out_op_type = out_edge + out_node = graph[out_task_idx][out_op_type] + out_node_viz_id = node_to_viz_id[out_node] + color = "blue" if label == "accelerator" else "black" + style = "dashed" if control_dependency else "solid" + dot.edge( + node_viz_id, out_node_viz_id, label=label, color=color, style=style + ) + + # Add legend + with dot.subgraph(name="cluster_legend") as legend: + legend.attr(label="Legend", labelloc="t", fontsize="20", bgcolor="lightgrey") + + # Single node and its explanation + legend.node("example_node", "[0] bwd C 10,10\n") + explanation = ( + '<' # noqa + '' + '' # noqa + "" + '' + '' # noqa + '' # noqa + '' # noqa + '' # noqa + "" + '' + '' # noqa + '' # noqa + "" + '' + '' # noqa + '' # noqa + '' # noqa + '' # noqa + "
    Node description format:
    [<task_index>] <method_name> <operation> <orig_index>, <overlap_index>
    Node description fields:
    operation: is R(READ), C(COMPUTE), or W(WRITE)
    orig_index: the index in the original execution schedule
    overlap_index: the index in the overlap-communication optimized execution schedule
    If this is different from orig_index, the node is highlighted in red color
    Node grouping:
    The nodes belonging to the same actor are grouped in the same rectangle
    The actor class name and the actor id are shown in the rectangle
    Edges:
    black color (without label): data dependency
    black color (annotated with "shm"): shared memory channel
    blue color (annotated with "accelerator): accelerator channel
    dashed edge: control dependency between compute operations
    >" + ) + + legend.node("example_explanation", explanation, shape="plaintext") + legend.edge("example_node", "example_explanation", style="invis") + + logger.info( + "Writing compiled graph schedule visualization " + "to compiled_graph_schedule.png" + ) + dot.render("compiled_graph_schedule", format="png", view=False) + + +def _generate_actor_to_execution_schedule( + graph: Dict[int, Dict[_DAGNodeOperationType, _DAGOperationGraphNode]], +) -> Dict["ray.actor.ActorHandle", List[_DAGOperationGraphNode]]: + """ + Generate an execution schedule for each actor. The schedule is a list of + operation nodes to be executed. The function uses a topological sort + algorithm to generate the schedule. + + Args: + graph: A graph where each node is a _DAGOperationGraphNode. The key is + `task_idx`, the index to retrieve its task from `idx_to_task`, and + the value is a dictionary that maps the _DAGNodeOperationType (READ, + COMPUTE, or WRITE) to the corresponding _DAGOperationGraphNode. It is + generated by `_build_dag_node_operation_graph`. + + Returns: + actor_to_execution_schedule: A dictionary that maps an actor handle to + the execution schedule which is a list of operation nodes to be + executed. + """ + + # Mapping from the actor handle to the execution schedule which is a list + # of operations to be executed. + actor_to_execution_schedule: Dict[ + "ray.actor.ActorHandle", List[_DAGOperationGraphNode] + ] = defaultdict(list) + + # A dictionary mapping an actor id to a list of candidate nodes. The list + # is maintained as a priority queue, so the head of the queue, i.e., + # `candidates[0]`, is the node with the smallest `bind_index`. + actor_to_candidates: Dict[ + "ray._raylet.ActorID", List[_DAGOperationGraphNode] + ] = defaultdict(list) + for _, node_dict in graph.items(): + for _, node in node_dict.items(): + # A node with a zero in-degree edge means all of its dependencies + # have been satisfied, including both data and control dependencies. + # Therefore, it is a candidate for execution. + if node.in_degree == 0: + _push_candidate_node_if_ready(actor_to_candidates, graph, node) + + visited_nodes = set() + + # Use topological sort algorithm to generate the execution schedule. + while True: + # Select a list of nodes to be executed. There are three cases: + # 1. If a selected node is not an accelerator operation, only itself is returned. + # 2. If a selected node is an accelerator write operation, the corresponding accelerator + # read operations are also returned. + # 3. If a selected node is an accelerator collective operation, all the nodes in + # its collective operation are returned. + nodes = _select_next_nodes(actor_to_candidates, graph) + if nodes is None: + break + # Add the selected nodes to the execution schedule. + for node in nodes: + assert node not in visited_nodes + visited_nodes.add(node) + actor_to_execution_schedule[node.actor_handle].append(node) + # Update the in-degree of the downstream nodes. + for node in nodes: + for out_node_task_idx, out_node_type in node.out_edges: + out_node = graph[out_node_task_idx][out_node_type] + if out_node in visited_nodes: + # If the downstream node is already visited, it has been added + # to the execution schedule. They are the accelerator read nodes in + # case 2. + continue + out_node.in_edges.pop((node.task_idx, node.operation.type)) + if out_node.in_degree == 0: + _push_candidate_node_if_ready(actor_to_candidates, graph, out_node) + assert len(visited_nodes) == len(graph) * 3, "Expected all nodes to be visited" + + return actor_to_execution_schedule + + +def _generate_overlapped_execution_schedule( + actor_to_execution_schedule: Dict[ + "ray.actor.ActorHandle", List[_DAGOperationGraphNode] + ], +) -> Dict["ray.actor.ActorHandle", List[_DAGOperationGraphNode]]: + """ + From an existing execution schedule, generate a new schedule by overlapping + computation and communication. + + Currently, the algorithm generates a new schedule for each actor as follows: + For each accelerator read operation (i.e., recv), scan backwards to find the nearest + compute node to swap with so that the accelerator read operation can be overlapped + with computation. + + Collective operations are not yet supported. + + Args: + actor_to_execution_schedule: A dictionary that maps an actor handle to + the existing execution schedule for the actor. The schedule is a list + is a list of operations to be executed. + + Returns: + A dictionary that maps an actor handle to the overlapped execution schedule + for the actor. + """ + + actor_to_overlapped_schedule: Dict[ + "ray.actor.ActorHandle", List[_DAGOperationGraphNode] + ] = copy.deepcopy(actor_to_execution_schedule) + for overlapped_schedule in actor_to_overlapped_schedule.values(): + for i in range(len(overlapped_schedule)): + if ( + overlapped_schedule[i].operation.type == _DAGNodeOperationType.READ + and overlapped_schedule[i].requires_accelerator + ): + # For each accelerator read operation (i.e., recv), scan backwards + # to find the nearest compute node to swap with so that + # the accelerator read operation can be overlapped with computation. + for j in range(i - 1, -1, -1): + if ( + overlapped_schedule[j].operation.type + == _DAGNodeOperationType.COMPUTE + ): + # Found a desired compute operation, make the swap + accelerator_read_op = overlapped_schedule[i] + prev_ops = overlapped_schedule[j:i] + overlapped_schedule[j + 1 : i + 1] = prev_ops + overlapped_schedule[j] = accelerator_read_op + break + if ( + overlapped_schedule[j].operation.type + == _DAGNodeOperationType.READ + or overlapped_schedule[j].operation.type + == _DAGNodeOperationType.WRITE + ) and overlapped_schedule[j].requires_accelerator: + # Found an accelerator read/write operation, skip the overlap + # optimization to keep relative order of accelerator operations + break + return actor_to_overlapped_schedule + + +def _extract_execution_schedule( + actor_to_execution_schedule: Dict[ + "ray.actor.ActorHandle", List[_DAGOperationGraphNode] + ], +) -> Dict["ray.actor.ActorHandle", List[_DAGNodeOperation]]: + """ + Extract _DAGNodeOperation from _DAGOperationGraphNode in the schedule + and discard unnecessary information. + """ + return { + actor: [node.operation for node in nodes] + for actor, nodes in actor_to_execution_schedule.items() + } diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_operation_future.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_operation_future.py new file mode 100644 index 0000000000000000000000000000000000000000..acfc83d7c1d6dca5c0de4cf6a5c56d27edf1a31e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/dag_operation_future.py @@ -0,0 +1,144 @@ +from abc import ABC, abstractmethod +from typing import Any, Generic, TypeVar, Dict +from ray.util.annotations import DeveloperAPI +from ray.experimental.channel.accelerator_context import AcceleratorContext + + +T = TypeVar("T") + + +@DeveloperAPI +class DAGOperationFuture(ABC, Generic[T]): + """ + A future representing the result of a DAG operation. + + This is an abstraction that is internal to each actor, + and is not exposed to the DAG caller. + """ + + @abstractmethod + def wait(self): + """ + Wait for the future and return the result of the operation. + """ + raise NotImplementedError + + +@DeveloperAPI +class ResolvedFuture(DAGOperationFuture): + """ + A future that is already resolved. Calling `wait()` on this will + immediately return the result without blocking. + """ + + def __init__(self, result): + """ + Initialize a resolved future. + + Args: + result: The result of the future. + """ + self._result = result + + def wait(self): + """ + Wait and immediately return the result. This operation will not block. + """ + return self._result + + +@DeveloperAPI +class GPUFuture(DAGOperationFuture[Any]): + """ + A future for a GPU event on a CUDA stream. + + This future wraps a buffer, and records an event on the given stream + when it is created. When the future is waited on, it makes the current + CUDA stream wait on the event, then returns the buffer. + + The buffer must be a GPU tensor produced by an earlier operation launched + on the given stream, or it could be CPU data. Then the future guarantees + that when the wait() returns, the buffer is ready on the current stream. + + The `wait()` does not block CPU. + """ + + # Caching GPU futures ensures CUDA events associated with futures are properly + # destroyed instead of relying on garbage collection. The CUDA event contained + # in a GPU future is destroyed right before removing the future from the cache. + # The dictionary key is the future ID, which is the task idx of the dag operation + # that produced the future. When a future is created, it is immediately added to + # the cache. When a future has been waited on, it is removed from the cache. + # When adding a future, if its ID is already a key in the cache, the old future + # is removed. This can happen when an exception is thrown in a previous execution + # of the dag, in which case the old future is never waited on. + # Upon dag teardown, all pending futures produced by the dag are removed. + gpu_futures: Dict[int, "GPUFuture"] = {} + + @staticmethod + def add_gpu_future(fut_id: int, fut: "GPUFuture") -> None: + """ + Cache the GPU future. + Args: + fut_id: GPU future ID. + fut: GPU future to be cached. + """ + if fut_id in GPUFuture.gpu_futures: + # The old future was not waited on because of an execution exception. + GPUFuture.gpu_futures.pop(fut_id).destroy_event() + GPUFuture.gpu_futures[fut_id] = fut + + @staticmethod + def remove_gpu_future(fut_id: int) -> None: + """ + Remove the cached GPU future and destroy its CUDA event. + Args: + fut_id: GPU future ID. + """ + if fut_id in GPUFuture.gpu_futures: + GPUFuture.gpu_futures.pop(fut_id).destroy_event() + + def __init__(self, buf: Any, fut_id: int, stream: Any = None): + """ + Initialize a GPU future on the given stream. + + Args: + buf: The buffer to return when the future is resolved. + fut_id: The future ID to cache the future. + stream: The torch stream to record the event on, this event is waited + on when the future is resolved. If None, the current stream is used. + """ + if stream is None: + stream = AcceleratorContext.get().current_stream() + + self._buf = buf + self._event = AcceleratorContext.get().create_event() + self._event.record(stream) + self._fut_id = fut_id + self._waited: bool = False + + # Cache the GPU future such that its CUDA event is properly destroyed. + GPUFuture.add_gpu_future(fut_id, self) + + def wait(self) -> Any: + """ + Wait for the future on the current CUDA stream and return the result from + the GPU operation. This operation does not block CPU. + """ + current_stream = AcceleratorContext.get().current_stream() + if not self._waited: + self._waited = True + current_stream.wait_event(self._event) + # Destroy the CUDA event after it is waited on. + GPUFuture.remove_gpu_future(self._fut_id) + + return self._buf + + def destroy_event(self) -> None: + """ + Destroy the CUDA event associated with this future. + """ + if self._event is None: + return + + self._event = None diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/format_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/format_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1428317da1c37a93800c66d3162ddffa58ad82e8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/format_utils.py @@ -0,0 +1,155 @@ +from ray.dag import DAGNode +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +def get_dag_node_str( + dag_node: DAGNode, + body_line, +): + indent = _get_indentation() + other_args_to_resolve_lines = _get_other_args_to_resolve_lines( + dag_node._bound_other_args_to_resolve + ) + return ( + f"({dag_node.__class__.__name__}, {dag_node._stable_uuid})(\n" + f"{indent}body={body_line}\n" + f"{indent}args={_get_args_lines(dag_node._bound_args)}\n" + f"{indent}kwargs={_get_kwargs_lines(dag_node._bound_kwargs)}\n" + f"{indent}options={_get_options_lines(dag_node._bound_options)}\n" + f"{indent}other_args_to_resolve={other_args_to_resolve_lines}\n" + f")" + ) + + +def _get_indentation(num_spaces=4): + return " " * num_spaces + + +def _get_args_lines(bound_args): + """Pretty prints bounded args of a DAGNode, and recursively handle + DAGNode in list / dict containers. + """ + indent = _get_indentation() + lines = [] + for arg in bound_args: + if isinstance(arg, DAGNode): + node_repr_lines = str(arg).split("\n") + for node_repr_line in node_repr_lines: + lines.append(f"{indent}" + node_repr_line) + elif isinstance(arg, list): + for ele in arg: + node_repr_lines = str(ele).split("\n") + for node_repr_line in node_repr_lines: + lines.append(f"{indent}" + node_repr_line) + elif isinstance(arg, dict): + for _, val in arg.items(): + node_repr_lines = str(val).split("\n") + for node_repr_line in node_repr_lines: + lines.append(f"{indent}" + node_repr_line) + # TODO: (jiaodong) Handle nested containers and other obj types + else: + lines.append(f"{indent}" + str(arg) + ", ") + + if len(lines) == 0: + args_line = "[]" + else: + args_line = "[" + for args in lines: + args_line += f"\n{indent}{args}" + args_line += f"\n{indent}]" + + return args_line + + +def _get_kwargs_lines(bound_kwargs): + """Pretty prints bounded kwargs of a DAGNode, and recursively handle + DAGNode in list / dict containers. + """ + # TODO: (jiaodong) Nits, we're missing keys and indentation was a bit off. + if not bound_kwargs: + return "{}" + indent = _get_indentation() + kwargs_lines = [] + for key, val in bound_kwargs.items(): + if isinstance(val, DAGNode): + node_repr_lines = str(val).split("\n") + for index, node_repr_line in enumerate(node_repr_lines): + if index == 0: + kwargs_lines.append( + f"{indent}{key}:" + f"{indent}" + node_repr_line + ) + else: + kwargs_lines.append(f"{indent}{indent}" + node_repr_line) + + elif isinstance(val, list): + for ele in val: + node_repr_lines = str(ele).split("\n") + for node_repr_line in node_repr_lines: + kwargs_lines.append(f"{indent}" + node_repr_line) + elif isinstance(val, dict): + for _, inner_val in val.items(): + node_repr_lines = str(inner_val).split("\n") + for node_repr_line in node_repr_lines: + kwargs_lines.append(f"{indent}" + node_repr_line) + # TODO: (jiaodong) Handle nested containers and other obj types + else: + kwargs_lines.append(val) + + if len(kwargs_lines) > 0: + kwargs_line = "{" + for line in kwargs_lines: + kwargs_line += f"\n{indent}{line}" + kwargs_line += f"\n{indent}}}" + else: + kwargs_line = "{}" + + return kwargs_line + + +def _get_options_lines(bound_options): + """Pretty prints .options() in DAGNode. Only prints non-empty values.""" + if not bound_options: + return "{}" + indent = _get_indentation() + options_lines = [] + for key, val in bound_options.items(): + if val: + options_lines.append(f"{indent}{key}: " + str(val)) + + options_line = "{" + for line in options_lines: + options_line += f"\n{indent}{line}" + options_line += f"\n{indent}}}" + return options_line + + +def _get_other_args_to_resolve_lines(other_args_to_resolve): + if not other_args_to_resolve: + return "{}" + indent = _get_indentation() + other_args_to_resolve_lines = [] + for key, val in other_args_to_resolve.items(): + if isinstance(val, DAGNode): + node_repr_lines = str(val).split("\n") + for index, node_repr_line in enumerate(node_repr_lines): + if index == 0: + other_args_to_resolve_lines.append( + f"{indent}{key}:" + + f"{indent}" + + "\n" + + f"{indent}{indent}{indent}" + + node_repr_line + ) + else: + other_args_to_resolve_lines.append( + f"{indent}{indent}" + node_repr_line + ) + else: + other_args_to_resolve_lines.append(f"{indent}{key}: " + str(val)) + + other_args_to_resolve_line = "{" + for line in other_args_to_resolve_lines: + other_args_to_resolve_line += f"\n{indent}{line}" + other_args_to_resolve_line += f"\n{indent}}}" + return other_args_to_resolve_line diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/function_node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/function_node.py new file mode 100644 index 0000000000000000000000000000000000000000..4565fcffe8ff3ac8e0f2c4821d27ae6d7d16a4f6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/function_node.py @@ -0,0 +1,60 @@ +from typing import Any, Dict, List + + +import ray +from ray.dag.dag_node import DAGNode +from ray.dag.format_utils import get_dag_node_str +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class FunctionNode(DAGNode): + """Represents a bound task node in a Ray task DAG.""" + + def __init__( + self, + func_body, + func_args, + func_kwargs, + func_options, + other_args_to_resolve=None, + ): + self._body = func_body + super().__init__( + func_args, + func_kwargs, + func_options, + other_args_to_resolve=other_args_to_resolve, + ) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return FunctionNode( + self._body, + new_args, + new_kwargs, + new_options, + other_args_to_resolve=new_other_args_to_resolve, + ) + + def _execute_impl(self, *args, **kwargs): + """Executor of FunctionNode by ray.remote(). + + Args and kwargs are to match base class signature, but not in the + implementation. All args and kwargs should be resolved and replaced + with value in bound_args and bound_kwargs via bottom-up recursion when + current node is executed. + """ + return ( + ray.remote(self._body) + .options(**self._bound_options) + .remote(*self._bound_args, **self._bound_kwargs) + ) + + def __str__(self) -> str: + return get_dag_node_str(self, str(self._body)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/input_node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/input_node.py new file mode 100644 index 0000000000000000000000000000000000000000..83f212e4e58f588081522b084750e03c5476bcde --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/input_node.py @@ -0,0 +1,321 @@ +from typing import Any, Dict, List, Union, Optional + +from ray.dag import DAGNode +from ray.dag.format_utils import get_dag_node_str +from ray.experimental.gradio_utils import type_to_string +from ray.util.annotations import DeveloperAPI + +IN_CONTEXT_MANAGER = "__in_context_manager__" + + +@DeveloperAPI +class InputNode(DAGNode): + r"""Ray dag node used in DAG building API to mark entrypoints of a DAG. + + Should only be function or class method. A DAG can have multiple + entrypoints, but only one instance of InputNode exists per DAG, shared + among all DAGNodes. + + Example: + + .. code-block:: + + m1.forward + / \ + dag_input ensemble -> dag_output + \ / + m2.forward + + In this pipeline, each user input is broadcasted to both m1.forward and + m2.forward as first stop of the DAG, and authored like + + .. code-block:: python + + import ray + + @ray.remote + class Model: + def __init__(self, val): + self.val = val + def forward(self, input): + return self.val * input + + @ray.remote + def combine(a, b): + return a + b + + with InputNode() as dag_input: + m1 = Model.bind(1) + m2 = Model.bind(2) + m1_output = m1.forward.bind(dag_input[0]) + m2_output = m2.forward.bind(dag_input.x) + ray_dag = combine.bind(m1_output, m2_output) + + # Pass mix of args and kwargs as input. + ray_dag.execute(1, x=2) # 1 sent to m1, 2 sent to m2 + + # Alternatively user can also pass single data object, list or dict + # and access them via list index, object attribute or dict key str. + ray_dag.execute(UserDataObject(m1=1, m2=2)) + # dag_input.m1, dag_input.m2 + ray_dag.execute([1, 2]) + # dag_input[0], dag_input[1] + ray_dag.execute({"m1": 1, "m2": 2}) + # dag_input["m1"], dag_input["m2"] + """ + + def __init__( + self, + *args, + input_type: Optional[Union[type, Dict[Union[int, str], type]]] = None, + _other_args_to_resolve=None, + **kwargs, + ): + """InputNode should only take attributes of validating and converting + input data rather than the input data itself. User input should be + provided via `ray_dag.execute(user_input)`. + + Args: + input_type: Describes the data type of inputs user will be giving. + - if given through singular InputNode: type of InputNode + - if given through InputAttributeNodes: map of key -> type + Used when deciding what Gradio block to represent the input nodes with. + _other_args_to_resolve: Internal only to keep InputNode's execution + context throughput pickling, replacement and serialization. + User should not use or pass this field. + """ + if len(args) != 0 or len(kwargs) != 0: + raise ValueError("InputNode should not take any args or kwargs.") + + self.input_attribute_nodes = {} + + self.input_type = input_type + if input_type is not None and isinstance(input_type, type): + if _other_args_to_resolve is None: + _other_args_to_resolve = {} + _other_args_to_resolve["result_type_string"] = type_to_string(input_type) + + super().__init__([], {}, {}, other_args_to_resolve=_other_args_to_resolve) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return InputNode(_other_args_to_resolve=new_other_args_to_resolve) + + def _execute_impl(self, *args, **kwargs): + """Executor of InputNode.""" + # Catch and assert singleton context at dag execution time. + assert self._in_context_manager(), ( + "InputNode is a singleton instance that should be only used in " + "context manager for dag building and execution. See the docstring " + "of class InputNode for examples." + ) + # If user only passed in one value, for simplicity we just return it. + if len(args) == 1 and len(kwargs) == 0: + return args[0] + + return DAGInputData(*args, **kwargs) + + def _in_context_manager(self) -> bool: + """Return if InputNode is created in context manager.""" + if ( + not self._bound_other_args_to_resolve + or IN_CONTEXT_MANAGER not in self._bound_other_args_to_resolve + ): + return False + else: + return self._bound_other_args_to_resolve[IN_CONTEXT_MANAGER] + + def set_context(self, key: str, val: Any): + """Set field in parent DAGNode attribute that can be resolved in both + pickle and JSON serialization + """ + self._bound_other_args_to_resolve[key] = val + + def __str__(self) -> str: + return get_dag_node_str(self, "__InputNode__") + + def __getattr__(self, key: str): + assert isinstance( + key, str + ), "Please only access dag input attributes with str key." + if key not in self.input_attribute_nodes: + self.input_attribute_nodes[key] = InputAttributeNode( + self, key, "__getattr__" + ) + return self.input_attribute_nodes[key] + + def __getitem__(self, key: Union[int, str]) -> Any: + assert isinstance(key, (str, int)), ( + "Please only use int index or str as first-level key to " + "access fields of dag input." + ) + + input_type = None + if self.input_type is not None and key in self.input_type: + input_type = type_to_string(self.input_type[key]) + + if key not in self.input_attribute_nodes: + self.input_attribute_nodes[key] = InputAttributeNode( + self, key, "__getitem__", input_type + ) + return self.input_attribute_nodes[key] + + def __enter__(self): + self.set_context(IN_CONTEXT_MANAGER, True) + return self + + def __exit__(self, *args): + pass + + def get_result_type(self) -> str: + """Get type of the output of this DAGNode. + + Generated by ray.experimental.gradio_utils.type_to_string(). + """ + if "result_type_string" in self._bound_other_args_to_resolve: + return self._bound_other_args_to_resolve["result_type_string"] + + +@DeveloperAPI +class InputAttributeNode(DAGNode): + """Represents partial access of user input based on an index (int), + object attribute or dict key (str). + + Examples: + + .. code-block:: python + + with InputNode() as dag_input: + a = dag_input[0] + b = dag_input.x + ray_dag = add.bind(a, b) + + # This makes a = 1 and b = 2 + ray_dag.execute(1, x=2) + + with InputNode() as dag_input: + a = dag_input[0] + b = dag_input[1] + ray_dag = add.bind(a, b) + + # This makes a = 2 and b = 3 + ray_dag.execute(2, 3) + + # Alternatively, you can input a single object + # and the inputs are automatically indexed from the object: + # This makes a = 2 and b = 3 + ray_dag.execute([2, 3]) + """ + + def __init__( + self, + dag_input_node: InputNode, + key: Union[int, str], + accessor_method: str, + input_type: str = None, + ): + self._dag_input_node = dag_input_node + self._key = key + self._accessor_method = accessor_method + super().__init__( + [], + {}, + {}, + { + "dag_input_node": dag_input_node, + "key": key, + "accessor_method": accessor_method, + # Type of the input tied to this node. Used by + # gradio_visualize_graph.GraphVisualizer to determine which Gradio + # component should be used for this node. + "result_type_string": input_type, + }, + ) + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ): + return InputAttributeNode( + new_other_args_to_resolve["dag_input_node"], + new_other_args_to_resolve["key"], + new_other_args_to_resolve["accessor_method"], + new_other_args_to_resolve["result_type_string"], + ) + + def _execute_impl(self, *args, **kwargs): + """Executor of InputAttributeNode. + + Args and kwargs are to match base class signature, but not in the + implementation. All args and kwargs should be resolved and replaced + with value in bound_args and bound_kwargs via bottom-up recursion when + current node is executed. + """ + + if isinstance(self._dag_input_node, DAGInputData): + return self._dag_input_node[self._key] + else: + # dag.execute() is called with only one arg, thus when an + # InputAttributeNode is executed, its dependent InputNode is + # resolved with original user input python object. + user_input_python_object = self._dag_input_node + if isinstance(self._key, str): + if self._accessor_method == "__getitem__": + return user_input_python_object[self._key] + elif self._accessor_method == "__getattr__": + return getattr(user_input_python_object, self._key) + elif isinstance(self._key, int): + return user_input_python_object[self._key] + else: + raise ValueError( + "Please only use int index or str as first-level key to " + "access fields of dag input." + ) + + def __str__(self) -> str: + return get_dag_node_str(self, f'["{self._key}"]') + + def get_result_type(self) -> str: + """Get type of the output of this DAGNode. + + Generated by ray.experimental.gradio_utils.type_to_string(). + """ + if "result_type_string" in self._bound_other_args_to_resolve: + return self._bound_other_args_to_resolve["result_type_string"] + + @property + def key(self) -> Union[int, str]: + return self._key + + +@DeveloperAPI +class DAGInputData: + """If user passed multiple args and kwargs directly to dag.execute(), we + generate this wrapper for all user inputs as one object, accessible via + list index or object attribute key. + """ + + def __init__(self, *args, **kwargs): + self._args = list(args) + self._kwargs = kwargs + + def __getitem__(self, key: Union[int, str]) -> Any: + if isinstance(key, int): + # Access list args by index. + return self._args[key] + elif isinstance(key, str): + # Access kwarg by key. + return self._kwargs[key] + else: + raise ValueError( + "Please only use int index or str as first-level key to " + "access fields of dag input." + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/output_node.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/output_node.py new file mode 100644 index 0000000000000000000000000000000000000000..f9abdf1643e092bcfc030b4855d6ebd86b3355ae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/output_node.py @@ -0,0 +1,45 @@ +import ray +from typing import Any, Dict, List, Union, Tuple + +from ray.dag import DAGNode +from ray.dag.format_utils import get_dag_node_str +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class MultiOutputNode(DAGNode): + """Ray dag node used in DAG building API to mark the endpoint of DAG""" + + def __init__( + self, + args: Union[List[DAGNode], Tuple[DAGNode]], + other_args_to_resolve: Dict[str, Any] = None, + ): + if isinstance(args, tuple): + args = list(args) + if not isinstance(args, list): + raise ValueError(f"Invalid input type for `args`, {type(args)}.") + super().__init__( + args, + {}, + {}, + other_args_to_resolve=other_args_to_resolve or {}, + ) + + def _execute_impl( + self, *args, **kwargs + ) -> Union[ray.ObjectRef, "ray.actor.ActorHandle"]: + return self._bound_args + + def _copy_impl( + self, + new_args: List[Any], + new_kwargs: Dict[str, Any], + new_options: Dict[str, Any], + new_other_args_to_resolve: Dict[str, Any], + ) -> "DAGNode": + """Return a copy of this node with the given new args.""" + return MultiOutputNode(new_args, new_other_args_to_resolve) + + def __str__(self) -> str: + return get_dag_node_str(self, "__MultiOutputNode__") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/py_obj_scanner.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/py_obj_scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..6bd6b94ab535bd485d06989ec686da36955788f4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/py_obj_scanner.py @@ -0,0 +1,105 @@ +import io +from typing import Any, Dict, Generic, List, Tuple, Type, TypeVar, Union + +import pickle # noqa: F401 + +import ray +from ray.dag.base import DAGNodeBase + + +# Used in deserialization hooks to reference scanner instances. +_instances: Dict[int, "_PyObjScanner"] = {} + +# Generic types for the scanner to transform from and to. +SourceType = TypeVar("SourceType") +TransformedType = TypeVar("TransformedType") + + +def _get_node(instance_id: int, node_index: int) -> SourceType: + """Get the node instance. + + Note: This function should be static and globally importable, + otherwise the serialization overhead would be very significant. + """ + return _instances[instance_id]._replace_index(node_index) + + +class _PyObjScanner(ray.cloudpickle.CloudPickler, Generic[SourceType, TransformedType]): + """Utility to find and replace the `source_type` in Python objects. + + `source_type` can either be a single type or a tuple of multiple types. + + The caller must first call `find_nodes()`, then compute a replacement table and + pass it to `replace_nodes`. + + This uses cloudpickle under the hood, so all sub-objects that are not `source_type` + must be serializable. + + Args: + source_type: the type(s) of object to find and replace. Default to DAGNodeBase. + """ + + def __init__(self, source_type: Union[Type, Tuple] = DAGNodeBase): + self.source_type = source_type + # Buffer to keep intermediate serialized state. + self._buf = io.BytesIO() + # List of top-level SourceType found during the serialization pass. + self._found = None + # List of other objects found during the serialization pass. + # This is used to store references to objects so they won't be + # serialized by cloudpickle. + self._objects = [] + # Replacement table to consult during deserialization. + self._replace_table: Dict[SourceType, TransformedType] = None + _instances[id(self)] = self + super().__init__(self._buf) + + def reducer_override(self, obj): + """Hook for reducing objects. + + Objects of `self.source_type` are saved to `self._found` and a global map so + they can later be replaced. + + All other objects fall back to the default `CloudPickler` serialization. + """ + if isinstance(obj, self.source_type): + index = len(self._found) + self._found.append(obj) + return _get_node, (id(self), index) + + return super().reducer_override(obj) + + def find_nodes(self, obj: Any) -> List[SourceType]: + """ + Serialize `obj` and store all instances of `source_type` found in `_found`. + + Args: + obj: The object to scan for `source_type`. + Returns: + A list of all instances of `source_type` found in `obj`. + """ + assert ( + self._found is None + ), "find_nodes cannot be called twice on the same PyObjScanner instance." + self._found = [] + self._objects = [] + self.dump(obj) + return self._found + + def replace_nodes(self, table: Dict[SourceType, TransformedType]) -> Any: + """Replace previously found DAGNodes per the given table.""" + assert self._found is not None, "find_nodes must be called first" + self._replace_table = table + self._buf.seek(0) + return pickle.load(self._buf) + + def _replace_index(self, i: int) -> SourceType: + return self._replace_table[self._found[i]] + + def clear(self): + """Clear the scanner from the _instances""" + if id(self) in _instances: + del _instances[id(self)] + + def __del__(self): + self.clear() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ce96b3c27a8aabc060901e75f4a675c943fa18c1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/utils.py @@ -0,0 +1,66 @@ +from typing import Dict + +from ray.dag import ( + DAGNode, + InputNode, + InputAttributeNode, + FunctionNode, + ClassNode, + ClassMethodNode, + MultiOutputNode, +) + + +class _DAGNodeNameGenerator(object): + """ + Generate unique suffix for each given Node in the DAG. + Apply monotonic increasing id suffix for duplicated names. + """ + + def __init__(self): + self.name_to_suffix: Dict[str, int] = dict() + + def get_node_name(self, node: DAGNode): + # InputNode should be unique. + if isinstance(node, InputNode): + return "INPUT_NODE" + if isinstance(node, MultiOutputNode): + return "MultiOutputNode" + # InputAttributeNode suffixes should match the user-defined key. + elif isinstance(node, InputAttributeNode): + return f"INPUT_ATTRIBUTE_NODE_{node._key}" + + # As class, method, and function nodes may have duplicated names, + # generate unique suffixes for such nodes. + if isinstance(node, ClassMethodNode): + node_name = node.get_options().get("name", None) or node._method_name + elif isinstance(node, (ClassNode, FunctionNode)): + node_name = node.get_options().get("name", None) or node._body.__name__ + # we use instance class name check here to avoid importing ServeNodes as + # serve components are not included in Ray Core. + elif type(node).__name__ in ("DeploymentNode", "DeploymentFunctionNode"): + node_name = node.get_deployment_name() + elif type(node).__name__ == "DeploymentFunctionExecutorNode": + node_name = node._deployment_function_handle.deployment_name + else: + raise ValueError( + "get_node_name() should only be called on DAGNode instances." + ) + + if node_name not in self.name_to_suffix: + self.name_to_suffix[node_name] = 0 + return node_name + else: + self.name_to_suffix[node_name] += 1 + suffix_num = self.name_to_suffix[node_name] + + return f"{node_name}_{suffix_num}" + + def reset(self): + self.name_to_suffix = dict() + + def __enter__(self): + return self + + def __exit__(self, *args): + self.reset() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/vis_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/vis_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c5a3b5cbc0962f72a640f1374025503bf79c262c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dag/vis_utils.py @@ -0,0 +1,115 @@ +from ray.dag import DAGNode + +import os +import tempfile + +from ray.dag.utils import _DAGNodeNameGenerator +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +def plot(dag: DAGNode, to_file=None): + if to_file is None: + tmp_file = tempfile.NamedTemporaryFile(suffix=".png") + to_file = tmp_file.name + extension = "png" + else: + _, extension = os.path.splitext(to_file) + if not extension: + extension = "png" + else: + extension = extension[1:] + + graph = _dag_to_dot(dag) + graph.write(to_file, format=extension) + + # Render the image directly if running inside a Jupyter notebook + try: + from IPython import display + + return display.Image(filename=to_file) + except ImportError: + pass + + # close temp file if needed + try: + tmp_file.close() + except NameError: + pass + + +def _check_pydot_and_graphviz(): + """Check if pydot and graphviz are installed. + + pydot and graphviz are required for plotting. We check this + during runtime rather than adding them to Ray dependencies. + + """ + try: + import pydot + except ImportError: + raise ImportError( + "pydot is required to plot DAG, install it with `pip install pydot`." + ) + try: + pydot.Dot.create(pydot.Dot()) + except (OSError, pydot.InvocationException): + raise ImportError( + "graphviz is required to plot DAG, " + "download it from https://graphviz.gitlab.io/download/" + ) + + +def _get_nodes_and_edges(dag: DAGNode): + """Get all unique nodes and edges in the DAG. + + A basic dfs with memorization to get all unique nodes + and edges in the DAG. + Unique nodes will be used to generate unique names, + while edges will be used to construct the graph. + """ + + edges = [] + nodes = [] + + def _dfs(node): + nodes.append(node) + for child_node in node._get_all_child_nodes(): + edges.append((child_node, node)) + return node + + dag.apply_recursive(_dfs) + return nodes, edges + + +def _dag_to_dot(dag: DAGNode): + """Create a Dot graph from dag. + + TODO(lchu): + 1. add more Dot configs in kwargs, + e.g. rankdir, alignment, etc. + 2. add more contents to graph, + e.g. args, kwargs and options of each node + + """ + # Step 0: check dependencies and init graph + _check_pydot_and_graphviz() + import pydot + + graph = pydot.Dot(rankdir="LR") + + # Step 1: generate unique name for each node in dag + nodes, edges = _get_nodes_and_edges(dag) + name_generator = _DAGNodeNameGenerator() + node_names = {} + for node in nodes: + node_names[node] = name_generator.get_node_name(node) + + # Step 2: create graph with all the edges + for edge in edges: + graph.add_edge(pydot.Edge(node_names[edge[0]], node_names[edge[1]])) + # if there is only one node + if len(nodes) == 1 and len(edges) == 0: + graph.add_node(pydot.Node(node_names[nodes[0]])) + + return graph diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/agent.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6513342d175a918827a5de90d0364d2f890a31 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/agent.py @@ -0,0 +1,454 @@ +import argparse +import asyncio +import json +import logging +import os +import signal +import sys + +import ray._private.ray_constants as ray_constants +import ray.dashboard.consts as dashboard_consts +import ray.dashboard.utils as dashboard_utils +from ray._common.utils import get_or_create_event_loop +from ray._private import logging_utils +from ray._private.process_watcher import create_check_raylet_task +from ray._private.ray_constants import AGENT_GRPC_MAX_MESSAGE_LENGTH +from ray._private.ray_logging import setup_component_logger +from ray._raylet import GcsClient + +logger = logging.getLogger(__name__) + + +class DashboardAgent: + def __init__( + self, + node_ip_address, + dashboard_agent_port, + gcs_address, + cluster_id_hex, + minimal, + metrics_export_port=None, + node_manager_port=None, + listen_port=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT, + disable_metrics_collection: bool = False, + *, # the following are required kwargs + object_store_name: str, + raylet_name: str, + log_dir: str, + temp_dir: str, + session_dir: str, + session_name: str, + ): + """Initialize the DashboardAgent object.""" + # Public attributes are accessible for all agent modules. + assert node_ip_address is not None + self.ip = node_ip_address + self.minimal = minimal + + assert gcs_address is not None + self.gcs_address = gcs_address + self.cluster_id_hex = cluster_id_hex + + self.temp_dir = temp_dir + self.session_dir = session_dir + self.log_dir = log_dir + self.dashboard_agent_port = dashboard_agent_port + self.metrics_export_port = metrics_export_port + self.node_manager_port = node_manager_port + self.listen_port = listen_port + self.object_store_name = object_store_name + self.raylet_name = raylet_name + self.node_id = os.environ["RAY_NODE_ID"] + self.metrics_collection_disabled = disable_metrics_collection + self.session_name = session_name + + # grpc server is None in mininal. + self.server = None + # http_server is None in minimal. + self.http_server = None + + # Used by the agent and sub-modules. + self.gcs_client = GcsClient( + address=self.gcs_address, + cluster_id=self.cluster_id_hex, + ) + + if not self.minimal: + self._init_non_minimal() + + def _init_non_minimal(self): + from grpc import aio as aiogrpc + + from ray._private.tls_utils import add_port_to_grpc_server + from ray.dashboard.http_server_agent import HttpServerAgent + + # We would want to suppress deprecating warnings from aiogrpc library + # with the usage of asyncio.get_event_loop() in python version >=3.10 + # This could be removed once https://github.com/grpc/grpc/issues/32526 + # is released, and we used higher versions of grpcio that that. + if sys.version_info.major >= 3 and sys.version_info.minor >= 10: + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + aiogrpc.init_grpc_aio() + else: + aiogrpc.init_grpc_aio() + + self.server = aiogrpc.server( + options=( + ("grpc.so_reuseport", 0), + ( + "grpc.max_send_message_length", + AGENT_GRPC_MAX_MESSAGE_LENGTH, + ), # noqa + ( + "grpc.max_receive_message_length", + AGENT_GRPC_MAX_MESSAGE_LENGTH, + ), + ) # noqa + ) + grpc_ip = "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0" + try: + self.grpc_port = add_port_to_grpc_server( + self.server, f"{grpc_ip}:{self.dashboard_agent_port}" + ) + except Exception: + # TODO(SongGuyang): Catch the exception here because there is + # port conflict issue which brought from static port. We should + # remove this after we find better port resolution. + logger.exception( + "Failed to add port to grpc server. Agent will stay alive but " + "disable the grpc service." + ) + self.server = None + self.grpc_port = None + else: + logger.info("Dashboard agent grpc address: %s:%s", grpc_ip, self.grpc_port) + + # If the agent is not minimal it should start the http server + # to communicate with the dashboard in a head node. + # Http server is not started in the minimal version because + # it requires additional dependencies that are not + # included in the minimal ray package. + self.http_server = HttpServerAgent(self.ip, self.listen_port) + + def _load_modules(self): + """Load dashboard agent modules.""" + modules = [] + agent_cls_list = dashboard_utils.get_all_modules( + dashboard_utils.DashboardAgentModule + ) + for cls in agent_cls_list: + logger.info( + "Loading %s: %s", dashboard_utils.DashboardAgentModule.__name__, cls + ) + c = cls(self) + modules.append(c) + logger.info("Loaded %d modules.", len(modules)) + return modules + + @property + def http_session(self): + assert ( + self.http_server + ), "Accessing unsupported API (HttpServerAgent) in a minimal ray." + return self.http_server.http_session + + def get_node_id(self) -> str: + return self.node_id + + async def run(self): + # Start a grpc asyncio server. + if self.server: + await self.server.start() + + modules = self._load_modules() + + launch_http_server = True + if self.http_server: + try: + await self.http_server.start(modules) + except Exception as e: + # TODO(kevin85421): We should fail the agent if the HTTP server + # fails to start to avoid hiding the root cause. However, + # agent processes are not cleaned up correctly after some tests + # finish. If we fail the agent, the CI will always fail until + # we fix the leak. + logger.exception( + f"Failed to start HTTP server with exception: {e}. " + "The agent will stay alive but the HTTP service will be disabled.", + ) + launch_http_server = False + + if launch_http_server: + # Writes agent address to kv. + # DASHBOARD_AGENT_ADDR_NODE_ID_PREFIX: -> (ip, http_port, grpc_port) + # DASHBOARD_AGENT_ADDR_IP_PREFIX: -> (node_id, http_port, grpc_port) + # -1 should indicate that http server is not started. + http_port = -1 if not self.http_server else self.http_server.http_port + grpc_port = -1 if not self.server else self.grpc_port + put_by_node_id = self.gcs_client.async_internal_kv_put( + f"{dashboard_consts.DASHBOARD_AGENT_ADDR_NODE_ID_PREFIX}{self.node_id}".encode(), + json.dumps([self.ip, http_port, grpc_port]).encode(), + True, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + ) + put_by_ip = self.gcs_client.async_internal_kv_put( + f"{dashboard_consts.DASHBOARD_AGENT_ADDR_IP_PREFIX}{self.ip}".encode(), + json.dumps([self.node_id, http_port, grpc_port]).encode(), + True, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + ) + + await asyncio.gather(put_by_node_id, put_by_ip) + + tasks = [m.run(self.server) for m in modules] + + if sys.platform not in ["win32", "cygwin"]: + + def callback(msg): + logger.info( + f"Terminated Raylet: ip={self.ip}, node_id={self.node_id}. {msg}" + ) + + check_parent_task = create_check_raylet_task( + self.log_dir, self.gcs_client, callback, loop + ) + tasks.append(check_parent_task) + + if self.server: + tasks.append(self.server.wait_for_termination()) + else: + + async def wait_forever(): + while True: + await asyncio.sleep(3600) + + tasks.append(wait_forever()) + + await asyncio.gather(*tasks) + + if self.http_server: + await self.http_server.cleanup() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Dashboard agent.") + parser.add_argument( + "--node-ip-address", + required=True, + type=str, + help="the IP address of this node.", + ) + parser.add_argument( + "--gcs-address", required=True, type=str, help="The address (ip:port) of GCS." + ) + parser.add_argument( + "--cluster-id-hex", + required=True, + type=str, + help="The cluster id in hex.", + ) + parser.add_argument( + "--metrics-export-port", + required=True, + type=int, + help="The port to expose metrics through Prometheus.", + ) + parser.add_argument( + "--dashboard-agent-port", + required=True, + type=int, + help="The port on which the dashboard agent will receive GRPCs.", + ) + parser.add_argument( + "--node-manager-port", + required=True, + type=int, + help="The port to use for starting the node manager", + ) + parser.add_argument( + "--object-store-name", + required=True, + type=str, + default=None, + help="The socket name of the plasma store", + ) + parser.add_argument( + "--listen-port", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT, + help="Port for HTTP server to listen on", + ) + parser.add_argument( + "--raylet-name", + required=True, + type=str, + default=None, + help="The socket path of the raylet process", + ) + parser.add_argument( + "--logging-level", + required=False, + type=lambda s: logging.getLevelName(s.upper()), + default=ray_constants.LOGGER_LEVEL, + choices=ray_constants.LOGGER_LEVEL_CHOICES, + help=ray_constants.LOGGER_LEVEL_HELP, + ) + parser.add_argument( + "--logging-format", + required=False, + type=str, + default=ray_constants.LOGGER_FORMAT, + help=ray_constants.LOGGER_FORMAT_HELP, + ) + parser.add_argument( + "--logging-filename", + required=False, + type=str, + default=dashboard_consts.DASHBOARD_AGENT_LOG_FILENAME, + help="Specify the name of log file, " + 'log to stdout if set empty, default is "{}".'.format( + dashboard_consts.DASHBOARD_AGENT_LOG_FILENAME + ), + ) + parser.add_argument( + "--logging-rotate-bytes", + required=True, + type=int, + help="Specify the max bytes for rotating log file.", + ) + parser.add_argument( + "--logging-rotate-backup-count", + required=True, + type=int, + help="Specify the backup count of rotated log file.", + ) + parser.add_argument( + "--log-dir", + required=True, + type=str, + default=None, + help="Specify the path of log directory.", + ) + parser.add_argument( + "--temp-dir", + required=True, + type=str, + default=None, + help="Specify the path of the temporary directory use by Ray process.", + ) + parser.add_argument( + "--session-dir", + required=True, + type=str, + default=None, + help="Specify the path of this session.", + ) + + parser.add_argument( + "--minimal", + action="store_true", + help=( + "Minimal agent only contains a subset of features that don't " + "require additional dependencies installed when ray is installed " + "by `pip install 'ray[default]'`." + ), + ) + parser.add_argument( + "--disable-metrics-collection", + action="store_true", + help=("If this arg is set, metrics report won't be enabled from the agent."), + ) + parser.add_argument( + "--session-name", + required=False, + type=str, + default=None, + help="The session name (cluster id) of this cluster.", + ) + parser.add_argument( + "--stdout-filepath", + required=False, + type=str, + default="", + help="The filepath to dump dashboard agent stdout.", + ) + parser.add_argument( + "--stderr-filepath", + required=False, + type=str, + default="", + help="The filepath to dump dashboard agent stderr.", + ) + + args = parser.parse_args() + + try: + # Disable log rotation for windows platform. + logging_rotation_bytes = ( + args.logging_rotate_bytes if sys.platform != "win32" else 0 + ) + logging_rotation_backup_count = ( + args.logging_rotate_backup_count if sys.platform != "win32" else 1 + ) + + logger = setup_component_logger( + logging_level=args.logging_level, + logging_format=args.logging_format, + log_dir=args.log_dir, + filename=args.logging_filename, + max_bytes=logging_rotation_bytes, + backup_count=logging_rotation_backup_count, + ) + + # Setup stdout/stderr redirect files if redirection enabled. + logging_utils.redirect_stdout_stderr_if_needed( + args.stdout_filepath, + args.stderr_filepath, + logging_rotation_bytes, + logging_rotation_backup_count, + ) + + # Initialize event loop, see Dashboard init code for caveat + # w.r.t grpc server init in the DashboardAgent initializer. + loop = get_or_create_event_loop() + + agent = DashboardAgent( + args.node_ip_address, + args.dashboard_agent_port, + args.gcs_address, + args.cluster_id_hex, + args.minimal, + temp_dir=args.temp_dir, + session_dir=args.session_dir, + log_dir=args.log_dir, + metrics_export_port=args.metrics_export_port, + node_manager_port=args.node_manager_port, + listen_port=args.listen_port, + object_store_name=args.object_store_name, + raylet_name=args.raylet_name, + disable_metrics_collection=args.disable_metrics_collection, + session_name=args.session_name, + ) + + def sigterm_handler(): + logger.warning("Exiting with SIGTERM immediately...") + # Exit code 0 will be considered as an expected shutdown + os._exit(signal.SIGTERM) + + if sys.platform != "win32": + # TODO(rickyyx): we currently do not have any logic for actual + # graceful termination in the agent. Most of the underlying + # async tasks run by the agent head doesn't handle CancelledError. + # So a truly graceful shutdown is not trivial w/o much refactoring. + # Re-open the issue: https://github.com/ray-project/ray/issues/25518 + # if a truly graceful shutdown is required. + loop.add_signal_handler(signal.SIGTERM, sigterm_handler) + + loop.run_until_complete(agent.run()) + except Exception: + logger.exception("Agent is working abnormally. It will exit immediately.") + exit(1) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/client/build/speedscope-1.5.3/favicon-16x16.361d2b26.png b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/client/build/speedscope-1.5.3/favicon-16x16.361d2b26.png new file mode 100644 index 0000000000000000000000000000000000000000..e292da07e1f445448df3650d1953a31455f80018 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/client/build/speedscope-1.5.3/favicon-16x16.361d2b26.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a62a6da7742b43ee798b106b709aa82eafd1b500ef050427cfec05e4d41dacac +size 679 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/client/build/speedscope-1.5.3/favicon-32x32.1165a94e.png b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/client/build/speedscope-1.5.3/favicon-32x32.1165a94e.png new file mode 100644 index 0000000000000000000000000000000000000000..e46848eb96c0f650ec2e065a651a6c0bd3ecdaf3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/client/build/speedscope-1.5.3/favicon-32x32.1165a94e.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9ea6e6d13b7b8064187866deba1e8674d8ba25071279ba7b15f34b54df2508d0 +size 1585 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/consts.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/consts.py new file mode 100644 index 0000000000000000000000000000000000000000..bbd1a2f57361a83dcf6f613a67b47a97ab8227b6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/consts.py @@ -0,0 +1,101 @@ +import os + +from ray._private.ray_constants import env_bool, env_float, env_integer + +DASHBOARD_LOG_FILENAME = "dashboard.log" +DASHBOARD_AGENT_ADDR_NODE_ID_PREFIX = "DASHBOARD_AGENT_ADDR_NODE_ID_PREFIX:" +DASHBOARD_AGENT_ADDR_IP_PREFIX = "DASHBOARD_AGENT_ADDR_IP_PREFIX:" +DASHBOARD_AGENT_LOG_FILENAME = "dashboard_agent.log" +DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S_ENV_NAME = ( + "RAY_DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S" # noqa +) +DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S = env_integer( + DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S_ENV_NAME, 0.4 +) +# The maximum time that parent can be considered +# as dead before agent kills itself. +_PARENT_DEATH_THREASHOLD = 5 +RAY_STATE_SERVER_MAX_HTTP_REQUEST_ENV_NAME = "RAY_STATE_SERVER_MAX_HTTP_REQUEST" +# Default number of in-progress requests to the state api server. +RAY_STATE_SERVER_MAX_HTTP_REQUEST = env_integer( + RAY_STATE_SERVER_MAX_HTTP_REQUEST_ENV_NAME, 100 +) +# Max allowed number of in-progress requests could be configured. +RAY_STATE_SERVER_MAX_HTTP_REQUEST_ALLOWED = 1000 + +RAY_DASHBOARD_STATS_PURGING_INTERVAL = env_integer( + "RAY_DASHBOARD_STATS_PURGING_INTERVAL", 60 * 10 +) +RAY_DASHBOARD_STATS_UPDATING_INTERVAL = env_integer( + "RAY_DASHBOARD_STATS_UPDATING_INTERVAL", 15 +) +GCS_SERVER_ADDRESS = "GcsServerAddress" +# GCS check alive +GCS_CHECK_ALIVE_INTERVAL_SECONDS = env_integer("GCS_CHECK_ALIVE_INTERVAL_SECONDS", 5) +GCS_RPC_TIMEOUT_SECONDS = env_integer("RAY_DASHBOARD_GCS_RPC_TIMEOUT_SECONDS", 60) +# aiohttp_cache +AIOHTTP_CACHE_TTL_SECONDS = 2 +AIOHTTP_CACHE_MAX_SIZE = 128 +AIOHTTP_CACHE_DISABLE_ENVIRONMENT_KEY = "RAY_DASHBOARD_NO_CACHE" +# Default value for datacenter (the default value in protobuf) +DEFAULT_LANGUAGE = "PYTHON" +DEFAULT_JOB_ID = "ffff" +# Hook that is invoked on the dashboard `/api/component_activities` endpoint. +# Environment variable stored here should be a callable that does not +# take any arguments and should return a dictionary mapping +# activity component type (str) to +# ray.dashboard.modules.api.api_head.RayActivityResponse. +# Example: "your.module.ray_cluster_activity_hook". +RAY_CLUSTER_ACTIVITY_HOOK = "RAY_CLUSTER_ACTIVITY_HOOK" + +# The number of candidate agents +CANDIDATE_AGENT_NUMBER = max(env_integer("CANDIDATE_AGENT_NUMBER", 1), 1) +# when head receive JobSubmitRequest, maybe not any agent is available, +# we need to wait for agents in other node start +WAIT_AVAILABLE_AGENT_TIMEOUT = 10 +TRY_TO_GET_AGENT_INFO_INTERVAL_SECONDS = 0.5 +RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES_ENV_VAR = "RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES" +RAY_STREAM_RUNTIME_ENV_LOG_TO_JOB_DRIVER_LOG_ENV_VAR = ( + "RAY_STREAM_RUNTIME_ENV_LOG_TO_JOB_DRIVER_LOG" +) + +# The max time to wait for the JobSupervisor to start before failing the job. +DEFAULT_JOB_START_TIMEOUT_SECONDS = 60 * 15 +RAY_JOB_START_TIMEOUT_SECONDS_ENV_VAR = "RAY_JOB_START_TIMEOUT_SECONDS" +# Port that dashboard prometheus metrics will be exported to +DASHBOARD_METRIC_PORT = env_integer("DASHBOARD_METRIC_PORT", 44227) + +NODE_TAG_KEYS = ["ip", "Version", "SessionName", "IsHeadNode"] +GPU_TAG_KEYS = NODE_TAG_KEYS + ["GpuDeviceName", "GpuIndex"] + +# TpuDeviceName and TpuIndex are expected to be equal to the number of TPU +# chips in the cluster. TpuType and TpuTopology are proportional to the number +# of node pools. +TPU_TAG_KEYS = NODE_TAG_KEYS + ["TpuDeviceName", "TpuIndex", "TpuType", "TpuTopology"] +CLUSTER_TAG_KEYS = ["node_type", "Version", "SessionName"] +COMPONENT_METRICS_TAG_KEYS = ["ip", "pid", "Version", "Component", "SessionName"] + +# Dashboard metrics are tracked separately at the dashboard. TODO(sang): Support GCS. +# Note that for dashboard subprocess module, the component name is "dashboard_[module_name]". +AVAILABLE_COMPONENT_NAMES_FOR_METRICS = { + "workers", + "raylet", + "agent", + "dashboard", + "gcs", +} +METRICS_INPUT_ROOT = os.path.join( + os.path.dirname(__file__), "modules", "metrics", "export" +) +METRICS_RECORD_INTERVAL_S = env_integer("METRICS_RECORD_INTERVAL_S", 5) +PROMETHEUS_CONFIG_INPUT_PATH = os.path.join( + METRICS_INPUT_ROOT, "prometheus", "prometheus.yml" +) +PARENT_HEALTH_CHECK_BY_PIPE = env_bool( + "RAY_enable_pipe_based_agent_to_parent_health_check", False +) + +# Maximum time to wait for the subprocess module to be ready. +SUBPROCESS_MODULE_WAIT_READY_TIMEOUT = env_float( + "RAY_DASHBOARD_SUBPROCESS_MODULE_WAIT_READY_TIMEOUT", 30.0 +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/dashboard.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a019947c31b549ace087713a9f520adf04f1b2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/dashboard.py @@ -0,0 +1,312 @@ +import argparse +import logging +import os +import platform +import signal +import sys +import traceback +from typing import Optional, Set + +import ray +import ray._private.ray_constants as ray_constants +import ray.dashboard.consts as dashboard_consts +import ray.dashboard.head as dashboard_head +import ray.dashboard.utils as dashboard_utils +from ray._common.utils import get_or_create_event_loop +from ray._private import logging_utils +from ray._private.ray_logging import setup_component_logger +from ray._private.utils import ( + format_error_message, + publish_error_to_driver, +) + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) + + +class Dashboard: + """A dashboard process for monitoring Ray nodes. + + This dashboard is made up of a REST API which collates data published by + Reporter processes on nodes into a json structure, and a webserver + which polls said API for display purposes. + + Args: + host: Host address of dashboard aiohttp server. + port: Port number of dashboard aiohttp server. + port_retries: The retry times to select a valid port. + gcs_address: GCS address of the cluster. + cluster_id_hex: Cluster ID hex string. + node_ip_address: The IP address of the dashboard. + serve_frontend: If configured, frontend HTML + is not served from the dashboard. + log_dir: Log directory of dashboard. + logging_level: The logging level (e.g. logging.INFO, logging.DEBUG) + logging_format: The format string for log messages + logging_filename: The name of the log file + logging_rotate_bytes: Max size in bytes before rotating log file + logging_rotate_backup_count: Number of backup files to keep when rotating + """ + + def __init__( + self, + host: str, + port: int, + port_retries: int, + gcs_address: str, + cluster_id_hex: str, + node_ip_address: str, + log_dir: str, + logging_level: int, + logging_format: str, + logging_filename: str, + logging_rotate_bytes: int, + logging_rotate_backup_count: int, + temp_dir: str = None, + session_dir: str = None, + minimal: bool = False, + serve_frontend: bool = True, + modules_to_load: Optional[Set[str]] = None, + ): + self.dashboard_head = dashboard_head.DashboardHead( + http_host=host, + http_port=port, + http_port_retries=port_retries, + gcs_address=gcs_address, + cluster_id_hex=cluster_id_hex, + node_ip_address=node_ip_address, + log_dir=log_dir, + logging_level=logging_level, + logging_format=logging_format, + logging_filename=logging_filename, + logging_rotate_bytes=logging_rotate_bytes, + logging_rotate_backup_count=logging_rotate_backup_count, + temp_dir=temp_dir, + session_dir=session_dir, + minimal=minimal, + serve_frontend=serve_frontend, + modules_to_load=modules_to_load, + ) + + async def run(self): + await self.dashboard_head.run() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Ray dashboard.") + parser.add_argument( + "--host", required=True, type=str, help="The host to use for the HTTP server." + ) + parser.add_argument( + "--port", required=True, type=int, help="The port to use for the HTTP server." + ) + parser.add_argument( + "--port-retries", + required=False, + type=int, + default=0, + help="The retry times to select a valid port.", + ) + parser.add_argument( + "--gcs-address", required=True, type=str, help="The address (ip:port) of GCS." + ) + parser.add_argument( + "--cluster-id-hex", required=True, type=str, help="The cluster ID in hex." + ) + parser.add_argument( + "--node-ip-address", + required=True, + type=str, + help="The IP address of the node where this is running.", + ) + parser.add_argument( + "--logging-level", + required=False, + type=lambda s: logging.getLevelName(s.upper()), + default=ray_constants.LOGGER_LEVEL, + choices=ray_constants.LOGGER_LEVEL_CHOICES, + help=ray_constants.LOGGER_LEVEL_HELP, + ) + parser.add_argument( + "--logging-format", + required=False, + type=str, + default=ray_constants.LOGGER_FORMAT, + help=ray_constants.LOGGER_FORMAT_HELP, + ) + parser.add_argument( + "--logging-filename", + required=False, + type=str, + default=dashboard_consts.DASHBOARD_LOG_FILENAME, + help="Specify the name of log file, " + 'log to stdout if set empty, default is "{}"'.format( + dashboard_consts.DASHBOARD_LOG_FILENAME + ), + ) + parser.add_argument( + "--logging-rotate-bytes", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BYTES, + help="Specify the max bytes for rotating " + "log file, default is {} bytes.".format(ray_constants.LOGGING_ROTATE_BYTES), + ) + parser.add_argument( + "--logging-rotate-backup-count", + required=False, + type=int, + default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT, + help="Specify the backup count of rotated log file, default is {}.".format( + ray_constants.LOGGING_ROTATE_BACKUP_COUNT + ), + ) + parser.add_argument( + "--log-dir", + required=True, + type=str, + default=None, + help="Specify the path of log directory.", + ) + parser.add_argument( + "--temp-dir", + required=True, + type=str, + default=None, + help="Specify the path of the temporary directory use by Ray process.", + ) + parser.add_argument( + "--session-dir", + required=True, + type=str, + default=None, + help="Specify the path of the session directory of the cluster.", + ) + parser.add_argument( + "--minimal", + action="store_true", + help=( + "Minimal dashboard only contains a subset of features that don't " + "require additional dependencies installed when ray is installed " + "by `pip install ray[default]`." + ), + ) + parser.add_argument( + "--modules-to-load", + required=False, + default=None, + help=( + "Specify the list of module names in [module_1],[module_2] format." + "E.g., JobHead,StateHead... " + "If nothing is specified, all modules are loaded." + ), + ) + parser.add_argument( + "--disable-frontend", + action="store_true", + help=("If configured, frontend html is not served from the server."), + ) + parser.add_argument( + "--stdout-filepath", + required=False, + type=str, + default="", + help="The filepath to dump dashboard stdout.", + ) + parser.add_argument( + "--stderr-filepath", + required=False, + type=str, + default="", + help="The filepath to dump dashboard stderr.", + ) + + args = parser.parse_args() + + try: + # Disable log rotation for windows platform. + logging_rotation_bytes = ( + args.logging_rotate_bytes if sys.platform != "win32" else 0 + ) + logging_rotation_backup_count = ( + args.logging_rotate_backup_count if sys.platform != "win32" else 1 + ) + setup_component_logger( + logging_level=args.logging_level, + logging_format=args.logging_format, + log_dir=args.log_dir, + filename=args.logging_filename, + max_bytes=logging_rotation_bytes, + backup_count=logging_rotation_backup_count, + ) + + # Setup stdout/stderr redirect files if redirection enabled. + logging_utils.redirect_stdout_stderr_if_needed( + args.stdout_filepath, + args.stderr_filepath, + logging_rotation_bytes, + logging_rotation_backup_count, + ) + + if args.modules_to_load: + modules_to_load = set(args.modules_to_load.strip(" ,").split(",")) + else: + # None == default. + modules_to_load = None + + loop = get_or_create_event_loop() + dashboard = Dashboard( + host=args.host, + port=args.port, + port_retries=args.port_retries, + gcs_address=args.gcs_address, + cluster_id_hex=args.cluster_id_hex, + node_ip_address=args.node_ip_address, + log_dir=args.log_dir, + logging_level=args.logging_level, + logging_format=args.logging_format, + logging_filename=args.logging_filename, + logging_rotate_bytes=logging_rotation_bytes, + logging_rotate_backup_count=logging_rotation_backup_count, + temp_dir=args.temp_dir, + session_dir=args.session_dir, + minimal=args.minimal, + serve_frontend=(not args.disable_frontend), + modules_to_load=modules_to_load, + ) + + def sigterm_handler(): + logger.warning("Exiting with SIGTERM immediately...") + os._exit(signal.SIGTERM) + + if sys.platform != "win32": + # TODO(rickyyx): we currently do not have any logic for actual + # graceful termination in the dashboard. Most of the underlying + # async tasks run by the dashboard head doesn't handle CancelledError. + # So a truly graceful shutdown is not trivial w/o much refactoring. + # Re-open the issue: https://github.com/ray-project/ray/issues/25518 + # if a truly graceful shutdown is required. + loop.add_signal_handler(signal.SIGTERM, sigterm_handler) + + loop.run_until_complete(dashboard.run()) + except Exception as e: + traceback_str = format_error_message(traceback.format_exc()) + message = ( + f"The dashboard on node {platform.uname()[1]} " + f"failed with the following " + f"error:\n{traceback_str}" + ) + if isinstance(e, dashboard_utils.FrontendNotFoundError): + logger.warning(message) + else: + logger.error(message) + raise e + + # Something went wrong, so push an error to all drivers. + publish_error_to_driver( + ray_constants.DASHBOARD_DIED_ERROR, + message, + gcs_client=ray._raylet.GcsClient(address=args.gcs_address), + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/dashboard_metrics.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/dashboard_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..7f1b6f2b22a9ed826409f80542e333aa51a5b037 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/dashboard_metrics.py @@ -0,0 +1,123 @@ +from typing import Optional + +from ray.dashboard.consts import COMPONENT_METRICS_TAG_KEYS + + +class NullMetric: + """Mock metric class to be used in case of prometheus_client import error.""" + + def set(self, *args, **kwargs): + pass + + def observe(self, *args, **kwargs): + pass + + def inc(self, *args, **kwargs): + pass + + +try: + + from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram + + # The metrics in this class should be kept in sync with + # python/ray/tests/test_metrics_agent.py + class DashboardPrometheusMetrics: + def __init__(self, registry: Optional[CollectorRegistry] = None): + self.registry: CollectorRegistry = registry or CollectorRegistry( + auto_describe=True + ) + # Buckets: 5ms, 10ms, 25ms, 50ms, 75ms + # 100ms, 250ms, 500ms, 750ms + # 1s, 2.5s, 5s, 7.5s, 10s + # 20s, 40s, 60s + # used for API duration + histogram_buckets_s = [ + 0.005, + 0.01, + 0.025, + 0.05, + 0.075, + 0.1, + 0.25, + 0.5, + 0.75, + 1, + 2.5, + 5, + 7.5, + 10, + 20, + 40, + 60, + ] + self.metrics_request_duration = Histogram( + "dashboard_api_requests_duration_seconds", + "Total duration in seconds per endpoint", + ("endpoint", "http_status", "Version", "SessionName", "Component"), + unit="seconds", + namespace="ray", + registry=self.registry, + buckets=histogram_buckets_s, + ) + self.metrics_request_count = Counter( + "dashboard_api_requests_count", + "Total requests count per endpoint", + ( + "method", + "endpoint", + "http_status", + "Version", + "SessionName", + "Component", + ), + unit="requests", + namespace="ray", + registry=self.registry, + ) + self.metrics_event_loop_tasks = Gauge( + "dashboard_event_loop_tasks", + "Number of tasks currently pending in the event loop's queue.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="tasks", + namespace="ray", + registry=self.registry, + ) + self.metrics_event_loop_lag = Gauge( + "dashboard_event_loop_lag", + "Event loop lag in seconds.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="seconds", + namespace="ray", + registry=self.registry, + ) + self.metrics_dashboard_cpu = Gauge( + "component_cpu", + "Dashboard CPU percentage usage.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="percentage", + namespace="ray", + registry=self.registry, + ) + self.metrics_dashboard_mem_uss = Gauge( + "component_uss", + "USS usage of all components on the node.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="mb", + namespace="ray", + registry=self.registry, + ) + self.metrics_dashboard_mem_rss = Gauge( + "component_rss", + "RSS usage of all components on the node.", + tuple(COMPONENT_METRICS_TAG_KEYS), + unit="mb", + namespace="ray", + registry=self.registry, + ) + +except ImportError: + + class DashboardPrometheusMetrics(object): + def __getattr__(self, attr): + return NullMetric() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/head.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/head.py new file mode 100644 index 0000000000000000000000000000000000000000..059c867ff66eccfc0d4163cd1589700e05a6cd2c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/head.py @@ -0,0 +1,471 @@ +import asyncio +import logging +import os +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import TYPE_CHECKING, List, Optional, Set, Tuple + +import ray +import ray.dashboard.consts as dashboard_consts +import ray.dashboard.utils as dashboard_utils +import ray.experimental.internal_kv as internal_kv +from ray._private import ray_constants +from ray._private.async_utils import enable_monitor_loop_lag +from ray._private.ray_constants import env_integer +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray._raylet import GcsClient +from ray.dashboard.consts import ( + AVAILABLE_COMPONENT_NAMES_FOR_METRICS, + DASHBOARD_METRIC_PORT, +) +from ray.dashboard.dashboard_metrics import DashboardPrometheusMetrics +from ray.dashboard.utils import ( + DashboardHeadModule, + DashboardHeadModuleConfig, + async_loop_forever, +) + +import psutil + +try: + import prometheus_client +except ImportError: + prometheus_client = None + +if TYPE_CHECKING: + from ray.dashboard.subprocesses.handle import SubprocessModuleHandle + +logger = logging.getLogger(__name__) + +# NOTE: Executor in this head is intentionally constrained to just 1 thread by +# default to limit its concurrency, therefore reducing potential for +# GIL contention +RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS = env_integer( + "RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS", 1 +) + + +class DashboardHead: + def __init__( + self, + http_host: str, + http_port: int, + http_port_retries: int, + gcs_address: str, + cluster_id_hex: str, + node_ip_address: str, + log_dir: str, + logging_level: int, + logging_format: str, + logging_filename: str, + logging_rotate_bytes: int, + logging_rotate_backup_count: int, + temp_dir: str, + session_dir: str, + minimal: bool, + serve_frontend: bool, + modules_to_load: Optional[Set[str]] = None, + ): + """ + Args: + http_host: The host address for the Http server. + http_port: The port for the Http server. + http_port_retries: The maximum retry to bind ports for the Http server. + gcs_address: The GCS address in the {address}:{port} format. + log_dir: The log directory. E.g., /tmp/session_latest/logs. + logging_level: The logging level (e.g. logging.INFO, logging.DEBUG) + logging_format: The format string for log messages + logging_filename: The name of the log file + logging_rotate_bytes: Max size in bytes before rotating log file + logging_rotate_backup_count: Number of backup files to keep when rotating + temp_dir: The temp directory. E.g., /tmp. + session_dir: The session directory. E.g., tmp/session_latest. + minimal: Whether or not it will load the minimal modules. + serve_frontend: If configured, frontend HTML is + served from the dashboard. + modules_to_load: A set of module name in string to load. + By default (None), it loads all available modules. + Note that available modules could be changed depending on + minimal flags. + """ + self.minimal = minimal + self.serve_frontend = serve_frontend + # If it is the minimal mode, we shouldn't serve frontend. + if self.minimal: + self.serve_frontend = False + # Public attributes are accessible for all head modules. + # Walkaround for issue: https://github.com/ray-project/ray/issues/7084 + self.http_host = "127.0.0.1" if http_host == "localhost" else http_host + self.http_port = http_port + self.http_port_retries = http_port_retries + self._modules_to_load = modules_to_load + self._modules_loaded = False + self.metrics = None + + self._executor = ThreadPoolExecutor( + max_workers=RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS, + thread_name_prefix="dashboard_head_executor", + ) + + assert gcs_address is not None + self.gcs_address = gcs_address + self.cluster_id_hex = cluster_id_hex + self.log_dir = log_dir + self.logging_level = logging_level + self.logging_format = logging_format + self.logging_filename = logging_filename + self.logging_rotate_bytes = logging_rotate_bytes + self.logging_rotate_backup_count = logging_rotate_backup_count + self.temp_dir = temp_dir + self.session_dir = session_dir + self.session_name = Path(session_dir).name + self.gcs_error_subscriber = None + self.gcs_log_subscriber = None + self.ip = node_ip_address + self.pid = os.getpid() + self.dashboard_proc = psutil.Process() + + # If the dashboard is started as non-minimal version, http server should + # be configured to expose APIs. + self.http_server = None + + async def _configure_http_server( + self, + dashboard_head_modules: List[DashboardHeadModule], + subprocess_module_handles: List["SubprocessModuleHandle"], + ): + from ray.dashboard.http_server_head import HttpServerDashboardHead + + self.http_server = HttpServerDashboardHead( + self.ip, + self.http_host, + self.http_port, + self.http_port_retries, + self.gcs_address, + self.session_name, + self.metrics, + ) + await self.http_server.run(dashboard_head_modules, subprocess_module_handles) + + @property + def http_session(self): + if not self._modules_loaded and not self.http_server: + # When the dashboard is still starting up, this property gets + # called as part of the method_route_table_factory magic. In + # this case, the property is not actually used but the magic + # method calls every property to look for a route to add to + # the global route table. It should be okay for http_server + # to still be None at this point. + return None + assert self.http_server, "Accessing unsupported API in a minimal ray." + return self.http_server.http_session + + @async_loop_forever(dashboard_consts.GCS_CHECK_ALIVE_INTERVAL_SECONDS) + async def _gcs_check_alive(self): + try: + # If gcs is permanently dead, gcs client will exit the process + # (see gcs_rpc_client.h) + await self.gcs_client.async_check_alive(node_ips=[], timeout=None) + except Exception: + logger.warning("Failed to check gcs aliveness, will retry", exc_info=True) + + def _load_modules( + self, modules_to_load: Optional[Set[str]] = None + ) -> Tuple[List[DashboardHeadModule], List["SubprocessModuleHandle"]]: + """ + If minimal, only load DashboardHeadModule. + If non-minimal, load both kinds of modules: DashboardHeadModule, SubprocessModule. + + If modules_to_load is not None, only load the modules in the set. + """ + dashboard_head_modules = self._load_dashboard_head_modules(modules_to_load) + subprocess_module_handles = self._load_subprocess_module_handles( + modules_to_load + ) + + all_names = {type(m).__name__ for m in dashboard_head_modules} | { + h.module_cls.__name__ for h in subprocess_module_handles + } + assert len(all_names) == len(dashboard_head_modules) + len( + subprocess_module_handles + ), "Duplicate module names. A module name can't be a DashboardHeadModule and a SubprocessModule at the same time." + + # Verify modules are loaded as expected. + if modules_to_load is not None and all_names != modules_to_load: + assert False, ( + f"Actual loaded modules {all_names}, doesn't match the requested modules " + f"to load, {modules_to_load}." + ) + + self._modules_loaded = True + return dashboard_head_modules, subprocess_module_handles + + def _load_dashboard_head_modules( + self, modules_to_load: Optional[Set[str]] = None + ) -> List[DashboardHeadModule]: + """Load `DashboardHeadModule`s. + + Args: + modules: A list of module names to load. By default (None), + it loads all modules. + """ + modules = [] + head_cls_list = dashboard_utils.get_all_modules(DashboardHeadModule) + + config = DashboardHeadModuleConfig( + minimal=self.minimal, + cluster_id_hex=self.cluster_id_hex, + session_name=self.session_name, + gcs_address=self.gcs_address, + log_dir=self.log_dir, + temp_dir=self.temp_dir, + session_dir=self.session_dir, + ip=self.ip, + http_host=self.http_host, + http_port=self.http_port, + ) + + # Select modules to load. + if modules_to_load is not None: + head_cls_list = [ + cls for cls in head_cls_list if cls.__name__ in modules_to_load + ] + + logger.info(f"DashboardHeadModules to load: {modules_to_load}.") + + for cls in head_cls_list: + logger.info(f"Loading {DashboardHeadModule.__name__}: {cls}.") + c = cls(config) + modules.append(c) + + logger.info(f"Loaded {len(modules)} dashboard head modules: {modules}.") + return modules + + def _load_subprocess_module_handles( + self, modules_to_load: Optional[Set[str]] = None + ) -> List["SubprocessModuleHandle"]: + """ + If minimal, return an empty list. + If non-minimal, load `SubprocessModule`s by creating Handles to them. + + Args: + modules: A list of module names to load. By default (None), + it loads all modules. + """ + if self.minimal: + logger.info("Subprocess modules not loaded in minimal mode.") + return [] + + from ray.dashboard.subprocesses.handle import SubprocessModuleHandle + from ray.dashboard.subprocesses.module import ( + SubprocessModule, + SubprocessModuleConfig, + ) + + handles = [] + subprocess_cls_list = dashboard_utils.get_all_modules(SubprocessModule) + + loop = ray._common.utils.get_or_create_event_loop() + config = SubprocessModuleConfig( + cluster_id_hex=self.cluster_id_hex, + gcs_address=self.gcs_address, + session_name=self.session_name, + temp_dir=self.temp_dir, + session_dir=self.session_dir, + logging_level=self.logging_level, + logging_format=self.logging_format, + log_dir=self.log_dir, + logging_filename=self.logging_filename, + logging_rotate_bytes=self.logging_rotate_bytes, + logging_rotate_backup_count=self.logging_rotate_backup_count, + socket_dir=str(Path(self.session_dir) / "sockets"), + ) + + # Select modules to load. + if modules_to_load is not None: + subprocess_cls_list = [ + cls for cls in subprocess_cls_list if cls.__name__ in modules_to_load + ] + + for cls in subprocess_cls_list: + logger.info(f"Loading {SubprocessModule.__name__}: {cls}.") + handle = SubprocessModuleHandle(loop, cls, config) + handles.append(handle) + + logger.info(f"Loaded {len(handles)} subprocess modules: {handles}.") + return handles + + async def _setup_metrics(self, gcs_client): + metrics = DashboardPrometheusMetrics() + + # Setup prometheus metrics export server + assert internal_kv._internal_kv_initialized() + assert gcs_client is not None + address = f"{self.ip}:{DASHBOARD_METRIC_PORT}" + await gcs_client.async_internal_kv_put( + "DashboardMetricsAddress".encode(), address.encode(), True, namespace=None + ) + if prometheus_client: + try: + logger.info( + "Starting dashboard metrics server on port {}".format( + DASHBOARD_METRIC_PORT + ) + ) + kwargs = {"addr": "127.0.0.1"} if self.ip == "127.0.0.1" else {} + prometheus_client.start_http_server( + port=DASHBOARD_METRIC_PORT, + registry=metrics.registry, + **kwargs, + ) + except Exception: + logger.exception( + "An exception occurred while starting the metrics server." + ) + elif not prometheus_client: + logger.warning( + "`prometheus_client` not found, so metrics will not be exported." + ) + + return metrics + + @dashboard_utils.async_loop_forever(dashboard_consts.METRICS_RECORD_INTERVAL_S) + async def _record_dashboard_metrics( + self, subprocess_module_handles: List["SubprocessModuleHandle"] + ): + labels = { + "ip": self.ip, + "pid": self.pid, + "Version": ray.__version__, + "Component": "dashboard", + "SessionName": self.session_name, + } + assert "dashboard" in AVAILABLE_COMPONENT_NAMES_FOR_METRICS + self._record_cpu_mem_metrics_for_proc(self.dashboard_proc) + for subprocess_module_handle in subprocess_module_handles: + assert subprocess_module_handle.process is not None + proc = psutil.Process(subprocess_module_handle.process.pid) + self._record_cpu_mem_metrics_for_proc( + proc, subprocess_module_handle.module_cls.__name__ + ) + + loop = ray._common.utils.get_or_create_event_loop() + + self.metrics.metrics_event_loop_tasks.labels(**labels).set( + len(asyncio.all_tasks(loop)) + ) + + # Report the max lag since the last export, if any. + if self._event_loop_lag_s_max is not None: + self.metrics.metrics_event_loop_lag.labels(**labels).set( + float(self._event_loop_lag_s_max) + ) + self._event_loop_lag_s_max = None + + def _record_cpu_mem_metrics_for_proc( + self, proc: psutil.Process, module_name: str = "" + ): + labels = { + "ip": self.ip, + "pid": proc.pid, + "Version": ray.__version__, + "Component": "dashboard" if not module_name else "dashboard_" + module_name, + "SessionName": self.session_name, + } + proc_attrs = proc.as_dict(attrs=["cpu_percent", "memory_full_info"]) + self.metrics.metrics_dashboard_cpu.labels(**labels).set( + float(proc_attrs.get("cpu_percent", 0.0)) + ) + # memory_full_info is None on Mac due to the permission issue + # (https://github.com/giampaolo/psutil/issues/883) + if proc_attrs.get("memory_full_info") is not None: + self.metrics.metrics_dashboard_mem_uss.labels(**labels).set( + float(proc_attrs.get("memory_full_info").uss) / 1.0e6 + ) + self.metrics.metrics_dashboard_mem_rss.labels(**labels).set( + float(proc_attrs.get("memory_full_info").rss) / 1.0e6 + ) + + async def run(self): + gcs_address = self.gcs_address + + # Dashboard will handle connection failure automatically + self.gcs_client = GcsClient(address=gcs_address, cluster_id=self.cluster_id_hex) + internal_kv._initialize_internal_kv(self.gcs_client) + + dashboard_head_modules, subprocess_module_handles = self._load_modules( + self._modules_to_load + ) + # Parallel start all subprocess modules. + for handle in subprocess_module_handles: + handle.start_module() + # Wait for all subprocess modules to be ready. + for handle in subprocess_module_handles: + handle.wait_for_module_ready() + + if not self.minimal: + self.metrics = await self._setup_metrics(self.gcs_client) + self._event_loop_lag_s_max: Optional[float] = None + + def on_new_lag(lag_s): + # Record the lag. It's exported in `record_dashboard_metrics` + self._event_loop_lag_s_max = max(self._event_loop_lag_s_max or 0, lag_s) + + enable_monitor_loop_lag(on_new_lag) + + self.record_dashboard_metrics_task = asyncio.create_task( + self._record_dashboard_metrics(subprocess_module_handles) + ) + + try: + assert internal_kv._internal_kv_initialized() + # Note: We always record the usage, but it is not reported + # if the usage stats is disabled. + record_extra_usage_tag(TagKey.DASHBOARD_USED, "False") + except Exception as e: + logger.warning( + "Failed to record the dashboard usage. " + "This error message is harmless and can be ignored. " + f"Error: {e}" + ) + + http_host, http_port = self.http_host, self.http_port + if self.serve_frontend: + logger.info("Initialize the http server.") + await self._configure_http_server( + dashboard_head_modules, subprocess_module_handles + ) + http_host, http_port = self.http_server.get_address() + logger.info(f"http server initialized at {http_host}:{http_port}") + else: + logger.info("http server disabled.") + + # We need to expose dashboard's node's ip for other worker nodes + # if it's listening to all interfaces. + dashboard_http_host = ( + self.ip + if self.http_host != ray_constants.DEFAULT_DASHBOARD_IP + else http_host + ) + # This synchronous code inside an async context is not great. + # It is however acceptable, because this only gets run once + # during initialization and therefore cannot block the event loop. + # This could be done better in the future, including + # removing the polling on the Ray side, by communicating the + # server address to Ray via stdin / stdout or a pipe. + self.gcs_client.internal_kv_put( + ray_constants.DASHBOARD_ADDRESS.encode(), + f"{dashboard_http_host}:{http_port}".encode(), + True, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + ) + + concurrent_tasks = [ + self._gcs_check_alive(), + ] + for m in dashboard_head_modules: + concurrent_tasks.append(m.run()) + await asyncio.gather(*concurrent_tasks) + + if self.http_server: + await self.http_server.cleanup() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/http_server_agent.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/http_server_agent.py new file mode 100644 index 0000000000000000000000000000000000000000..eba97aee9ad5a008a7fa28aa16f5d297a800ebf9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/http_server_agent.py @@ -0,0 +1,128 @@ +import asyncio +import logging +import random +from typing import List, Optional + +from packaging.version import Version + +import ray.dashboard.optional_utils as dashboard_optional_utils +from ray._common.utils import get_or_create_event_loop +from ray.dashboard.optional_deps import aiohttp, aiohttp_cors, hdrs + +logger = logging.getLogger(__name__) +routes = dashboard_optional_utils.DashboardAgentRouteTable + + +class HttpServerAgent: + def __init__(self, ip: str, listen_port: int) -> None: + self.ip = ip + self.listen_port = listen_port + self.http_host = None + self.http_port = None + self.http_session = None + self.runner = None + + async def _start_site_with_retry( + self, max_retries: int = 5, base_delay: float = 0.1 + ) -> aiohttp.web.TCPSite: + """Start the TCP site with retry logic and exponential backoff. + + Args: + max_retries: Maximum number of retry attempts + base_delay: Base delay in seconds for exponential backoff + + Returns: + The started site object + + Raises: + OSError: If all retry attempts fail + """ + last_exception: Optional[OSError] = None + + for attempt in range(max_retries + 1): # +1 for initial attempt + try: + site = aiohttp.web.TCPSite( + self.runner, + "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0", + self.listen_port, + ) + await site.start() + if attempt > 0: + logger.info( + f"Successfully started agent on port {self.listen_port} " + f"after {attempt} retry attempts" + ) + return site + + except OSError as e: + last_exception = e + if attempt < max_retries: + # Calculate exponential backoff with jitter + delay = base_delay * (2**attempt) + random.uniform(0, 0.1) + logger.warning( + f"Failed to bind to port {self.listen_port} (attempt {attempt + 1}/" + f"{max_retries + 1}). Retrying in {delay:.2f}s. Error: {e}" + ) + await asyncio.sleep(delay) + else: + logger.exception( + f"Agent port #{self.listen_port} failed to bind after " + f"{max_retries + 1} attempts." + ) + break + + # If we get here, all retries failed + raise last_exception + + async def start(self, modules: List) -> None: + # Create a http session for all modules. + # aiohttp<4.0.0 uses a 'loop' variable, aiohttp>=4.0.0 doesn't anymore + if Version(aiohttp.__version__) < Version("4.0.0"): + self.http_session = aiohttp.ClientSession(loop=get_or_create_event_loop()) + else: + self.http_session = aiohttp.ClientSession() + + # Bind routes for every module so that each module + # can use decorator-style routes. + for c in modules: + dashboard_optional_utils.DashboardAgentRouteTable.bind(c) + + app = aiohttp.web.Application() + app.add_routes(routes=routes.bound_routes()) + + # Enable CORS on all routes. + cors = aiohttp_cors.setup( + app, + defaults={ + "*": aiohttp_cors.ResourceOptions( + allow_credentials=True, + expose_headers="*", + allow_methods="*", + allow_headers=("Content-Type", "X-Header"), + ) + }, + ) + for route in list(app.router.routes()): + cors.add(route) + + self.runner = aiohttp.web.AppRunner(app) + await self.runner.setup() + + # Start the site with retry logic + site = await self._start_site_with_retry() + + self.http_host, self.http_port, *_ = site._server.sockets[0].getsockname() + logger.info( + "Dashboard agent http address: %s:%s", self.http_host, self.http_port + ) + + # Dump registered http routes. + dump_routes = [r for r in app.router.routes() if r.method != hdrs.METH_HEAD] + for r in dump_routes: + logger.info(r) + logger.info("Registered %s routes.", len(dump_routes)) + + async def cleanup(self) -> None: + # Wait for finish signal. + await self.runner.cleanup() + await self.http_session.close() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/http_server_head.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/http_server_head.py new file mode 100644 index 0000000000000000000000000000000000000000..4acb919cbf72f1e18abd472b54efe6452c1b08ee --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/http_server_head.py @@ -0,0 +1,302 @@ +import asyncio +import errno +import ipaddress +import logging +import os +import pathlib +import sys +import time +from math import floor +from typing import List + +from packaging.version import Version + +import ray +import ray.dashboard.optional_utils as dashboard_optional_utils +import ray.dashboard.timezone_utils as timezone_utils +import ray.dashboard.utils as dashboard_utils +from ray import ray_constants +from ray._common.utils import get_or_create_event_loop +from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag +from ray.dashboard.dashboard_metrics import DashboardPrometheusMetrics +from ray.dashboard.head import DashboardHeadModule + +# All third-party dependencies that are not included in the minimal Ray +# installation must be included in this file. This allows us to determine if +# the agent has the necessary dependencies to be started. +from ray.dashboard.optional_deps import aiohttp, hdrs +from ray.dashboard.subprocesses.handle import SubprocessModuleHandle +from ray.dashboard.subprocesses.routes import SubprocessRouteTable + +# Logger for this module. It should be configured at the entry point +# into the program using Ray. Ray provides a default configuration at +# entry/init points. +logger = logging.getLogger(__name__) +routes = dashboard_optional_utils.DashboardHeadRouteTable + +# Env var that enables follow_symlinks for serving UI static files. +# This is an advanced setting that should only be used with special Ray installations +# where the dashboard build files are symlinked to a different directory. +# This is not recommended for most users and can pose a security risk. +# Please reference the aiohttp docs here: +# https://docs.aiohttp.org/en/stable/web_reference.html#aiohttp.web.UrlDispatcher.add_static +ENV_VAR_FOLLOW_SYMLINKS = "RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS" +FOLLOW_SYMLINKS_ENABLED = os.environ.get(ENV_VAR_FOLLOW_SYMLINKS) == "1" +if FOLLOW_SYMLINKS_ENABLED: + logger.warning( + "Enabling RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS is not recommended as it " + "allows symlinks to directories outside the dashboard build folder. " + "You may accidentally expose files on your system outside of the " + "build directory." + ) + + +def setup_static_dir(): + build_dir = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "client", "build" + ) + module_name = os.path.basename(os.path.dirname(__file__)) + if not os.path.isdir(build_dir): + raise dashboard_utils.FrontendNotFoundError( + errno.ENOENT, + "Dashboard build directory not found. If installing " + "from source, please follow the additional steps " + "required to build the dashboard" + f"(cd python/ray/{module_name}/client " + "&& npm ci " + "&& npm run build)", + build_dir, + ) + + static_dir = os.path.join(build_dir, "static") + routes.static("/static", static_dir, follow_symlinks=FOLLOW_SYMLINKS_ENABLED) + return build_dir + + +class HttpServerDashboardHead: + def __init__( + self, + ip: str, + http_host: str, + http_port: int, + http_port_retries: int, + gcs_address: str, + session_name: str, + metrics: DashboardPrometheusMetrics, + ): + self.ip = ip + self.http_host = http_host + self.http_port = http_port + self.http_port_retries = http_port_retries + self.head_node_ip = gcs_address.split(":")[0] + self.metrics = metrics + self._session_name = session_name + + # Below attirubtes are filled after `run` API is invoked. + self.runner = None + + # Setup Dashboard Routes + try: + build_dir = setup_static_dir() + logger.info("Setup static dir for dashboard: %s", build_dir) + except dashboard_utils.FrontendNotFoundError as ex: + # Not to raise FrontendNotFoundError due to NPM incompatibilities + # with Windows. + # Please refer to ci.sh::build_dashboard_front_end() + if sys.platform in ["win32", "cygwin"]: + logger.warning(ex) + else: + raise ex + dashboard_optional_utils.DashboardHeadRouteTable.bind(self) + + # Create a http session for all modules. + # aiohttp<4.0.0 uses a 'loop' variable, aiohttp>=4.0.0 doesn't anymore + if Version(aiohttp.__version__) < Version("4.0.0"): + self.http_session = aiohttp.ClientSession(loop=get_or_create_event_loop()) + else: + self.http_session = aiohttp.ClientSession() + + @routes.get("/") + async def get_index(self, req) -> aiohttp.web.FileResponse: + try: + # This API will be no-op after the first report. + # Note: We always record the usage, but it is not reported + # if the usage stats is disabled. + record_extra_usage_tag(TagKey.DASHBOARD_USED, "True") + except Exception as e: + logger.warning( + "Failed to record the dashboard usage. " + "This error message is harmless and can be ignored. " + f"Error: {e}" + ) + resp = aiohttp.web.FileResponse( + os.path.join( + os.path.dirname(os.path.abspath(__file__)), "client/build/index.html" + ) + ) + resp.headers["Cache-Control"] = "no-cache" + return resp + + @routes.get("/favicon.ico") + async def get_favicon(self, req) -> aiohttp.web.FileResponse: + return aiohttp.web.FileResponse( + os.path.join( + os.path.dirname(os.path.abspath(__file__)), "client/build/favicon.ico" + ) + ) + + @routes.get("/timezone") + async def get_timezone(self, req) -> aiohttp.web.Response: + try: + current_timezone = timezone_utils.get_current_timezone_info() + return aiohttp.web.json_response(current_timezone) + + except Exception as e: + logger.error(f"Error getting timezone: {e}") + return aiohttp.web.Response( + status=500, text="Internal Server Error:" + str(e) + ) + + def get_address(self): + assert self.http_host and self.http_port + return self.http_host, self.http_port + + @aiohttp.web.middleware + async def path_clean_middleware(self, request, handler): + if request.path.startswith("/static") or request.path.startswith("/logs"): + parent = pathlib.PurePosixPath( + "/logs" if request.path.startswith("/logs") else "/static" + ) + + # If the destination is not relative to the expected directory, + # then the user is attempting path traversal, so deny the request. + request_path = pathlib.PurePosixPath( + pathlib.posixpath.realpath(request.path) + ) + if request_path != parent and parent not in request_path.parents: + logger.info( + f"Rejecting {request_path=} because it is not relative to {parent=}" + ) + raise aiohttp.web.HTTPForbidden() + return await handler(request) + + @aiohttp.web.middleware + async def browsers_no_post_put_middleware(self, request, handler): + if ( + # A best effort test for browser traffic. All common browsers + # start with Mozilla at the time of writing. + dashboard_optional_utils.is_browser_request(request) + and request.method in [hdrs.METH_POST, hdrs.METH_PUT] + ): + return aiohttp.web.Response( + status=405, text="Method Not Allowed for browser traffic." + ) + + return await handler(request) + + @aiohttp.web.middleware + async def metrics_middleware(self, request, handler): + start_time = time.monotonic() + + try: + response = await handler(request) + status_tag = f"{floor(response.status / 100)}xx" + return response + except (Exception, asyncio.CancelledError): + status_tag = "5xx" + raise + finally: + resp_time = time.monotonic() - start_time + try: + self.metrics.metrics_request_duration.labels( + endpoint=handler.__name__, + http_status=status_tag, + Version=ray.__version__, + SessionName=self._session_name, + Component="dashboard", + ).observe(resp_time) + self.metrics.metrics_request_count.labels( + method=request.method, + endpoint=handler.__name__, + http_status=status_tag, + Version=ray.__version__, + SessionName=self._session_name, + Component="dashboard", + ).inc() + except Exception as e: + logger.exception(f"Error emitting api metrics: {e}") + + @aiohttp.web.middleware + async def cache_control_static_middleware(self, request, handler): + if request.path.startswith("/static"): + response = await handler(request) + response.headers["Cache-Control"] = "max-age=31536000" + return response + return await handler(request) + + async def run( + self, + dashboard_head_modules: List[DashboardHeadModule], + subprocess_module_handles: List[SubprocessModuleHandle], + ): + # Bind http routes of each module. + for m in dashboard_head_modules: + dashboard_optional_utils.DashboardHeadRouteTable.bind(m) + + for h in subprocess_module_handles: + SubprocessRouteTable.bind(h) + + # Http server should be initialized after all modules loaded. + # working_dir uploads for job submission can be up to 100MiB. + app = aiohttp.web.Application( + client_max_size=ray_constants.DASHBOARD_CLIENT_MAX_SIZE, + middlewares=[ + self.metrics_middleware, + self.path_clean_middleware, + self.browsers_no_post_put_middleware, + self.cache_control_static_middleware, + ], + ) + app.add_routes(routes=routes.bound_routes()) + app.add_routes(routes=SubprocessRouteTable.bound_routes()) + + self.runner = aiohttp.web.AppRunner( + app, + access_log_format=( + "%a %t '%r' %s %b bytes %D us '%{Referer}i' '%{User-Agent}i'" + ), + ) + await self.runner.setup() + last_ex = None + for i in range(1 + self.http_port_retries): + try: + site = aiohttp.web.TCPSite(self.runner, self.http_host, self.http_port) + await site.start() + break + except OSError as e: + last_ex = e + self.http_port += 1 + logger.warning("Try to use port %s: %s", self.http_port, e) + else: + raise Exception( + f"Failed to find a valid port for dashboard after " + f"{self.http_port_retries} retries: {last_ex}" + ) + self.http_host, self.http_port, *_ = site._server.sockets[0].getsockname() + self.http_host = ( + self.ip + if ipaddress.ip_address(self.http_host).is_unspecified + else self.http_host + ) + logger.info( + "Dashboard head http address: %s:%s", self.http_host, self.http_port + ) + # Dump registered http routes. + dump_routes = [r for r in app.router.routes() if r.method != hdrs.METH_HEAD] + for r in dump_routes: + logger.info(r) + logger.info("Registered %s routes.", len(dump_routes)) + + async def cleanup(self): + # Wait for finish signal. + await self.runner.cleanup() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/k8s_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/k8s_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f9c5da030f4417ffde81b176a2b73a9296a6d442 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/k8s_utils.py @@ -0,0 +1,111 @@ +import logging + +from ray._private.utils import get_num_cpus + +logger = logging.getLogger(__name__) + +CPU_USAGE_PATH = "/sys/fs/cgroup/cpuacct/cpuacct.usage" +CPU_USAGE_PATH_V2 = "/sys/fs/cgroup/cpu.stat" +PROC_STAT_PATH = "/proc/stat" + +container_num_cpus = None +host_num_cpus = None + +last_cpu_usage = None +last_system_usage = None + + +def cpu_percent(): + """Estimate CPU usage percent for Ray pod managed by Kubernetes + Operator. + + Computed by the following steps + (1) Replicate the logic used by 'docker stats' cli command. + See https://github.com/docker/cli/blob/c0a6b1c7b30203fbc28cd619acb901a95a80e30e/cli/command/container/stats_helpers.go#L166. + (2) Divide by the number of CPUs available to the container, so that + e.g. full capacity use of 2 CPUs will read as 100%, + rather than 200%. + + Step (1) above works by + dividing delta in cpu usage by + delta in total host cpu usage, averaged over host's cpus. + + Since deltas are not initially available, return 0.0 on first call. + """ # noqa + global last_system_usage + global last_cpu_usage + try: + cpu_usage = _cpu_usage() + system_usage = _system_usage() + # Return 0.0 on first call. + if last_system_usage is None: + cpu_percent = 0.0 + else: + cpu_delta = cpu_usage - last_cpu_usage + # "System time passed." (Typically close to clock time.) + system_delta = (system_usage - last_system_usage) / _host_num_cpus() + + quotient = cpu_delta / system_delta + cpu_percent = round(quotient * 100 / get_num_cpus(), 1) + last_system_usage = system_usage + last_cpu_usage = cpu_usage + # Computed percentage might be slightly above 100%. + return min(cpu_percent, 100.0) + except Exception: + logger.exception("Error computing CPU usage of Ray Kubernetes pod.") + return 0.0 + + +def _cpu_usage(): + """Compute total cpu usage of the container in nanoseconds + by reading from cpuacct in cgroups v1 or cpu.stat in cgroups v2.""" + try: + # cgroups v1 + return int(open(CPU_USAGE_PATH).read()) + except FileNotFoundError: + # cgroups v2 + cpu_stat_text = open(CPU_USAGE_PATH_V2).read() + # e.g. "usage_usec 16089294616" + cpu_stat_first_line = cpu_stat_text.split("\n")[0] + # get the second word of the first line, cast as an integer + # this is the CPU usage is microseconds + cpu_usec = int(cpu_stat_first_line.split()[1]) + # Convert to nanoseconds and return. + return cpu_usec * 1000 + + +def _system_usage(): + """ + Computes total CPU usage of the host in nanoseconds. + + Logic taken from here: + https://github.com/moby/moby/blob/b42ac8d370a8ef8ec720dff0ca9dfb3530ac0a6a/daemon/stats/collector_unix.go#L31 + + See also the /proc/stat entry here: + https://man7.org/linux/man-pages/man5/proc.5.html + """ # noqa + cpu_summary_str = open(PROC_STAT_PATH).read().split("\n")[0] + parts = cpu_summary_str.split() + assert parts[0] == "cpu" + usage_data = parts[1:8] + total_clock_ticks = sum(int(entry) for entry in usage_data) + # 100 clock ticks per second, 10^9 ns per second + usage_ns = total_clock_ticks * 10**7 + return usage_ns + + +def _host_num_cpus(): + """Number of physical CPUs, obtained by parsing /proc/stat.""" + global host_num_cpus + if host_num_cpus is None: + proc_stat_lines = open(PROC_STAT_PATH).read().split("\n") + split_proc_stat_lines = [line.split() for line in proc_stat_lines] + cpu_lines = [ + split_line + for split_line in split_proc_stat_lines + if len(split_line) > 0 and "cpu" in split_line[0] + ] + # Number of lines starting with a word including 'cpu', subtracting + # 1 for the first summary line. + host_num_cpus = len(cpu_lines) - 1 + return host_num_cpus diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/memory_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/memory_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ef2d51a1de1cb5f669336f3dd06689227334e217 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/memory_utils.py @@ -0,0 +1,523 @@ +import base64 +import logging +from collections import defaultdict +from enum import Enum +from typing import List + +import ray +from ray._private.internal_api import node_stats +from ray._raylet import ActorID, JobID, TaskID +from ray.dashboard.utils import node_stats_to_dict + +logger = logging.getLogger(__name__) + +# These values are used to calculate if objectRefs are actor handles. +TASKID_BYTES_SIZE = TaskID.size() +ACTORID_BYTES_SIZE = ActorID.size() +JOBID_BYTES_SIZE = JobID.size() + + +def decode_object_ref_if_needed(object_ref: str) -> bytes: + """Decode objectRef bytes string. + + gRPC reply contains an objectRef that is encodded by Base64. + This function is used to decode the objectRef. + Note that there are times that objectRef is already decoded as + a hex string. In this case, just convert it to a binary number. + """ + if object_ref.endswith("="): + # If the object ref ends with =, that means it is base64 encoded. + # Object refs will always have = as a padding + # when it is base64 encoded because objectRef is always 20B. + return base64.standard_b64decode(object_ref) + else: + return ray._common.utils.hex_to_binary(object_ref) + + +class SortingType(Enum): + PID = 1 + OBJECT_SIZE = 3 + REFERENCE_TYPE = 4 + + +class GroupByType(Enum): + NODE_ADDRESS = "node" + STACK_TRACE = "stack_trace" + + +class ReferenceType(Enum): + # We don't use enum because enum is not json serializable. + ACTOR_HANDLE = "ACTOR_HANDLE" + PINNED_IN_MEMORY = "PINNED_IN_MEMORY" + LOCAL_REFERENCE = "LOCAL_REFERENCE" + USED_BY_PENDING_TASK = "USED_BY_PENDING_TASK" + CAPTURED_IN_OBJECT = "CAPTURED_IN_OBJECT" + UNKNOWN_STATUS = "UNKNOWN_STATUS" + + +def get_sorting_type(sort_by: str): + """Translate string input into SortingType instance""" + sort_by = sort_by.upper() + if sort_by == "PID": + return SortingType.PID + elif sort_by == "OBJECT_SIZE": + return SortingType.OBJECT_SIZE + elif sort_by == "REFERENCE_TYPE": + return SortingType.REFERENCE_TYPE + else: + raise Exception( + "The sort-by input provided is not one of\ + PID, OBJECT_SIZE, or REFERENCE_TYPE." + ) + + +def get_group_by_type(group_by: str): + """Translate string input into GroupByType instance""" + group_by = group_by.upper() + if group_by == "NODE_ADDRESS": + return GroupByType.NODE_ADDRESS + elif group_by == "STACK_TRACE": + return GroupByType.STACK_TRACE + else: + raise Exception( + "The group-by input provided is not one of\ + NODE_ADDRESS or STACK_TRACE." + ) + + +class MemoryTableEntry: + def __init__( + self, *, object_ref: dict, node_address: str, is_driver: bool, pid: int + ): + # worker info + self.is_driver = is_driver + self.pid = pid + self.node_address = node_address + + # object info + self.task_status = object_ref.get("taskStatus", "?") + if self.task_status == "NIL": + self.task_status = "-" + self.attempt_number = int(object_ref.get("attemptNumber", 0)) + 1 + self.object_size = int(object_ref.get("objectSize", -1)) + self.call_site = object_ref.get("callSite", "") + if len(self.call_site) == 0: + self.call_site = "disabled" + self.object_ref = ray.ObjectRef( + decode_object_ref_if_needed(object_ref["objectId"]) + ) + + # reference info + self.local_ref_count = int(object_ref.get("localRefCount", 0)) + self.pinned_in_memory = bool(object_ref.get("pinnedInMemory", False)) + self.submitted_task_ref_count = int(object_ref.get("submittedTaskRefCount", 0)) + self.contained_in_owned = [ + ray.ObjectRef(decode_object_ref_if_needed(object_ref)) + for object_ref in object_ref.get("containedInOwned", []) + ] + self.reference_type = self._get_reference_type() + + def is_valid(self) -> bool: + # If the entry doesn't have a reference type or some invalid state, + # (e.g., no object ref presented), it is considered invalid. + if ( + not self.pinned_in_memory + and self.local_ref_count == 0 + and self.submitted_task_ref_count == 0 + and len(self.contained_in_owned) == 0 + ): + return False + elif self.object_ref.is_nil(): + return False + else: + return True + + def group_key(self, group_by_type: GroupByType) -> str: + if group_by_type == GroupByType.NODE_ADDRESS: + return self.node_address + elif group_by_type == GroupByType.STACK_TRACE: + return self.call_site + else: + raise ValueError(f"group by type {group_by_type} is invalid.") + + def _get_reference_type(self) -> str: + if self._is_object_ref_actor_handle(): + return ReferenceType.ACTOR_HANDLE.value + if self.pinned_in_memory: + return ReferenceType.PINNED_IN_MEMORY.value + elif self.submitted_task_ref_count > 0: + return ReferenceType.USED_BY_PENDING_TASK.value + elif self.local_ref_count > 0: + return ReferenceType.LOCAL_REFERENCE.value + elif len(self.contained_in_owned) > 0: + return ReferenceType.CAPTURED_IN_OBJECT.value + else: + return ReferenceType.UNKNOWN_STATUS.value + + def _is_object_ref_actor_handle(self) -> bool: + object_ref_hex = self.object_ref.hex() + + # We need to multiply 2 because we need bits size instead of bytes size. + taskid_random_bits_size = (TASKID_BYTES_SIZE - ACTORID_BYTES_SIZE) * 2 + actorid_random_bits_size = (ACTORID_BYTES_SIZE - JOBID_BYTES_SIZE) * 2 + + # random (8B) | ActorID(6B) | flag (2B) | index (6B) + # ActorID(6B) == ActorRandomByte(4B) + JobID(2B) + # If random bytes are all 'f', but ActorRandomBytes + # are not all 'f', that means it is an actor creation + # task, which is an actor handle. + random_bits = object_ref_hex[:taskid_random_bits_size] + actor_random_bits = object_ref_hex[ + taskid_random_bits_size : taskid_random_bits_size + actorid_random_bits_size + ] + if random_bits == "f" * 16 and not actor_random_bits == "f" * 24: + return True + else: + return False + + def as_dict(self): + return { + "object_ref": self.object_ref.hex(), + "pid": self.pid, + "node_ip_address": self.node_address, + "object_size": self.object_size, + "reference_type": self.reference_type, + "call_site": self.call_site, + "task_status": self.task_status, + "attempt_number": self.attempt_number, + "local_ref_count": self.local_ref_count, + "pinned_in_memory": self.pinned_in_memory, + "submitted_task_ref_count": self.submitted_task_ref_count, + "contained_in_owned": [ + object_ref.hex() for object_ref in self.contained_in_owned + ], + "type": "Driver" if self.is_driver else "Worker", + } + + def __str__(self): + return self.__repr__() + + def __repr__(self): + return str(self.as_dict()) + + +class MemoryTable: + def __init__( + self, + entries: List[MemoryTableEntry], + group_by_type: GroupByType = GroupByType.NODE_ADDRESS, + sort_by_type: SortingType = SortingType.PID, + ): + self.table = entries + # Group is a list of memory tables grouped by a group key. + self.group = {} + self.summary = defaultdict(int) + # NOTE YOU MUST SORT TABLE BEFORE GROUPING. + # self._group_by(..)._sort_by(..) != self._sort_by(..)._group_by(..) + if group_by_type and sort_by_type: + self.setup(group_by_type, sort_by_type) + elif group_by_type: + self._group_by(group_by_type) + elif sort_by_type: + self._sort_by(sort_by_type) + + def setup(self, group_by_type: GroupByType, sort_by_type: SortingType): + """Setup memory table. + + This will sort entries first and group them after. + Sort order will be still kept. + """ + self._sort_by(sort_by_type)._group_by(group_by_type) + for group_memory_table in self.group.values(): + group_memory_table.summarize() + self.summarize() + return self + + def insert_entry(self, entry: MemoryTableEntry): + self.table.append(entry) + + def summarize(self): + # Reset summary. + total_object_size = 0 + total_local_ref_count = 0 + total_pinned_in_memory = 0 + total_used_by_pending_task = 0 + total_captured_in_objects = 0 + total_actor_handles = 0 + + for entry in self.table: + if entry.object_size > 0: + total_object_size += entry.object_size + if entry.reference_type == ReferenceType.LOCAL_REFERENCE.value: + total_local_ref_count += 1 + elif entry.reference_type == ReferenceType.PINNED_IN_MEMORY.value: + total_pinned_in_memory += 1 + elif entry.reference_type == ReferenceType.USED_BY_PENDING_TASK.value: + total_used_by_pending_task += 1 + elif entry.reference_type == ReferenceType.CAPTURED_IN_OBJECT.value: + total_captured_in_objects += 1 + elif entry.reference_type == ReferenceType.ACTOR_HANDLE.value: + total_actor_handles += 1 + + self.summary = { + "total_object_size": total_object_size, + "total_local_ref_count": total_local_ref_count, + "total_pinned_in_memory": total_pinned_in_memory, + "total_used_by_pending_task": total_used_by_pending_task, + "total_captured_in_objects": total_captured_in_objects, + "total_actor_handles": total_actor_handles, + } + return self + + def _sort_by(self, sorting_type: SortingType): + if sorting_type == SortingType.PID: + self.table.sort(key=lambda entry: entry.pid) + elif sorting_type == SortingType.OBJECT_SIZE: + self.table.sort(key=lambda entry: entry.object_size) + elif sorting_type == SortingType.REFERENCE_TYPE: + self.table.sort(key=lambda entry: entry.reference_type) + else: + raise ValueError(f"Give sorting type: {sorting_type} is invalid.") + return self + + def _group_by(self, group_by_type: GroupByType): + """Group entries and summarize the result. + + NOTE: Each group is another MemoryTable. + """ + # Reset group + self.group = {} + + # Build entries per group. + group = defaultdict(list) + for entry in self.table: + group[entry.group_key(group_by_type)].append(entry) + + # Build a group table. + for group_key, entries in group.items(): + self.group[group_key] = MemoryTable( + entries, group_by_type=None, sort_by_type=None + ) + for group_key, group_memory_table in self.group.items(): + group_memory_table.summarize() + return self + + def as_dict(self): + return { + "summary": self.summary, + "group": { + group_key: { + "entries": group_memory_table.get_entries(), + "summary": group_memory_table.summary, + } + for group_key, group_memory_table in self.group.items() + }, + } + + def get_entries(self) -> List[dict]: + return [entry.as_dict() for entry in self.table] + + def __repr__(self): + return str(self.as_dict()) + + def __str__(self): + return self.__repr__() + + +def construct_memory_table( + workers_stats: List, + group_by: GroupByType = GroupByType.NODE_ADDRESS, + sort_by=SortingType.OBJECT_SIZE, +) -> MemoryTable: + memory_table_entries = [] + for core_worker_stats in workers_stats: + pid = core_worker_stats["pid"] + is_driver = core_worker_stats.get("workerType") == "DRIVER" + node_address = core_worker_stats["ipAddress"] + object_refs = core_worker_stats.get("objectRefs", []) + + for object_ref in object_refs: + memory_table_entry = MemoryTableEntry( + object_ref=object_ref, + node_address=node_address, + is_driver=is_driver, + pid=pid, + ) + if memory_table_entry.is_valid(): + memory_table_entries.append(memory_table_entry) + memory_table = MemoryTable( + memory_table_entries, group_by_type=group_by, sort_by_type=sort_by + ) + return memory_table + + +def track_reference_size(group): + """Returns dictionary mapping reference type + to memory usage for a given memory table group.""" + d = defaultdict(int) + table_name = { + "LOCAL_REFERENCE": "total_local_ref_count", + "PINNED_IN_MEMORY": "total_pinned_in_memory", + "USED_BY_PENDING_TASK": "total_used_by_pending_task", + "CAPTURED_IN_OBJECT": "total_captured_in_objects", + "ACTOR_HANDLE": "total_actor_handles", + } + for entry in group["entries"]: + size = entry["object_size"] + if size == -1: + # size not recorded + size = 0 + d[table_name[entry["reference_type"]]] += size + return d + + +def memory_summary( + state, + group_by="NODE_ADDRESS", + sort_by="OBJECT_SIZE", + line_wrap=True, + unit="B", + num_entries=None, +) -> str: + # Get terminal size + import shutil + + size = shutil.get_terminal_size((80, 20)).columns + line_wrap_threshold = 137 + + # Unit conversions + units = {"B": 10**0, "KB": 10**3, "MB": 10**6, "GB": 10**9} + + # Fetch core memory worker stats, store as a dictionary + core_worker_stats = [] + for raylet in state.node_table(): + if not raylet["Alive"]: + continue + try: + stats = node_stats_to_dict( + node_stats(raylet["NodeManagerAddress"], raylet["NodeManagerPort"]) + ) + except RuntimeError: + continue + core_worker_stats.extend(stats["coreWorkersStats"]) + assert type(stats) is dict and "coreWorkersStats" in stats + + # Build memory table with "group_by" and "sort_by" parameters + group_by, sort_by = get_group_by_type(group_by), get_sorting_type(sort_by) + memory_table = construct_memory_table( + core_worker_stats, group_by, sort_by + ).as_dict() + assert "summary" in memory_table and "group" in memory_table + + # Build memory summary + mem = "" + group_by, sort_by = group_by.name.lower().replace( + "_", " " + ), sort_by.name.lower().replace("_", " ") + summary_labels = [ + "Mem Used by Objects", + "Local References", + "Pinned", + "Used by task", + "Captured in Objects", + "Actor Handles", + ] + summary_string = "{:<19} {:<16} {:<12} {:<13} {:<19} {:<13}\n" + + object_ref_labels = [ + "IP Address", + "PID", + "Type", + "Call Site", + "Status", + "Attampt", + "Size", + "Reference Type", + "Object Ref", + ] + object_ref_string = "{:<13} | {:<8} | {:<7} | {:<9} \ +| {:<9} | {:<8} | {:<8} | {:<14} | {:<10}\n" + + if size > line_wrap_threshold and line_wrap: + object_ref_string = "{:<15} {:<5} {:<6} {:<22} {:<14} {:<8} {:<6} \ +{:<18} {:<56}\n" + + mem += f"Grouping by {group_by}...\ + Sorting by {sort_by}...\ + Display {num_entries if num_entries is not None else 'all'}\ +entries per group...\n\n\n" + + for key, group in memory_table["group"].items(): + # Group summary + summary = group["summary"] + ref_size = track_reference_size(group) + for k, v in summary.items(): + if k == "total_object_size": + summary[k] = str(v / units[unit]) + f" {unit}" + else: + summary[k] = str(v) + f", ({ref_size[k] / units[unit]} {unit})" + mem += f"--- Summary for {group_by}: {key} ---\n" + mem += summary_string.format(*summary_labels) + mem += summary_string.format(*summary.values()) + "\n" + + # Memory table per group + mem += f"--- Object references for {group_by}: {key} ---\n" + mem += object_ref_string.format(*object_ref_labels) + n = 1 # Counter for num entries per group + for entry in group["entries"]: + if num_entries is not None and n > num_entries: + break + entry["object_size"] = ( + str(entry["object_size"] / units[unit]) + f" {unit}" + if entry["object_size"] > -1 + else "?" + ) + num_lines = 1 + if size > line_wrap_threshold and line_wrap: + call_site_length = 22 + if len(entry["call_site"]) == 0: + entry["call_site"] = ["disabled"] + else: + entry["call_site"] = [ + entry["call_site"][i : i + call_site_length] + for i in range(0, len(entry["call_site"]), call_site_length) + ] + + task_status_length = 12 + entry["task_status"] = [ + entry["task_status"][i : i + task_status_length] + for i in range(0, len(entry["task_status"]), task_status_length) + ] + num_lines = max(len(entry["call_site"]), len(entry["task_status"])) + + else: + mem += "\n" + object_ref_values = [ + entry["node_ip_address"], + entry["pid"], + entry["type"], + entry["call_site"], + entry["task_status"], + entry["attempt_number"], + entry["object_size"], + entry["reference_type"], + entry["object_ref"], + ] + for i in range(len(object_ref_values)): + if not isinstance(object_ref_values[i], list): + object_ref_values[i] = [object_ref_values[i]] + object_ref_values[i].extend( + ["" for x in range(num_lines - len(object_ref_values[i]))] + ) + for i in range(num_lines): + row = [elem[i] for elem in object_ref_values] + mem += object_ref_string.format(*row) + mem += "\n" + n += 1 + + mem += ( + "To record callsite information for each ObjectRef created, set " + "env variable RAY_record_ref_creation_sites=1\n\n" + ) + + return mem diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/optional_deps.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/optional_deps.py new file mode 100644 index 0000000000000000000000000000000000000000..c8f60a7bbeda8a5be9d543a941b9f70b4bfe6264 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/optional_deps.py @@ -0,0 +1,27 @@ +# These imports determine whether or not a user has the required dependencies +# to launch the optional dashboard API server. +# If any of these imports fail, the dashboard API server will not be launched. +# Please add important dashboard-api dependencies to this list. + +import aiohttp # noqa: F401 +import aiohttp.web # noqa: F401 +import aiohttp_cors # noqa: F401 +import grpc # noqa: F401 + +# These checks have to come first because aiohttp looks +# for opencensus, too, and raises a different error otherwise. +import opencensus # noqa: F401 +import opentelemetry # noqa: F401 +import opentelemetry.exporter.prometheus # noqa: F401 +import opentelemetry.proto # noqa: F401 +import prometheus_client # noqa: F401 +import pydantic # noqa: F401 +from aiohttp import hdrs # noqa: F401 +from aiohttp.typedefs import PathLike # noqa: F401 +from aiohttp.web import ( + Request, # noqa: F401 + RouteDef, # noqa: F401 +) + +# Adding new modules should also be reflected in the +# python/ray/tests/test_minimal_install.py diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/optional_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/optional_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..94311565e24604bb3ff92682f506ce4f66820c5b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/optional_utils.py @@ -0,0 +1,197 @@ +""" +Optional utils module contains utility methods +that require optional dependencies. +""" +import asyncio +import collections +import functools +import inspect +import logging +import os +import time +import traceback +from collections import namedtuple +from typing import Callable, Union + +from aiohttp.web import Request, Response + +import ray +import ray.dashboard.consts as dashboard_consts +import ray.dashboard.utils as dashboard_utils +from ray._private.ray_constants import RAY_INTERNAL_DASHBOARD_NAMESPACE, env_bool + +# All third-party dependencies that are not included in the minimal Ray +# installation must be included in this file. This allows us to determine if +# the agent has the necessary dependencies to be started. +from ray.dashboard.optional_deps import aiohttp, hdrs +from ray.dashboard.routes import method_route_table_factory, rest_response +from ray.dashboard.utils import ( + DashboardAgentModule, + DashboardHeadModule, +) + +try: + create_task = asyncio.create_task +except AttributeError: + create_task = asyncio.ensure_future + + +logger = logging.getLogger(__name__) + +DashboardHeadRouteTable = method_route_table_factory() +DashboardAgentRouteTable = method_route_table_factory() + + +# The cache value type used by aiohttp_cache. +_AiohttpCacheValue = namedtuple("AiohttpCacheValue", ["data", "expiration", "task"]) +# The methods with no request body used by aiohttp_cache. +_AIOHTTP_CACHE_NOBODY_METHODS = {hdrs.METH_GET, hdrs.METH_DELETE} + + +def aiohttp_cache( + ttl_seconds=dashboard_consts.AIOHTTP_CACHE_TTL_SECONDS, + maxsize=dashboard_consts.AIOHTTP_CACHE_MAX_SIZE, + enable=not env_bool(dashboard_consts.AIOHTTP_CACHE_DISABLE_ENVIRONMENT_KEY, False), +): + assert maxsize > 0 + cache = collections.OrderedDict() + + def _wrapper(handler): + if enable: + + @functools.wraps(handler) + async def _cache_handler(*args) -> aiohttp.web.Response: + # Make the route handler as a bound method. + # The args may be: + # * (Request, ) + # * (self, Request) + req = args[-1] + # If nocache=1 in query string, bypass cache. + if req.query.get("nocache") == "1": + return await handler(*args) + + # Make key. + if req.method in _AIOHTTP_CACHE_NOBODY_METHODS: + key = req.path_qs + else: + key = (req.path_qs, await req.read()) + # Query cache. + value = cache.get(key) + if value is not None: + cache.move_to_end(key) + if not value.task.done() or value.expiration >= time.time(): + # Update task not done or the data is not expired. + return aiohttp.web.Response(**value.data) + + def _update_cache(task): + try: + response = task.result() + except Exception: + response = rest_response( + status_code=dashboard_utils.HTTPStatusCode.INTERNAL_ERROR, + message=traceback.format_exc(), + ) + data = { + "status": response.status, + "headers": dict(response.headers), + "body": response.body, + } + cache[key] = _AiohttpCacheValue( + data, time.time() + ttl_seconds, task + ) + cache.move_to_end(key) + if len(cache) > maxsize: + cache.popitem(last=False) + return response + + task = create_task(handler(*args)) + task.add_done_callback(_update_cache) + if value is None: + return await task + else: + return aiohttp.web.Response(**value.data) + + suffix = f"[cache ttl={ttl_seconds}, max_size={maxsize}]" + _cache_handler.__name__ += suffix + _cache_handler.__qualname__ += suffix + return _cache_handler + else: + return handler + + if inspect.iscoroutinefunction(ttl_seconds): + target_func = ttl_seconds + ttl_seconds = dashboard_consts.AIOHTTP_CACHE_TTL_SECONDS + return _wrapper(target_func) + else: + return _wrapper + + +def is_browser_request(req: Request) -> bool: + """Checks if a request is made by a browser like user agent. + + This heuristic is very weak, but hard for a browser to bypass- eg, + fetch/xhr and friends cannot alter the user-agent, but requests made with + an http library can stumble into this if they choose to user a browser like + user agent. + """ + return req.headers["User-Agent"].startswith("Mozilla") + + +def deny_browser_requests() -> Callable: + """Reject any requests that appear to be made by a browser""" + + def decorator_factory(f: Callable) -> Callable: + @functools.wraps(f) + async def decorator(self, req: Request): + if is_browser_request(req): + return Response( + text="Browser requests not allowed", + status=aiohttp.web.HTTPMethodNotAllowed.status_code, + ) + return await f(self, req) + + return decorator + + return decorator_factory + + +def init_ray_and_catch_exceptions() -> Callable: + """Decorator to be used on methods that require being connected to Ray.""" + + def decorator_factory(f: Callable) -> Callable: + @functools.wraps(f) + async def decorator( + self: Union[DashboardAgentModule, DashboardHeadModule], *args, **kwargs + ): + try: + if not ray.is_initialized(): + try: + address = self.gcs_address + logger.info(f"Connecting to ray with address={address}") + # Set the gcs rpc timeout to shorter + os.environ["RAY_gcs_server_request_timeout_seconds"] = str( + dashboard_consts.GCS_RPC_TIMEOUT_SECONDS + ) + # Init ray without logging to driver + # to avoid infinite logging issue. + ray.init( + address=address, + log_to_driver=False, + configure_logging=False, + namespace=RAY_INTERNAL_DASHBOARD_NAMESPACE, + _skip_env_hook=True, + ) + except Exception as e: + ray.shutdown() + raise e from None + return await f(self, *args, **kwargs) + except Exception as e: + logger.exception(f"Unexpected error in handler: {e}") + return Response( + text=traceback.format_exc(), + status=aiohttp.web.HTTPInternalServerError.status_code, + ) + + return decorator + + return decorator_factory diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/routes.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/routes.py new file mode 100644 index 0000000000000000000000000000000000000000..cce72f2dea11713cfbc8df9b12988d620f42756d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/routes.py @@ -0,0 +1,212 @@ +import abc +import collections +import functools +import inspect +import json +import logging +import os +import traceback +from typing import Any + +from ray.dashboard.optional_deps import PathLike, RouteDef, aiohttp, hdrs +from ray.dashboard.utils import CustomEncoder, HTTPStatusCode, to_google_style + +logger = logging.getLogger(__name__) + + +class BaseRouteTable(abc.ABC): + """A base class to bind http route to a target instance. Subclass should implement + the _register_route method. It should define how the handler interacts with + _BindInfo.instance. + + Subclasses must declare their own _bind_map and _routes properties to avoid + conflicts. + """ + + class _BindInfo: + def __init__(self, filename, lineno, instance): + self.filename = filename + self.lineno = lineno + self.instance = instance + + @classmethod + @property + @abc.abstractmethod + def _bind_map(cls): + pass + + @classmethod + @property + @abc.abstractmethod + def _routes(cls): + pass + + @classmethod + @abc.abstractmethod + def _register_route(cls, method, path, **kwargs): + pass + + @classmethod + @abc.abstractmethod + def bind(cls, instance): + pass + + @classmethod + def routes(cls): + return cls._routes + + @classmethod + def bound_routes(cls): + bound_items = [] + for r in cls._routes._items: + if isinstance(r, RouteDef): + route_method = r.handler.__route_method__ + route_path = r.handler.__route_path__ + instance = cls._bind_map[route_method][route_path].instance + if instance is not None: + bound_items.append(r) + else: + bound_items.append(r) + routes = aiohttp.web.RouteTableDef() + routes._items = bound_items + return routes + + @classmethod + def head(cls, path, **kwargs): + return cls._register_route(hdrs.METH_HEAD, path, **kwargs) + + @classmethod + def get(cls, path, **kwargs): + return cls._register_route(hdrs.METH_GET, path, **kwargs) + + @classmethod + def post(cls, path, **kwargs): + return cls._register_route(hdrs.METH_POST, path, **kwargs) + + @classmethod + def put(cls, path, **kwargs): + return cls._register_route(hdrs.METH_PUT, path, **kwargs) + + @classmethod + def patch(cls, path, **kwargs): + return cls._register_route(hdrs.METH_PATCH, path, **kwargs) + + @classmethod + def delete(cls, path, **kwargs): + return cls._register_route(hdrs.METH_DELETE, path, **kwargs) + + @classmethod + def view(cls, path, **kwargs): + return cls._register_route(hdrs.METH_ANY, path, **kwargs) + + @classmethod + def static(cls, prefix: str, path: PathLike, **kwargs: Any) -> None: + cls._routes.static(prefix, path, **kwargs) + + +def method_route_table_factory(): + """ + Return a method-based route table class, for in-process HeadModule objects. + """ + + class MethodRouteTable(BaseRouteTable): + """A helper class to bind http route to class method. Each _BindInfo.instance + is a class instance, and for an inbound request, we invoke the async handler + method.""" + + _bind_map = collections.defaultdict(dict) + _routes = aiohttp.web.RouteTableDef() + + @classmethod + def _register_route(cls, method, path, **kwargs): + def _wrapper(handler): + if path in cls._bind_map[method]: + bind_info = cls._bind_map[method][path] + raise Exception( + f"Duplicated route path: {path}, " + f"previous one registered at " + f"{bind_info.filename}:{bind_info.lineno}" + ) + + bind_info = cls._BindInfo( + handler.__code__.co_filename, handler.__code__.co_firstlineno, None + ) + + @functools.wraps(handler) + async def _handler_route(*args) -> aiohttp.web.Response: + try: + # Make the route handler as a bound method. + # The args may be: + # * (Request, ) + # * (self, Request) + req = args[-1] + return await handler(bind_info.instance, req) + except Exception: + logger.exception("Handle %s %s failed.", method, path) + return rest_response( + status_code=HTTPStatusCode.INTERNAL_ERROR, + message=traceback.format_exc(), + ) + + cls._bind_map[method][path] = bind_info + _handler_route.__route_method__ = method + _handler_route.__route_path__ = path + return cls._routes.route(method, path, **kwargs)(_handler_route) + + return _wrapper + + @classmethod + def bind(cls, instance): + def predicate(o): + if inspect.ismethod(o): + return hasattr(o, "__route_method__") and hasattr( + o, "__route_path__" + ) + return False + + handler_routes = inspect.getmembers(instance, predicate) + for _, h in handler_routes: + cls._bind_map[h.__func__.__route_method__][ + h.__func__.__route_path__ + ].instance = instance + + return MethodRouteTable + + +def rest_response( + status_code: HTTPStatusCode, + message: str, + convert_google_style: bool = True, + **kwargs, +) -> aiohttp.web.Response: + """ + Args: + status_code: HTTPStatusCode + The HTTP status code of the response. + message: str + The message of the response. + convert_google_style: bool + Whether to convert the response to google style. + + Returns: + aiohttp.web.Response + """ + # In the dev context we allow a dev server running on a + # different port to consume the API, meaning we need to allow + # cross-origin access + if os.environ.get("RAY_DASHBOARD_DEV") == "1": + headers = {"Access-Control-Allow-Origin": "*"} + else: + headers = {} + + success = status_code == HTTPStatusCode.OK + return aiohttp.web.json_response( + { + "result": success, + "msg": message, + "data": to_google_style(kwargs) if convert_google_style else kwargs, + }, + dumps=functools.partial(json.dumps, cls=CustomEncoder), + headers=headers, + status=status_code, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/state_aggregator.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/state_aggregator.py new file mode 100644 index 0000000000000000000000000000000000000000..70b939ddde4fcd5883257ac1e27abf29abd3b178 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/state_aggregator.py @@ -0,0 +1,671 @@ +import asyncio +import logging +from concurrent.futures import ThreadPoolExecutor +from itertools import islice +from typing import List, Optional + +import ray.dashboard.memory_utils as memory_utils +from ray import NodeID +from ray._common.utils import get_or_create_event_loop +from ray._private.profiling import chrome_tracing_dump +from ray._private.ray_constants import env_integer +from ray.dashboard.state_api_utils import do_filter +from ray.dashboard.utils import compose_state_message +from ray.runtime_env import RuntimeEnv +from ray.util.state.common import ( + RAY_MAX_LIMIT_FROM_API_SERVER, + ActorState, + ActorSummaries, + JobState, + ListApiOptions, + ListApiResponse, + NodeState, + ObjectState, + ObjectSummaries, + PlacementGroupState, + RuntimeEnvState, + StateSummary, + SummaryApiOptions, + SummaryApiResponse, + TaskState, + TaskSummaries, + WorkerState, + protobuf_message_to_dict, + protobuf_to_task_state_dict, +) +from ray.util.state.state_manager import DataSourceUnavailable, StateDataSourceClient + +logger = logging.getLogger(__name__) + +GCS_QUERY_FAILURE_WARNING = ( + "Failed to query data from GCS. It is due to " + "(1) GCS is unexpectedly failed. " + "(2) GCS is overloaded. " + "(3) There's an unexpected network issue. " + "Please check the gcs_server.out log to find the root cause." +) +NODE_QUERY_FAILURE_WARNING = ( + "Failed to query data from {type}. " + "Queried {total} {type} " + "and {network_failures} {type} failed to reply. It is due to " + "(1) {type} is unexpectedly failed. " + "(2) {type} is overloaded. " + "(3) There's an unexpected network issue. Please check the " + "{log_command} to find the root cause." +) + + +# TODO(sang): Move the class to state/state_manager.py. +# TODO(sang): Remove *State and replaces with Pydantic or protobuf. +# (depending on API interface standardization). +class StateAPIManager: + """A class to query states from data source, caches, and post-processes + the entries. + """ + + def __init__( + self, + state_data_source_client: StateDataSourceClient, + thread_pool_executor: ThreadPoolExecutor, + ): + self._client = state_data_source_client + self._thread_pool_executor = thread_pool_executor + + @property + def data_source_client(self): + return self._client + + async def list_actors(self, *, option: ListApiOptions) -> ListApiResponse: + """List all actor information from the cluster. + + Returns: + {actor_id -> actor_data_in_dict} + actor_data_in_dict's schema is in ActorState + + """ + try: + reply = await self._client.get_all_actor_info( + timeout=option.timeout, filters=option.filters + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [] + for message in reply.actor_table_data: + # Note: this is different from actor_table_data_to_dict in actor_head.py + # because we set preserving_proto_field_name=True so fields are + # snake_case, while actor_table_data_to_dict in actor_head.py is + # camelCase. + # TODO(ryw): modify actor_table_data_to_dict to use snake_case, and + # consolidate the code. + data = protobuf_message_to_dict( + message=message, + fields_to_decode=[ + "actor_id", + "owner_id", + "job_id", + "node_id", + "placement_group_id", + ], + ) + result.append(data) + + num_after_truncation = len(result) + reply.num_filtered + result = do_filter(result, option.filters, ActorState, option.detail) + num_filtered = len(result) + + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["actor_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_placement_groups(self, *, option: ListApiOptions) -> ListApiResponse: + """List all placement group information from the cluster. + + Returns: + {pg_id -> pg_data_in_dict} + pg_data_in_dict's schema is in PlacementGroupState + """ + try: + reply = await self._client.get_all_placement_group_info( + timeout=option.timeout + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [] + for message in reply.placement_group_table_data: + data = protobuf_message_to_dict( + message=message, + fields_to_decode=[ + "placement_group_id", + "creator_job_id", + "node_id", + ], + ) + result.append(data) + num_after_truncation = len(result) + + result = do_filter( + result, option.filters, PlacementGroupState, option.detail + ) + num_filtered = len(result) + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["placement_group_id"]) + return ListApiResponse( + result=list(islice(result, option.limit)), + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_nodes(self, *, option: ListApiOptions) -> ListApiResponse: + """List all node information from the cluster. + + Returns: + {node_id -> node_data_in_dict} + node_data_in_dict's schema is in NodeState + """ + try: + reply = await self._client.get_all_node_info( + timeout=option.timeout, filters=option.filters + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [] + for message in reply.node_info_list: + data = protobuf_message_to_dict( + message=message, fields_to_decode=["node_id"] + ) + data["node_ip"] = data["node_manager_address"] + data["start_time_ms"] = int(data["start_time_ms"]) + data["end_time_ms"] = int(data["end_time_ms"]) + death_info = data.get("death_info", {}) + data["state_message"] = compose_state_message( + death_info.get("reason", None), + death_info.get("reason_message", None), + ) + + result.append(data) + + num_after_truncation = len(result) + reply.num_filtered + result = do_filter(result, option.filters, NodeState, option.detail) + num_filtered = len(result) + + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["node_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_workers(self, *, option: ListApiOptions) -> ListApiResponse: + """List all worker information from the cluster. + + Returns: + {worker_id -> worker_data_in_dict} + worker_data_in_dict's schema is in WorkerState + """ + try: + reply = await self._client.get_all_worker_info( + timeout=option.timeout, + filters=option.filters, + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + + result = [] + for message in reply.worker_table_data: + data = protobuf_message_to_dict( + message=message, fields_to_decode=["worker_id", "raylet_id"] + ) + data["worker_id"] = data["worker_address"]["worker_id"] + data["node_id"] = data["worker_address"]["raylet_id"] + data["ip"] = data["worker_address"]["ip_address"] + data["start_time_ms"] = int(data["start_time_ms"]) + data["end_time_ms"] = int(data["end_time_ms"]) + data["worker_launch_time_ms"] = int(data["worker_launch_time_ms"]) + data["worker_launched_time_ms"] = int(data["worker_launched_time_ms"]) + result.append(data) + + num_after_truncation = len(result) + reply.num_filtered + result = do_filter(result, option.filters, WorkerState, option.detail) + num_filtered = len(result) + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["worker_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=reply.total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_jobs(self, *, option: ListApiOptions) -> ListApiResponse: + try: + reply = await self._client.get_job_info(timeout=option.timeout) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + result = [job.dict() for job in reply] + total = len(result) + result = do_filter(result, option.filters, JobState, option.detail) + num_filtered = len(result) + result.sort(key=lambda entry: entry["job_id"] or "") + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + total=total, + num_after_truncation=total, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_tasks(self, *, option: ListApiOptions) -> ListApiResponse: + """List all task information from the cluster. + + Returns: + {task_id -> task_data_in_dict} + task_data_in_dict's schema is in TaskState + """ + try: + reply = await self._client.get_all_task_info( + timeout=option.timeout, + filters=option.filters, + exclude_driver=option.exclude_driver, + ) + except DataSourceUnavailable: + raise DataSourceUnavailable(GCS_QUERY_FAILURE_WARNING) + + def transform(reply) -> ListApiResponse: + """ + Transforms from proto to dict, applies filters, sorts, and truncates. + This function is executed in a separate thread. + """ + result = [ + protobuf_to_task_state_dict(message) for message in reply.events_by_task + ] + + # Num pre-truncation is the number of tasks returned from + # source + num filtered on source + num_after_truncation = len(result) + num_total = len(result) + reply.num_status_task_events_dropped + + # Only certain filters are done on GCS, so here the filter function is still + # needed to apply all the filters + result = do_filter(result, option.filters, TaskState, option.detail) + num_filtered = len(result) + + result.sort(key=lambda entry: entry["task_id"]) + result = list(islice(result, option.limit)) + + # TODO(rickyx): we could do better with the warning logic. It's messy now. + return ListApiResponse( + result=result, + total=num_total, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + # In the error case + if reply.status.code != 0: + return ListApiResponse( + result=[], + total=0, + num_after_truncation=0, + num_filtered=0, + warnings=[reply.status.message], + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, reply + ) + + async def list_objects(self, *, option: ListApiOptions) -> ListApiResponse: + """List all object information from the cluster. + + Returns: + {object_id -> object_data_in_dict} + object_data_in_dict's schema is in ObjectState + """ + all_node_info_reply = await self._client.get_all_node_info( + timeout=option.timeout, + limit=None, + filters=[("state", "=", "ALIVE")], + ) + tasks = [ + self._client.get_object_info( + node_info.node_manager_address, + node_info.node_manager_port, + timeout=option.timeout, + ) + for node_info in all_node_info_reply.node_info_list + ] + + replies = await asyncio.gather( + *tasks, + return_exceptions=True, + ) + + def transform(replies) -> ListApiResponse: + unresponsive_nodes = 0 + worker_stats = [] + total_objects = 0 + for reply in replies: + if isinstance(reply, DataSourceUnavailable): + unresponsive_nodes += 1 + continue + elif isinstance(reply, Exception): + raise reply + + total_objects += reply.total + for core_worker_stat in reply.core_workers_stats: + # NOTE: Set preserving_proto_field_name=False here because + # `construct_memory_table` requires a dictionary that has + # modified protobuf name + # (e.g., workerId instead of worker_id) as a key. + worker_stats.append( + protobuf_message_to_dict( + message=core_worker_stat, + fields_to_decode=["object_id"], + preserving_proto_field_name=False, + ) + ) + + partial_failure_warning = None + if len(tasks) > 0 and unresponsive_nodes > 0: + warning_msg = NODE_QUERY_FAILURE_WARNING.format( + type="raylet", + total=len(tasks), + network_failures=unresponsive_nodes, + log_command="raylet.out", + ) + if unresponsive_nodes == len(tasks): + raise DataSourceUnavailable(warning_msg) + partial_failure_warning = ( + f"The returned data may contain incomplete result. {warning_msg}" + ) + + result = [] + memory_table = memory_utils.construct_memory_table(worker_stats) + for entry in memory_table.table: + data = entry.as_dict() + # `construct_memory_table` returns object_ref field which is indeed + # object_id. We do transformation here. + # TODO(sang): Refactor `construct_memory_table`. + data["object_id"] = data["object_ref"] + del data["object_ref"] + data["ip"] = data["node_ip_address"] + del data["node_ip_address"] + data["type"] = data["type"].upper() + data["task_status"] = ( + "NIL" if data["task_status"] == "-" else data["task_status"] + ) + result.append(data) + + # Add callsite warnings if it is not configured. + callsite_warning = [] + callsite_enabled = env_integer("RAY_record_ref_creation_sites", 0) + if not callsite_enabled: + callsite_warning.append( + "Callsite is not being recorded. " + "To record callsite information for each ObjectRef created, set " + "env variable RAY_record_ref_creation_sites=1 during `ray start` " + "and `ray.init`." + ) + + num_after_truncation = len(result) + result = do_filter(result, option.filters, ObjectState, option.detail) + num_filtered = len(result) + # Sort to make the output deterministic. + result.sort(key=lambda entry: entry["object_id"]) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + partial_failure_warning=partial_failure_warning, + total=total_objects, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + warnings=callsite_warning, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, replies + ) + + async def list_runtime_envs(self, *, option: ListApiOptions) -> ListApiResponse: + """List all runtime env information from the cluster. + + Returns: + A list of runtime env information in the cluster. + The schema of returned "dict" is equivalent to the + `RuntimeEnvState` protobuf message. + We don't have id -> data mapping like other API because runtime env + doesn't have unique ids. + """ + live_node_info_reply = await self._client.get_all_node_info( + timeout=option.timeout, + limit=None, + filters=[("state", "=", "ALIVE")], + ) + node_infos = [ + node_info + for node_info in live_node_info_reply.node_info_list + if node_info.runtime_env_agent_port is not None + ] + tasks = [ + self._client.get_runtime_envs_info( + node_info.node_manager_address, + node_info.runtime_env_agent_port, + timeout=option.timeout, + ) + for node_info in node_infos + ] + + replies = await asyncio.gather( + *tasks, + return_exceptions=True, + ) + + def transform(replies) -> ListApiResponse: + result = [] + unresponsive_nodes = 0 + total_runtime_envs = 0 + for node_info, reply in zip(node_infos, replies): + if isinstance(reply, DataSourceUnavailable): + unresponsive_nodes += 1 + continue + elif isinstance(reply, Exception): + raise reply + + total_runtime_envs += reply.total + states = reply.runtime_env_states + for state in states: + data = protobuf_message_to_dict(message=state, fields_to_decode=[]) + # Need to deserialize this field. + data["runtime_env"] = RuntimeEnv.deserialize( + data["runtime_env"] + ).to_dict() + data["node_id"] = NodeID(node_info.node_id).hex() + result.append(data) + + partial_failure_warning = None + if len(tasks) > 0 and unresponsive_nodes > 0: + warning_msg = NODE_QUERY_FAILURE_WARNING.format( + type="agent", + total=len(tasks), + network_failures=unresponsive_nodes, + log_command="dashboard_agent.log", + ) + if unresponsive_nodes == len(tasks): + raise DataSourceUnavailable(warning_msg) + partial_failure_warning = ( + f"The returned data may contain incomplete result. {warning_msg}" + ) + num_after_truncation = len(result) + result = do_filter(result, option.filters, RuntimeEnvState, option.detail) + num_filtered = len(result) + + # Sort to make the output deterministic. + def sort_func(entry): + # If creation time is not there yet (runtime env is failed + # to be created or not created yet, they are the highest priority. + # Otherwise, "bigger" creation time is coming first. + if "creation_time_ms" not in entry: + return float("inf") + elif entry["creation_time_ms"] is None: + return float("inf") + else: + return float(entry["creation_time_ms"]) + + result.sort(key=sort_func, reverse=True) + result = list(islice(result, option.limit)) + return ListApiResponse( + result=result, + partial_failure_warning=partial_failure_warning, + total=total_runtime_envs, + num_after_truncation=num_after_truncation, + num_filtered=num_filtered, + ) + + return await get_or_create_event_loop().run_in_executor( + self._thread_pool_executor, transform, replies + ) + + async def summarize_tasks(self, option: SummaryApiOptions) -> SummaryApiResponse: + summary_by = option.summary_by or "func_name" + if summary_by not in ["func_name", "lineage"]: + raise ValueError('summary_by must be one of "func_name" or "lineage".') + + # For summary, try getting as many entries as possible to minimze data loss. + result = await self.list_tasks( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + filters=option.filters, + detail=summary_by == "lineage", + ) + ) + + if summary_by == "func_name": + summary_results = TaskSummaries.to_summary_by_func_name(tasks=result.result) + else: + # We will need the actors info for actor tasks. + actors = await self.list_actors( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + detail=True, + ) + ) + summary_results = TaskSummaries.to_summary_by_lineage( + tasks=result.result, actors=actors.result + ) + summary = StateSummary(node_id_to_summary={"cluster": summary_results}) + warnings = result.warnings + if ( + summary_results.total_actor_scheduled + + summary_results.total_actor_tasks + + summary_results.total_tasks + < result.num_filtered + ): + warnings = warnings or [] + warnings.append( + "There is missing data in this aggregation. " + "Possibly due to task data being evicted to preserve memory." + ) + return SummaryApiResponse( + total=result.total, + result=summary, + partial_failure_warning=result.partial_failure_warning, + warnings=warnings, + num_after_truncation=result.num_after_truncation, + num_filtered=result.num_filtered, + ) + + async def summarize_actors(self, option: SummaryApiOptions) -> SummaryApiResponse: + # For summary, try getting as many entries as possible to minimze data loss. + result = await self.list_actors( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + filters=option.filters, + ) + ) + summary = StateSummary( + node_id_to_summary={ + "cluster": ActorSummaries.to_summary(actors=result.result) + } + ) + return SummaryApiResponse( + total=result.total, + result=summary, + partial_failure_warning=result.partial_failure_warning, + warnings=result.warnings, + num_after_truncation=result.num_after_truncation, + num_filtered=result.num_filtered, + ) + + async def summarize_objects(self, option: SummaryApiOptions) -> SummaryApiResponse: + # For summary, try getting as many entries as possible to minimize data loss. + result = await self.list_objects( + option=ListApiOptions( + timeout=option.timeout, + limit=RAY_MAX_LIMIT_FROM_API_SERVER, + filters=option.filters, + ) + ) + summary = StateSummary( + node_id_to_summary={ + "cluster": ObjectSummaries.to_summary(objects=result.result) + } + ) + return SummaryApiResponse( + total=result.total, + result=summary, + partial_failure_warning=result.partial_failure_warning, + warnings=result.warnings, + num_after_truncation=result.num_after_truncation, + num_filtered=result.num_filtered, + ) + + async def generate_task_timeline(self, job_id: Optional[str]) -> List[dict]: + filters = [("job_id", "=", job_id)] if job_id else None + result = await self.list_tasks( + option=ListApiOptions(detail=True, filters=filters, limit=10000) + ) + return chrome_tracing_dump(result.result) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/state_api_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/state_api_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8ffafa7badb35081e4f8a8f321c65b2f83b81aa5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/state_api_utils.py @@ -0,0 +1,252 @@ +import dataclasses +from dataclasses import asdict, fields +from typing import Awaitable, Callable, List, Tuple + +import aiohttp.web + +from ray.dashboard.optional_utils import rest_response +from ray.dashboard.utils import HTTPStatusCode +from ray.util.state.common import ( + DEFAULT_LIMIT, + DEFAULT_RPC_TIMEOUT, + RAY_MAX_LIMIT_FROM_API_SERVER, + ListApiOptions, + ListApiResponse, + PredicateType, + StateSchema, + SummaryApiOptions, + SummaryApiResponse, + SupportedFilterType, + filter_fields, +) +from ray.util.state.exception import DataSourceUnavailable +from ray.util.state.util import convert_string_to_type + + +def do_reply(success: bool, error_message: str, result: ListApiResponse, **kwargs): + return rest_response( + status_code=HTTPStatusCode.OK if success else HTTPStatusCode.INTERNAL_ERROR, + message=error_message, + result=result, + convert_google_style=False, + **kwargs, + ) + + +async def handle_list_api( + list_api_fn: Callable[[ListApiOptions], Awaitable[ListApiResponse]], + req: aiohttp.web.Request, +): + try: + result = await list_api_fn(option=options_from_req(req)) + return do_reply( + success=True, + error_message="", + result=asdict(result), + ) + except DataSourceUnavailable as e: + return do_reply(success=False, error_message=str(e), result=None) + + +def _get_filters_from_req( + req: aiohttp.web.Request, +) -> List[Tuple[str, PredicateType, SupportedFilterType]]: + filter_keys = req.query.getall("filter_keys", []) + filter_predicates = req.query.getall("filter_predicates", []) + filter_values = req.query.getall("filter_values", []) + assert len(filter_keys) == len(filter_values) + filters = [] + for key, predicate, val in zip(filter_keys, filter_predicates, filter_values): + filters.append((key, predicate, val)) + return filters + + +def options_from_req(req: aiohttp.web.Request) -> ListApiOptions: + """Obtain `ListApiOptions` from the aiohttp request.""" + limit = int( + req.query.get("limit") if req.query.get("limit") is not None else DEFAULT_LIMIT + ) + + if limit > RAY_MAX_LIMIT_FROM_API_SERVER: + raise ValueError( + f"Given limit {limit} exceeds the supported " + f"limit {RAY_MAX_LIMIT_FROM_API_SERVER}. Use a lower limit." + ) + + timeout = int(req.query.get("timeout", 30)) + filters = _get_filters_from_req(req) + detail = convert_string_to_type(req.query.get("detail", False), bool) + exclude_driver = convert_string_to_type(req.query.get("exclude_driver", True), bool) + + return ListApiOptions( + limit=limit, + timeout=timeout, + filters=filters, + detail=detail, + exclude_driver=exclude_driver, + ) + + +def summary_options_from_req(req: aiohttp.web.Request) -> SummaryApiOptions: + timeout = int(req.query.get("timeout", DEFAULT_RPC_TIMEOUT)) + filters = _get_filters_from_req(req) + summary_by = req.query.get("summary_by", None) + return SummaryApiOptions(timeout=timeout, filters=filters, summary_by=summary_by) + + +async def handle_summary_api( + summary_fn: Callable[[SummaryApiOptions], SummaryApiResponse], + req: aiohttp.web.Request, +): + result = await summary_fn(option=summary_options_from_req(req)) + return do_reply( + success=True, + error_message="", + result=asdict(result), + ) + + +def convert_filters_type( + filter: List[Tuple[str, PredicateType, SupportedFilterType]], + schema: StateSchema, +) -> List[Tuple[str, PredicateType, SupportedFilterType]]: + """Convert the given filter's type to SupportedFilterType. + + This method is necessary because click can only accept a single type + for its tuple (which is string in this case). + + Args: + filter: A list of filter which is a tuple of (key, val). + schema: The state schema. It is used to infer the type of the column for filter. + + Returns: + A new list of filters with correct types that match the schema. + """ + new_filter = [] + if dataclasses.is_dataclass(schema): + schema = {field.name: field.type for field in fields(schema)} + else: + schema = schema.schema_dict() + + for col, predicate, val in filter: + if col in schema: + column_type = schema[col] + try: + isinstance(val, column_type) + except TypeError: + # Calling `isinstance` to the Literal type raises a TypeError. + # Ignore this case. + pass + else: + if isinstance(val, column_type): + # Do nothing. + pass + elif column_type is int or column_type == "integer": + try: + val = convert_string_to_type(val, int) + except ValueError: + raise ValueError( + f"Invalid filter `--filter {col} {val}` for a int type " + "column. Please provide an integer filter " + f"`--filter {col} [int]`" + ) + elif column_type is float or column_type == "number": + try: + val = convert_string_to_type( + val, + float, + ) + except ValueError: + raise ValueError( + f"Invalid filter `--filter {col} {val}` for a float " + "type column. Please provide an integer filter " + f"`--filter {col} [float]`" + ) + elif column_type is bool or column_type == "boolean": + try: + val = convert_string_to_type(val, bool) + except ValueError: + raise ValueError( + f"Invalid filter `--filter {col} {val}` for a boolean " + "type column. Please provide " + f"`--filter {col} [True|true|1]` for True or " + f"`--filter {col} [False|false|0]` for False." + ) + new_filter.append((col, predicate, val)) + return new_filter + + +def do_filter( + data: List[dict], + filters: List[Tuple[str, PredicateType, SupportedFilterType]], + state_dataclass: StateSchema, + detail: bool, +) -> List[dict]: + """Return the filtered data given filters. + + Args: + data: A list of state data. + filters: A list of KV tuple to filter data (key, val). The data is filtered + if data[key] != val. + state_dataclass: The state schema. + + Returns: + A list of filtered state data in dictionary. Each state data's + unnecessary columns are filtered by the given state_dataclass schema. + """ + filters = convert_filters_type(filters, state_dataclass) + result = [] + for datum in data: + match = True + for filter_column, filter_predicate, filter_value in filters: + filterable_columns = state_dataclass.filterable_columns() + filter_column = filter_column.lower() + if filter_column not in filterable_columns: + raise ValueError( + f"The given filter column {filter_column} is not supported. " + "Enter filters with –-filter key=value " + "or –-filter key!=value " + f"Supported filter columns: {filterable_columns}" + ) + + if filter_column not in datum: + match = False + elif filter_predicate == "=": + if isinstance(filter_value, str) and isinstance( + datum[filter_column], str + ): + # Case insensitive match for string filter values. + match = datum[filter_column].lower() == filter_value.lower() + elif isinstance(filter_value, str) and isinstance( + datum[filter_column], bool + ): + match = datum[filter_column] == convert_string_to_type( + filter_value, bool + ) + elif isinstance(filter_value, str) and isinstance( + datum[filter_column], int + ): + match = datum[filter_column] == convert_string_to_type( + filter_value, int + ) + else: + match = datum[filter_column] == filter_value + elif filter_predicate == "!=": + if isinstance(filter_value, str) and isinstance( + datum[filter_column], str + ): + match = datum[filter_column].lower() != filter_value.lower() + else: + match = datum[filter_column] != filter_value + else: + raise ValueError( + f"Unsupported filter predicate {filter_predicate} is given. " + "Available predicates: =, !=." + ) + + if not match: + break + + if match: + result.append(filter_fields(datum, state_dataclass, detail)) + return result diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/timezone_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/timezone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..6a0d68b9c1a9989bc62682dd09b7eccaf51fc335 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/timezone_utils.py @@ -0,0 +1,56 @@ +import logging +from datetime import datetime + +logger = logging.getLogger(__name__) + +timezones = [ + {"offset": "-12:00", "value": "Etc/+12"}, + {"offset": "-11:00", "value": "Pacific/Pago_Pago"}, + {"offset": "-10:00", "value": "Pacific/Honolulu"}, + {"offset": "-09:00", "value": "America/Anchorage"}, + {"offset": "-08:00", "value": "America/Los_Angeles"}, + {"offset": "-07:00", "value": "America/Phoenix"}, + {"offset": "-06:00", "value": "America/Guatemala"}, + {"offset": "-05:00", "value": "America/Bogota"}, + {"offset": "-04:00", "value": "America/Halifax"}, + {"offset": "-03:30", "value": "America/St_Johns"}, + {"offset": "-03:00", "value": "America/Sao_Paulo"}, + {"offset": "-02:00", "value": "America/Godthab"}, + {"offset": "-01:00", "value": "Atlantic/Azores"}, + {"offset": "+00:00", "value": "Europe/London"}, + {"offset": "+01:00", "value": "Europe/Amsterdam"}, + {"offset": "+02:00", "value": "Asia/Amman"}, + {"offset": "+03:00", "value": "Asia/Baghdad"}, + {"offset": "+03:30", "value": "Asia/Tehran"}, + {"offset": "+04:00", "value": "Asia/Dubai"}, + {"offset": "+04:30", "value": "Asia/Kabul"}, + {"offset": "+05:00", "value": "Asia/Karachi"}, + {"offset": "+05:30", "value": "Asia/Kolkata"}, + {"offset": "+05:45", "value": "Asia/Kathmandu"}, + {"offset": "+06:00", "value": "Asia/Almaty"}, + {"offset": "+06:30", "value": "Asia/Yangon"}, + {"offset": "+07:00", "value": "Asia/Bangkok"}, + {"offset": "+08:00", "value": "Asia/Shanghai"}, + {"offset": "+09:00", "value": "Asia/Irkutsk"}, + {"offset": "+09:30", "value": "Australia/Adelaide"}, + {"offset": "+10:00", "value": "Australia/Brisbane"}, + {"offset": "+11:00", "value": "Asia/Magadan"}, + {"offset": "+12:00", "value": "Pacific/Auckland"}, + {"offset": "+13:00", "value": "Pacific/Tongatapu"}, +] + + +def get_current_timezone_info(): + current_tz = datetime.now().astimezone().tzinfo + offset = current_tz.utcoffset(None) + hours, remainder = divmod(offset.total_seconds(), 3600) + minutes = remainder // 60 + sign = "+" if hours >= 0 else "-" + current_offset = f"{sign}{abs(int(hours)):02d}:{abs(int(minutes)):02d}" + + current_timezone = next( + (tz for tz in timezones if tz["offset"] == current_offset), + {"offset": None, "value": None}, + ) + + return current_timezone diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b0bf438d1a496768ec9faebe89f8bbc19408478a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/dashboard/utils.py @@ -0,0 +1,761 @@ +import abc +import asyncio +import datetime +import functools +import importlib +import json +import logging +import os +import pkgutil +from abc import ABCMeta, abstractmethod +from base64 import b64decode +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from enum import IntEnum +from typing import TYPE_CHECKING, Any, Dict, List, Optional + +from ray._common.utils import binary_to_hex + +if TYPE_CHECKING: + from ray.core.generated.node_manager_pb2 import GetNodeStatsReply + +from packaging.version import Version + +import ray +import ray._private.protobuf_compat +import ray._private.ray_constants as ray_constants +import ray._private.services as services +import ray.experimental.internal_kv as internal_kv +from ray._common.utils import get_or_create_event_loop +from ray._private.gcs_utils import GcsChannel +from ray._private.utils import ( + check_dashboard_dependencies_installed, + split_address, +) +from ray._raylet import GcsClient + +try: + create_task = asyncio.create_task +except AttributeError: + create_task = asyncio.ensure_future + +logger = logging.getLogger(__name__) + + +class HTTPStatusCode(IntEnum): + # 2xx Success + OK = 200 + + # 4xx Client Errors + NOT_FOUND = 404 + + # 5xx Server Errors + INTERNAL_ERROR = 500 + + +class FrontendNotFoundError(OSError): + pass + + +class DashboardAgentModule(abc.ABC): + def __init__(self, dashboard_agent): + """ + Initialize current module when DashboardAgent loading modules. + :param dashboard_agent: The DashboardAgent instance. + """ + self._dashboard_agent = dashboard_agent + self.session_name = dashboard_agent.session_name + + @abc.abstractmethod + async def run(self, server): + """ + Run the module in an asyncio loop. An agent module can provide + servicers to the server. + :param server: Asyncio GRPC server, or None if ray is minimal. + """ + + @staticmethod + @abc.abstractclassmethod + def is_minimal_module(): + """ + Return True if the module is minimal, meaning it + should work with `pip install ray` that doesn't requires additional + dependencies. + """ + + @property + def gcs_address(self): + return self._dashboard_agent.gcs_address + + +@dataclass +class DashboardHeadModuleConfig: + minimal: bool + cluster_id_hex: str + session_name: str + gcs_address: str + log_dir: str + temp_dir: str + session_dir: str + ip: str + http_host: str + http_port: int + + +class DashboardHeadModule(abc.ABC): + def __init__(self, config: DashboardHeadModuleConfig): + """ + Initialize current module when DashboardHead loading modules. + :param config: The DashboardHeadModuleConfig instance. + """ + self._config = config + self._gcs_client = None + self._aiogrpc_gcs_channel = None # lazy init + self._http_session = None # lazy init + + @property + def minimal(self): + return self._config.minimal + + @property + def session_name(self): + return self._config.session_name + + @property + def gcs_address(self): + return self._config.gcs_address + + @property + def log_dir(self): + return self._config.log_dir + + @property + def temp_dir(self): + return self._config.temp_dir + + @property + def session_dir(self): + return self._config.session_dir + + @property + def ip(self): + return self._config.ip + + @property + def http_host(self): + return self._config.http_host + + @property + def http_port(self): + return self._config.http_port + + @property + def http_session(self): + assert not self._config.minimal, "http_session accessed in minimal Ray." + import aiohttp + + if self._http_session is not None: + return self._http_session + # Create a http session for all modules. + # aiohttp<4.0.0 uses a 'loop' variable, aiohttp>=4.0.0 doesn't anymore + if Version(aiohttp.__version__) < Version("4.0.0"): + self._http_session = aiohttp.ClientSession(loop=get_or_create_event_loop()) + else: + self._http_session = aiohttp.ClientSession() + return self._http_session + + @property + def gcs_client(self): + if self._gcs_client is None: + self._gcs_client = GcsClient( + address=self._config.gcs_address, + cluster_id=self._config.cluster_id_hex, + ) + if not internal_kv._internal_kv_initialized(): + internal_kv._initialize_internal_kv(self._gcs_client) + return self._gcs_client + + @property + def aiogrpc_gcs_channel(self): + # TODO(ryw): once we removed the old gcs client, also remove this. + if self._config.minimal: + return None + if self._aiogrpc_gcs_channel is None: + gcs_channel = GcsChannel(gcs_address=self._config.gcs_address, aio=True) + gcs_channel.connect() + self._aiogrpc_gcs_channel = gcs_channel.channel() + return self._aiogrpc_gcs_channel + + @abc.abstractmethod + async def run(self): + """ + Run the module in an asyncio loop. A head module can provide + servicers to the server. + """ + + @staticmethod + @abc.abstractclassmethod + def is_minimal_module(): + """ + Return True if the module is minimal, meaning it + should work with `pip install ray` that doesn't requires additional + dependencies. + """ + + +class RateLimitedModule(abc.ABC): + """Simple rate limiter + + Inheriting from this class and decorate any class methods will + apply simple rate limit. + It will limit the maximal number of concurrent invocations of **all** the + methods decorated. + + The below Example class will only allow 10 concurrent calls to A() and B() + + E.g.: + + class Example(RateLimitedModule): + def __init__(self): + super().__init__(max_num_call=10) + + @RateLimitedModule.enforce_max_concurrent_calls + async def A(): + ... + + @RateLimitedModule.enforce_max_concurrent_calls + async def B(): + ... + + async def limit_handler_(self): + raise RuntimeError("rate limited reached!") + + """ + + def __init__(self, max_num_call: int, logger: Optional[logging.Logger] = None): + """ + Args: + max_num_call: Maximal number of concurrent invocations of all decorated + functions in the instance. + Setting to -1 will disable rate limiting. + + logger: Logger + """ + self.max_num_call_ = max_num_call + self.num_call_ = 0 + self.logger_ = logger + + @staticmethod + def enforce_max_concurrent_calls(func): + """Decorator to enforce max number of invocations of the decorated func + + NOTE: This should be used as the innermost decorator if there are multiple + ones. + + E.g., when decorating functions already with @routes.get(...), this must be + added below then the routes decorators: + ``` + @routes.get('/') + @RateLimitedModule.enforce_max_concurrent_calls + async def fn(self): + ... + + ``` + """ + + @functools.wraps(func) + async def async_wrapper(self, *args, **kwargs): + if self.max_num_call_ >= 0 and self.num_call_ >= self.max_num_call_: + if self.logger_: + self.logger_.warning( + f"Max concurrent requests reached={self.max_num_call_}" + ) + return await self.limit_handler_() + self.num_call_ += 1 + try: + ret = await func(self, *args, **kwargs) + finally: + self.num_call_ -= 1 + return ret + + # Returning closure here to avoid passing 'self' to the + # 'enforce_max_concurrent_calls' decorator. + return async_wrapper + + @abstractmethod + async def limit_handler_(self): + """Handler that is invoked when max number of concurrent calls reached""" + + +def dashboard_module(enable): + """A decorator for dashboard module.""" + + def _cls_wrapper(cls): + cls.__ray_dashboard_module_enable__ = enable + return cls + + return _cls_wrapper + + +def get_all_modules(module_type): + """ + Get all importable modules that are subclass of a given module type. + """ + logger.info(f"Get all modules by type: {module_type.__name__}") + import ray.dashboard.modules + + should_only_load_minimal_modules = not check_dashboard_dependencies_installed() + + for module_loader, name, ispkg in pkgutil.walk_packages( + ray.dashboard.modules.__path__, ray.dashboard.modules.__name__ + "." + ): + try: + importlib.import_module(name) + except ModuleNotFoundError as e: + logger.info( + f"Module {name} cannot be loaded because " + "we cannot import all dependencies. Install this module using " + "`pip install 'ray[default]'` for the full " + f"dashboard functionality. Error: {e}" + ) + if not should_only_load_minimal_modules: + logger.info( + "Although `pip install 'ray[default]'` is downloaded, " + "module couldn't be imported`" + ) + raise e + + imported_modules = [] + # module_type.__subclasses__() should contain modules that + # we could successfully import. + for m in module_type.__subclasses__(): + if not getattr(m, "__ray_dashboard_module_enable__", True): + continue + if should_only_load_minimal_modules and not m.is_minimal_module(): + continue + imported_modules.append(m) + logger.info(f"Available modules: {imported_modules}") + return imported_modules + + +def to_posix_time(dt): + return (dt - datetime.datetime(1970, 1, 1)).total_seconds() + + +def address_tuple(address): + if isinstance(address, tuple): + return address + ip, port = address.split(":") + return ip, int(port) + + +def node_stats_to_dict( + message: "GetNodeStatsReply", +) -> Optional[Dict[str, List[Dict[str, Any]]]]: + decode_keys = { + "actorId", + "jobId", + "taskId", + "parentTaskId", + "sourceActorId", + "callerId", + "rayletId", + "workerId", + "placementGroupId", + } + core_workers_stats = message.core_workers_stats + result = message_to_dict(message, decode_keys) + result["coreWorkersStats"] = [ + message_to_dict(m, decode_keys, always_print_fields_with_no_presence=True) + for m in core_workers_stats + ] + return result + + +class CustomEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, bytes): + return binary_to_hex(obj) + if isinstance(obj, Immutable): + return obj.mutable() + # Let the base class default method raise the TypeError + return json.JSONEncoder.default(self, obj) + + +def to_camel_case(snake_str): + """Convert a snake str to camel case.""" + components = snake_str.split("_") + # We capitalize the first letter of each component except the first one + # with the 'title' method and join them together. + return components[0] + "".join(x.title() for x in components[1:]) + + +def to_google_style(d): + """Recursive convert all keys in dict to google style.""" + new_dict = {} + + for k, v in d.items(): + if isinstance(v, dict): + new_dict[to_camel_case(k)] = to_google_style(v) + elif isinstance(v, list): + new_list = [] + for i in v: + if isinstance(i, dict): + new_list.append(to_google_style(i)) + else: + new_list.append(i) + new_dict[to_camel_case(k)] = new_list + else: + new_dict[to_camel_case(k)] = v + return new_dict + + +def message_to_dict(message, decode_keys=None, **kwargs): + """Convert protobuf message to Python dict.""" + + def _decode_keys(d): + for k, v in d.items(): + if isinstance(v, dict): + d[k] = _decode_keys(v) + if isinstance(v, list): + new_list = [] + for i in v: + if isinstance(i, dict): + new_list.append(_decode_keys(i)) + else: + new_list.append(i) + d[k] = new_list + else: + if k in decode_keys: + d[k] = binary_to_hex(b64decode(v)) + else: + d[k] = v + return d + + d = ray._private.protobuf_compat.message_to_dict( + message, use_integers_for_enums=False, **kwargs + ) + if decode_keys: + return _decode_keys(d) + else: + return d + + +class Bunch(dict): + """A dict with attribute-access.""" + + def __getattr__(self, key): + try: + return self.__getitem__(key) + except KeyError: + raise AttributeError(key) + + def __setattr__(self, key, value): + self.__setitem__(key, value) + + +""" +https://docs.python.org/3/library/json.html?highlight=json#json.JSONEncoder + +-------------------+---------------+ + | Python | JSON | + +===================+===============+ + | dict | object | + +-------------------+---------------+ + | list, tuple | array | + +-------------------+---------------+ + | str | string | + +-------------------+---------------+ + | int, float | number | + +-------------------+---------------+ + | True | true | + +-------------------+---------------+ + | False | false | + +-------------------+---------------+ + | None | null | + +-------------------+---------------+ +""" +_json_compatible_types = {dict, list, tuple, str, int, float, bool, type(None), bytes} + + +def is_immutable(self): + raise TypeError("%r objects are immutable" % self.__class__.__name__) + + +def make_immutable(value, strict=True): + value_type = type(value) + if value_type is dict: + return ImmutableDict(value) + if value_type is list: + return ImmutableList(value) + if strict: + if value_type not in _json_compatible_types: + raise TypeError("Type {} can't be immutable.".format(value_type)) + return value + + +class Immutable(metaclass=ABCMeta): + @abstractmethod + def mutable(self): + pass + + +class ImmutableList(Immutable, Sequence): + """Makes a :class:`list` immutable.""" + + __slots__ = ("_list", "_proxy") + + def __init__(self, list_value): + if type(list_value) not in (list, ImmutableList): + raise TypeError(f"{type(list_value)} object is not a list.") + if isinstance(list_value, ImmutableList): + list_value = list_value.mutable() + self._list = list_value + self._proxy = [None] * len(list_value) + + def __reduce_ex__(self, protocol): + return type(self), (self._list,) + + def mutable(self): + return self._list + + def __eq__(self, other): + if isinstance(other, ImmutableList): + other = other.mutable() + return list.__eq__(self._list, other) + + def __ne__(self, other): + if isinstance(other, ImmutableList): + other = other.mutable() + return list.__ne__(self._list, other) + + def __contains__(self, item): + if isinstance(item, Immutable): + item = item.mutable() + return list.__contains__(self._list, item) + + def __getitem__(self, item): + proxy = self._proxy[item] + if proxy is None: + proxy = self._proxy[item] = make_immutable(self._list[item]) + return proxy + + def __len__(self): + return len(self._list) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, list.__repr__(self._list)) + + +class ImmutableDict(Immutable, Mapping): + """Makes a :class:`dict` immutable.""" + + __slots__ = ("_dict", "_proxy") + + def __init__(self, dict_value): + if type(dict_value) not in (dict, ImmutableDict): + raise TypeError(f"{type(dict_value)} object is not a dict.") + if isinstance(dict_value, ImmutableDict): + dict_value = dict_value.mutable() + self._dict = dict_value + self._proxy = {} + + def __reduce_ex__(self, protocol): + return type(self), (self._dict,) + + def mutable(self): + return self._dict + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return make_immutable(default) + + def __eq__(self, other): + if isinstance(other, ImmutableDict): + other = other.mutable() + return dict.__eq__(self._dict, other) + + def __ne__(self, other): + if isinstance(other, ImmutableDict): + other = other.mutable() + return dict.__ne__(self._dict, other) + + def __contains__(self, item): + if isinstance(item, Immutable): + item = item.mutable() + return dict.__contains__(self._dict, item) + + def __getitem__(self, item): + proxy = self._proxy.get(item, None) + if proxy is None: + proxy = self._proxy[item] = make_immutable(self._dict[item]) + return proxy + + def __len__(self) -> int: + return len(self._dict) + + def __iter__(self): + if len(self._proxy) != len(self._dict): + for key in self._dict.keys() - self._proxy.keys(): + self._proxy[key] = make_immutable(self._dict[key]) + return iter(self._proxy) + + def __repr__(self): + return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self._dict)) + + +# Register immutable types. +for immutable_type in Immutable.__subclasses__(): + _json_compatible_types.add(immutable_type) + + +def async_loop_forever(interval_seconds, cancellable=False): + def _wrapper(coro): + @functools.wraps(coro) + async def _looper(*args, **kwargs): + while True: + try: + await coro(*args, **kwargs) + except asyncio.CancelledError as ex: + if cancellable: + logger.info( + f"An async loop forever coroutine " f"is cancelled {coro}." + ) + raise ex + else: + logger.exception( + f"Can not cancel the async loop " + f"forever coroutine {coro}." + ) + except Exception: + logger.exception(f"Error looping coroutine {coro}.") + await asyncio.sleep(interval_seconds) + + return _looper + + return _wrapper + + +def ray_client_address_to_api_server_url(address: str): + """Convert a Ray Client address of a running Ray cluster to its API server URL. + + Args: + address: The Ray Client address, e.g. "ray://my-cluster". + + Returns: + str: The API server URL of the cluster, e.g. "http://:8265". + """ + with ray.init(address=address) as client_context: + dashboard_url = client_context.dashboard_url + + return f"http://{dashboard_url}" + + +def ray_address_to_api_server_url(address: Optional[str]) -> str: + """Parse a Ray cluster address into API server URL. + + When an address is provided, it will be used to query GCS for + API server address from GCS, so a Ray cluster must be running. + + When an address is not provided, it will first try to auto-detect + a running Ray instance, or look for local GCS process. + + Args: + address: Ray cluster bootstrap address or Ray Client address. + Could also be `auto`. + + Returns: + API server HTTP URL. + """ + + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = GcsClient(address=address) + + ray.experimental.internal_kv._initialize_internal_kv(gcs_client) + api_server_url = ray._private.utils.internal_kv_get_with_retry( + gcs_client, + ray_constants.DASHBOARD_ADDRESS, + namespace=ray_constants.KV_NAMESPACE_DASHBOARD, + num_retries=20, + ) + + if api_server_url is None: + raise ValueError( + ( + "Couldn't obtain the API server address from GCS. It is likely that " + "the GCS server is down. Check gcs_server.[out | err] to see if it is " + "still alive." + ) + ) + api_server_url = f"http://{api_server_url.decode()}" + return api_server_url + + +def get_address_for_submission_client(address: Optional[str]) -> str: + """Get Ray API server address from Ray bootstrap or Client address. + + If None, it will try to auto-detect a running Ray instance, or look + for local GCS process. + + `address` is always overridden by the RAY_ADDRESS environment + variable, just like the `address` argument in `ray.init()`. + + Args: + address: Ray cluster bootstrap address or Ray Client address. + Could also be "auto". + + Returns: + API server HTTP URL, e.g. "http://:8265". + """ + if os.environ.get("RAY_ADDRESS"): + logger.debug(f"Using RAY_ADDRESS={os.environ['RAY_ADDRESS']}") + address = os.environ["RAY_ADDRESS"] + + if address and "://" in address: + module_string, _ = split_address(address) + if module_string == "ray": + logger.debug( + f"Retrieving API server address from Ray Client address {address}..." + ) + address = ray_client_address_to_api_server_url(address) + else: + # User specified a non-Ray-Client Ray cluster address. + address = ray_address_to_api_server_url(address) + logger.debug(f"Using API server address {address}.") + return address + + +def compose_state_message( + death_reason: Optional[str], death_reason_message: Optional[str] +) -> Optional[str]: + """Compose node state message based on death information. + + Args: + death_reason: The reason of node death. + This is a string representation of `gcs_pb2.NodeDeathInfo.Reason`. + death_reason_message: The message of node death. + This corresponds to `gcs_pb2.NodeDeathInfo.ReasonMessage`. + """ + if death_reason == "EXPECTED_TERMINATION": + state_message = "Expected termination" + elif death_reason == "UNEXPECTED_TERMINATION": + state_message = "Unexpected termination" + elif death_reason == "AUTOSCALER_DRAIN_PREEMPTED": + state_message = "Terminated due to preemption" + elif death_reason == "AUTOSCALER_DRAIN_IDLE": + state_message = "Terminated due to idle (no Ray activity)" + else: + state_message = None + + if death_reason_message: + if state_message: + state_message += f": {death_reason_message}" + else: + state_message = death_reason_message + return state_message + + +def close_logger_file_descriptor(logger_instance): + for handler in logger_instance.handlers: + handler.close() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4e6be48cb725fb6ff6068a0a3402f55fad290ecf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__init__.py @@ -0,0 +1,174 @@ +# Short term workaround for https://github.com/ray-project/ray/issues/32435 +# Dataset has a hard dependency on pandas, so it doesn't need to be delayed. +import pandas # noqa +from packaging.version import parse as parse_version + +from ray._private.arrow_utils import get_pyarrow_version + +from ray.data._internal.compute import ActorPoolStrategy +from ray.data._internal.datasource.tfrecords_datasource import TFXReadOptions +from ray.data._internal.execution.interfaces import ( + ExecutionOptions, + ExecutionResources, + NodeIdStr, +) +from ray.data._internal.logging import configure_logging +from ray.data.context import DataContext, DatasetContext +from ray.data.dataset import Dataset, Schema, SinkMode, ClickHouseTableSettings +from ray.data.datasource import ( + BlockBasedFileDatasink, + Datasink, + Datasource, + FileShuffleConfig, + ReadTask, + RowBasedFileDatasink, +) +from ray.data.iterator import DataIterator, DatasetIterator +from ray.data.preprocessor import Preprocessor +from ray.data.read_api import ( # noqa: F401 + from_arrow, + from_arrow_refs, + from_blocks, + from_daft, + from_dask, + from_huggingface, + from_items, + from_mars, + from_modin, + from_numpy, + from_numpy_refs, + from_pandas, + from_pandas_refs, + from_spark, + from_tf, + from_torch, + range, + range_tensor, + read_audio, + read_avro, + read_bigquery, + read_binary_files, + read_clickhouse, + read_csv, + read_databricks_tables, + read_datasource, + read_delta, + read_delta_sharing_tables, + read_hudi, + read_iceberg, + read_images, + read_json, + read_lance, + read_mongo, + read_numpy, + read_parquet, + read_parquet_bulk, + read_sql, + read_text, + read_tfrecords, + read_unity_catalog, + read_videos, + read_webdataset, +) + +# Module-level cached global functions for callable classes. It needs to be defined here +# since it has to be process-global across cloudpickled funcs. +_map_actor_context = None + +configure_logging() + +try: + import pyarrow as pa + + # https://github.com/apache/arrow/pull/38608 deprecated `PyExtensionType`, and + # disabled it's deserialization by default. To ensure that users can load data + # written with earlier version of Ray Data, we enable auto-loading of serialized + # tensor extensions. + pyarrow_version = get_pyarrow_version() + if pyarrow_version is None: + # PyArrow is mocked in documentation builds. In this case, we don't need to do + # anything. + pass + else: + from ray._private.ray_constants import env_bool + + RAY_DATA_AUTOLOAD_PYEXTENSIONTYPE = env_bool( + "RAY_DATA_AUTOLOAD_PYEXTENSIONTYPE", False + ) + + if ( + pyarrow_version >= parse_version("14.0.1") + and RAY_DATA_AUTOLOAD_PYEXTENSIONTYPE + ): + pa.PyExtensionType.set_auto_load(True) + # Import these arrow extension types to ensure that they are registered. + from ray.air.util.tensor_extensions.arrow import ( # noqa + ArrowTensorType, + ArrowVariableShapedTensorType, + ) +except ModuleNotFoundError: + pass + + +__all__ = [ + "ActorPoolStrategy", + "BlockBasedFileDatasink", + "ClickHouseTableSettings", + "Dataset", + "DataContext", + "DatasetContext", # Backwards compatibility alias. + "DataIterator", + "DatasetIterator", # Backwards compatibility alias. + "Datasink", + "Datasource", + "ExecutionOptions", + "ExecutionResources", + "FileShuffleConfig", + "NodeIdStr", + "ReadTask", + "RowBasedFileDatasink", + "Schema", + "SinkMode", + "from_daft", + "from_dask", + "from_items", + "from_arrow", + "from_arrow_refs", + "from_mars", + "from_modin", + "from_numpy", + "from_numpy_refs", + "from_pandas", + "from_pandas_refs", + "from_spark", + "from_tf", + "from_torch", + "from_huggingface", + "range", + "range_tensor", + "read_audio", + "read_avro", + "read_text", + "read_binary_files", + "read_clickhouse", + "read_csv", + "read_datasource", + "read_delta", + "read_delta_sharing_tables", + "read_hudi", + "read_iceberg", + "read_images", + "read_json", + "read_lance", + "read_numpy", + "read_mongo", + "read_parquet", + "read_parquet_bulk", + "read_sql", + "read_tfrecords", + "read_unity_catalog", + "read_videos", + "read_webdataset", + "Preprocessor", + "TFXReadOptions", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7af875200f9d2b93ab1bf172957c3a40a856b567 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/dataset.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0394a0d8bdbce5ff7a7b7d817bcd036f4477de4349d2605cf68808b96ce87b96 +size 268137 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..32801751621dd12c0360aabda5970c4bb1e4a1a0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/__pycache__/read_api.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0a96569e7907a1cb5005a2c01daed843353f8fa3f8f3aae4ec2d85feec9b66a +size 166347 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/aggregate.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/aggregate.py new file mode 100644 index 0000000000000000000000000000000000000000..e67dc441613ca8cbbf5089a0b34520321d7b8dc9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/aggregate.py @@ -0,0 +1,1003 @@ +import abc +import math +from typing import TYPE_CHECKING, Any, Callable, List, Optional + +import numpy as np + +from ray.data._internal.util import is_null +from ray.data.block import AggType, Block, BlockAccessor, KeyType, T, U +from ray.util.annotations import Deprecated, PublicAPI + +if TYPE_CHECKING: + from ray.data import Schema + + +@Deprecated(message="AggregateFn is deprecated, please use AggregateFnV2") +@PublicAPI +class AggregateFn: + """NOTE: THIS IS DEPRECATED, PLEASE USE :class:`AggregateFnV2` INSTEAD + + Defines how to perform a custom aggregation in Ray Data. + + `AggregateFn` instances are passed to a Dataset's ``.aggregate(...)`` method to + specify the steps required to transform and combine rows sharing the same key. + This enables implementing custom aggregators beyond the standard + built-in options like Sum, Min, Max, Mean, etc. + + Args: + init: Function that creates an initial aggregator for each group. Receives a key + (the group key) and returns the initial accumulator state (commonly 0, + an empty list, or an empty dictionary). + merge: Function that merges two accumulators generated by different workers + into one accumulator. + name: An optional display name for the aggregator. Useful for debugging. + accumulate_row: Function that processes an individual row. It receives the current + accumulator and a row, then returns an updated accumulator. Cannot be + used if `accumulate_block` is provided. + accumulate_block: Function that processes an entire block of rows at once. It receives the + current accumulator and a block of rows, then returns an updated accumulator. + This allows for vectorized operations. Cannot be used if `accumulate_row` + is provided. + finalize: Function that finishes the aggregation by transforming the final + accumulator state into the desired output. For example, if your + accumulator is a list of items, you may want to compute a statistic + from the list. If not provided, the final accumulator state is returned + as-is. + + Example: + .. testcode:: + + import ray + from ray.data.aggregate import AggregateFn + + # A simple aggregator that counts how many rows there are per group + count_agg = AggregateFn( + init=lambda k: 0, + accumulate_row=lambda counter, row: counter + 1, + merge=lambda c1, c2: c1 + c2, + name="custom_count" + ) + ds = ray.data.from_items([{"group": "A"}, {"group": "B"}, {"group": "A"}]) + result = ds.groupby("group").aggregate(count_agg).take_all() + # result: [{'group': 'A', 'custom_count': 2}, {'group': 'B', 'custom_count': 1}] + """ + + def __init__( + self, + init: Callable[[KeyType], AggType], + merge: Callable[[AggType, AggType], AggType], + name: str, + accumulate_row: Callable[[AggType, T], AggType] = None, + accumulate_block: Callable[[AggType, Block], AggType] = None, + finalize: Optional[Callable[[AggType], U]] = None, + ): + if (accumulate_row is None and accumulate_block is None) or ( + accumulate_row is not None and accumulate_block is not None + ): + raise ValueError( + "Exactly one of accumulate_row or accumulate_block must be provided." + ) + + if accumulate_block is None: + + def accumulate_block(a: AggType, block: Block) -> AggType: + block_acc = BlockAccessor.for_block(block) + for r in block_acc.iter_rows(public_row_format=False): + a = accumulate_row(a, r) + return a + + if not isinstance(name, str): + raise TypeError("`name` must be provided.") + + if finalize is None: + finalize = lambda a: a # noqa: E731 + + self.name = name + self.init = init + self.merge = merge + self.accumulate_block = accumulate_block + self.finalize = finalize + + def _validate(self, schema: Optional["Schema"]) -> None: + """Raise an error if this cannot be applied to the given schema.""" + pass + + +@PublicAPI(stability="alpha") +class AggregateFnV2(AggregateFn, abc.ABC): + """Provides an interface to implement efficient aggregations to be applied + to the dataset. + + `AggregateFnV2` instances are passed to a Dataset's ``.aggregate(...)`` method to + perform distributed aggregations. To create a custom aggregation, you should subclass + `AggregateFnV2` and implement the `aggregate_block` and `combine` methods. + The `finalize` method can also be overridden if the final accumulated state + needs further transformation. + + Aggregation follows these steps: + + 1. **Initialization**: For each group (if grouping) or for the entire dataset, + an initial accumulator is created using `zero_factory`. + 2. **Block Aggregation**: The `aggregate_block` method is applied to + each block independently, producing a partial aggregation result for that block. + 3. **Combination**: The `combine` method is used to merge these partial + results (or an existing accumulated result with a new partial result) + into a single, combined accumulator. + 4. **Finalization**: Optionally, the `finalize` method transforms the + final combined accumulator into the desired output format. + + Args: + name: The name of the aggregation. This will be used as the column name + in the output, e.g., "sum(my_col)". + zero_factory: A callable that returns the initial "zero" value for the + accumulator. For example, for a sum, this would be `lambda: 0`; for + finding a minimum, `lambda: float("inf")`, for finding a maximum, + `lambda: float("-inf")`. + on: The name of the column to perform the aggregation on. If `None`, + the aggregation is performed over the entire row (e.g., for `Count()`). + ignore_nulls: Whether to ignore null values during aggregation. + If `True`, nulls are skipped. + If `False`, the presence of a null value might result in a null output, + depending on the aggregation logic. + """ + + def __init__( + self, + name: str, + zero_factory: Callable[[], AggType], + *, + on: Optional[str], + ignore_nulls: bool, + ): + if not name: + raise ValueError( + f"Non-empty string has to be provided as name (got {name})" + ) + + self._target_col_name = on + self._ignore_nulls = ignore_nulls + + _safe_combine = _null_safe_combine(self.combine, ignore_nulls) + _safe_aggregate = _null_safe_aggregate(self.aggregate_block, ignore_nulls) + _safe_finalize = _null_safe_finalize(self.finalize) + + _safe_zero_factory = _null_safe_zero_factory(zero_factory, ignore_nulls) + + super().__init__( + name=name, + init=_safe_zero_factory, + merge=_safe_combine, + accumulate_block=lambda _, block: _safe_aggregate(block), + finalize=_safe_finalize, + ) + + def get_target_column(self) -> Optional[str]: + return self._target_col_name + + @abc.abstractmethod + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + """Combines a new partial aggregation result with the current accumulator. + + This method defines how two intermediate aggregation states are merged. + For example, if `aggregate_block` produces partial sums `s1` and `s2` from + two different blocks, `combine(s1, s2)` should return `s1 + s2`. + + Args: + current_accumulator: The current accumulated state (e.g., the result of + previous `combine` calls or an initial value from `zero_factory`). + new: A new partially aggregated value, typically the output of + `aggregate_block` from a new block of data, or another accumulator + from a parallel task. + + Returns: + The updated accumulator after combining it with the new value. + """ + ... + + @abc.abstractmethod + def aggregate_block(self, block: Block) -> AggType: + """Aggregates data within a single block. + + This method processes all rows in a given `Block` and returns a partial + aggregation result for that block. For instance, if implementing a sum, + this method would sum all relevant values within the block. + + Args: + block: A `Block` of data to be aggregated. + + Returns: + A partial aggregation result for the input block. The type of this + result (`AggType`) should be consistent with the `current_accumulator` + and `new` arguments of the `combine` method, and the `accumulator` + argument of the `finalize` method. + """ + ... + + def finalize(self, accumulator: AggType) -> Optional[U]: + """Transforms the final accumulated state into the desired output. + + This method is called once per group after all blocks have been processed + and all partial results have been combined. It provides an opportunity + to perform a final transformation on the accumulated data. + + For many aggregations (e.g., Sum, Count, Min, Max), the accumulated state + is already the final result, so this method can simply return the + accumulator as is (which is the default behavior). + + For other aggregations, like Mean, this method is crucial. + A Mean aggregation might accumulate `[sum, count]`. The `finalize` + method would then compute `sum / count` to get the final mean. + + Args: + accumulator: The final accumulated state for a group, after all + `aggregate_block` and `combine` operations. + + Returns: + The final result of the aggregation for the group. + """ + return accumulator + + def _validate(self, schema: Optional["Schema"]) -> None: + if self._target_col_name: + from ray.data._internal.planner.exchange.sort_task_spec import SortKey + + SortKey(self._target_col_name).validate_schema(schema) + + +@PublicAPI +class Count(AggregateFnV2): + """Defines count aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Count + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Counting all rows: + result = ds.aggregate(Count()) + # result: {'count()': 100} + + + # Counting all rows per group: + result = ds.groupby("group_key").aggregate(Count(on="id")).take_all() + # result: [{'group_key': 0, 'count(id)': 34}, + # {'group_key': 1, 'count(id)': 33}, + # {'group_key': 2, 'count(id)': 33}] + + + Args: + on: Optional name of the column to count values on. If None, counts rows. + ignore_nulls: Whether to ignore null values when counting. Only applies if + `on` is specified. Default is `False` which means `Count()` on a column + will count nulls by default. To match pandas default behavior of not counting nulls, + set `ignore_nulls=True`. + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ignore_nulls: bool = False, + alias_name: Optional[str] = None, + ): + super().__init__( + alias_name if alias_name else f"count({on or ''})", + on=on, + ignore_nulls=ignore_nulls, + zero_factory=lambda: 0, + ) + + def aggregate_block(self, block: Block) -> AggType: + block_accessor = BlockAccessor.for_block(block) + + if self._target_col_name is None: + # In case of global count, simply fetch number of rows + return block_accessor.num_rows() + + return block_accessor.count( + self._target_col_name, ignore_nulls=self._ignore_nulls + ) + + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + return current_accumulator + new + + +@PublicAPI +class Sum(AggregateFnV2): + """Defines sum aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Sum + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Summing all rows per group: + result = ds.aggregate(Sum(on="id")) + # result: {'sum(id)': 4950} + + Args: + on: The name of the numerical column to sum. Must be provided. + ignore_nulls: Whether to ignore null values during summation. If `True` (default), + nulls are skipped. If `False`, the sum will be null if any + value in the group is null. + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + super().__init__( + alias_name if alias_name else f"sum({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + zero_factory=lambda: 0, + ) + + def aggregate_block(self, block: Block) -> AggType: + return BlockAccessor.for_block(block).sum( + self._target_col_name, self._ignore_nulls + ) + + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + return current_accumulator + new + + +@PublicAPI +class Min(AggregateFnV2): + """Defines min aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Min + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Finding the minimum value per group: + result = ds.groupby("group_key").aggregate(Min(on="id")).take_all() + # result: [{'group_key': 0, 'min(id)': 0}, + # {'group_key': 1, 'min(id)': 1}, + # {'group_key': 2, 'min(id)': 2}] + + Args: + on: The name of the column to find the minimum value from. Must be provided. + ignore_nulls: Whether to ignore null values. If `True` (default), nulls are + skipped. If `False`, the minimum will be null if any value in + the group is null (for most data types, or follow type-specific + comparison rules with nulls). + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + super().__init__( + alias_name if alias_name else f"min({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + zero_factory=lambda: float("+inf"), + ) + + def aggregate_block(self, block: Block) -> AggType: + return BlockAccessor.for_block(block).min( + self._target_col_name, self._ignore_nulls + ) + + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + return min(current_accumulator, new) + + +@PublicAPI +class Max(AggregateFnV2): + """Defines max aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Max + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Finding the maximum value per group: + result = ds.groupby("group_key").aggregate(Max(on="id")).take_all() + # result: [{'group_key': 0, 'max(id)': ...}, + # {'group_key': 1, 'max(id)': ...}, + # {'group_key': 2, 'max(id)': ...}] + + Args: + on: The name of the column to find the maximum value from. Must be provided. + ignore_nulls: Whether to ignore null values. If `True` (default), nulls are + skipped. If `False`, the maximum will be null if any value in + the group is null (for most data types, or follow type-specific + comparison rules with nulls). + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + + super().__init__( + alias_name if alias_name else f"max({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + zero_factory=lambda: float("-inf"), + ) + + def aggregate_block(self, block: Block) -> AggType: + return BlockAccessor.for_block(block).max( + self._target_col_name, self._ignore_nulls + ) + + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + return max(current_accumulator, new) + + +@PublicAPI +class Mean(AggregateFnV2): + """Defines mean (average) aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Mean + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Calculating the mean value per group: + result = ds.groupby("group_key").aggregate(Mean(on="id")).take_all() + # result: [{'group_key': 0, 'mean(id)': ...}, + # {'group_key': 1, 'mean(id)': ...}, + # {'group_key': 2, 'mean(id)': ...}] + + Args: + on: The name of the numerical column to calculate the mean on. Must be provided. + ignore_nulls: Whether to ignore null values. If `True` (default), nulls are + skipped. If `False`, the mean will be null if any value in the + group is null. + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + super().__init__( + alias_name if alias_name else f"mean({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + # The accumulator is: [current_sum, current_count]. + # NOTE: We copy the returned list `list([0,0])` as some internal mechanisms + # might modify accumulators in-place. + zero_factory=lambda: list([0, 0]), # noqa: C410 + ) + + def aggregate_block(self, block: Block) -> AggType: + block_acc = BlockAccessor.for_block(block) + count = block_acc.count(self._target_col_name, self._ignore_nulls) + + if count == 0 or count is None: + # Empty or all null. + return None + + sum_ = block_acc.sum(self._target_col_name, self._ignore_nulls) + + if is_null(sum_): + # In case of ignore_nulls=False and column containing 'null' + # return as is (to prevent unnecessary type conversions, when, for ex, + # using Pandas and returning None) + return sum_ + + return [sum_, count] + + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + return [current_accumulator[0] + new[0], current_accumulator[1] + new[1]] + + def finalize(self, accumulator: AggType) -> Optional[U]: + # The final accumulator for a group is [total_sum, total_count]. + if accumulator[1] == 0: + # If total_count is 0 (e.g., group was empty or all nulls ignored), + # the mean is undefined. Return NaN + return np.nan + + return accumulator[0] / accumulator[1] + + +@PublicAPI +class Std(AggregateFnV2): + """Defines standard deviation aggregation. + + Uses Welford's online algorithm for numerical stability. This method computes + the standard deviation in a single pass. Results may differ slightly from + libraries like NumPy or Pandas that use a two-pass algorithm but are generally + more accurate. + + See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Std + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Calculating the standard deviation per group: + result = ds.groupby("group_key").aggregate(Std(on="id")).take_all() + # result: [{'group_key': 0, 'std(id)': ...}, + # {'group_key': 1, 'std(id)': ...}, + # {'group_key': 2, 'std(id)': ...}] + + Args: + on: The name of the column to calculate standard deviation on. + ddof: Delta Degrees of Freedom. The divisor used in calculations is `N - ddof`, + where `N` is the number of elements. Default is 1. + ignore_nulls: Whether to ignore null values. Default is True. + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ddof: int = 1, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + super().__init__( + alias_name if alias_name else f"std({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + # Accumulator: [M2, mean, count] + # M2: sum of squares of differences from the current mean + # mean: current mean + # count: current count of non-null elements + # We need to copy the list as it might be modified in-place by some aggregations. + zero_factory=lambda: list([0, 0, 0]), # noqa: C410 + ) + + self._ddof = ddof + + def aggregate_block(self, block: Block) -> AggType: + block_acc = BlockAccessor.for_block(block) + count = block_acc.count(self._target_col_name, ignore_nulls=self._ignore_nulls) + if count == 0 or count is None: + # Empty or all null. + return None + sum_ = block_acc.sum(self._target_col_name, self._ignore_nulls) + if is_null(sum_): + # If sum is null (e.g., ignore_nulls=False and a null was encountered), + # return as is to prevent type conversions. + return sum_ + mean = sum_ / count + M2 = block_acc.sum_of_squared_diffs_from_mean( + self._target_col_name, self._ignore_nulls, mean + ) + return [M2, mean, count] + + def combine(self, current_accumulator: List[float], new: List[float]) -> AggType: + # Merges two accumulators [M2, mean, count] using a parallel algorithm. + # See: https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Parallel_algorithm + M2_a, mean_a, count_a = current_accumulator + M2_b, mean_b, count_b = new + delta = mean_b - mean_a + count = count_a + count_b + # NOTE: We use this mean calculation since it's more numerically + # stable than mean_a + delta * count_b / count, which actually + # deviates from Pandas in the ~15th decimal place and causes our + # exact comparison tests to fail. + mean = (mean_a * count_a + mean_b * count_b) / count + # Update the sum of squared differences. + M2 = M2_a + M2_b + (delta**2) * count_a * count_b / count + return [M2, mean, count] + + def finalize(self, accumulator: List[float]) -> Optional[U]: + # Compute the final standard deviation from the accumulated + # sum of squared differences from current mean and the count. + # Final accumulator: [M2, mean, count] + M2, mean, count = accumulator + # Denominator for variance calculation is count - ddof + if count - self._ddof <= 0: + # If count - ddof is not positive, variance/std is undefined (or zero). + # Return NaN, consistent with pandas/numpy. + return np.nan + # Standard deviation is the square root of variance (M2 / (count - ddof)) + return math.sqrt(M2 / (count - self._ddof)) + + +@PublicAPI +class AbsMax(AggregateFnV2): + """Defines absolute max aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import AbsMax + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Calculating the absolute maximum value per group: + result = ds.groupby("group_key").aggregate(AbsMax(on="id")).take_all() + # result: [{'group_key': 0, 'abs_max(id)': ...}, + # {'group_key': 1, 'abs_max(id)': ...}, + # {'group_key': 2, 'abs_max(id)': ...}] + + Args: + on: The name of the column to calculate absolute maximum on. Must be provided. + ignore_nulls: Whether to ignore null values. Default is True. + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + if on is None or not isinstance(on, str): + raise ValueError(f"Column to aggregate on has to be provided (got {on})") + + super().__init__( + alias_name if alias_name else f"abs_max({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + zero_factory=lambda: 0, + ) + + def aggregate_block(self, block: Block) -> AggType: + block_accessor = BlockAccessor.for_block(block) + + max_ = block_accessor.max(self._target_col_name, self._ignore_nulls) + min_ = block_accessor.min(self._target_col_name, self._ignore_nulls) + + if is_null(max_) or is_null(min_): + return None + + return max( + abs(max_), + abs(min_), + ) + + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + return max(current_accumulator, new) + + +@PublicAPI +class Quantile(AggregateFnV2): + """Defines Quantile aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Quantile + + ds = ray.data.range(100) + # Schema: {'id': int64} + ds = ds.add_column("group_key", lambda x: x % 3) + # Schema: {'id': int64, 'group_key': int64} + + # Calculating the 50th percentile (median) per group: + result = ds.groupby("group_key").aggregate(Quantile(q=0.5, on="id")).take_all() + # result: [{'group_key': 0, 'quantile(id)': ...}, + # {'group_key': 1, 'quantile(id)': ...}, + # {'group_key': 2, 'quantile(id)': ...}] + + Args: + on: The name of the column to calculate the quantile on. Must be provided. + q: The quantile to compute, which must be between 0 and 1 inclusive. + For example, q=0.5 computes the median. + ignore_nulls: Whether to ignore null values. Default is True. + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + q: float = 0.5, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + self._q = q + + super().__init__( + alias_name if alias_name else f"quantile({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + zero_factory=list, + ) + + def combine(self, current_accumulator: List[Any], new: List[Any]) -> List[Any]: + if isinstance(current_accumulator, List) and isinstance(new, List): + current_accumulator.extend(new) + return current_accumulator + + if isinstance(current_accumulator, List) and (not isinstance(new, List)): + if new is not None and new != "": + current_accumulator.append(new) + return current_accumulator + + if isinstance(new, List) and (not isinstance(current_accumulator, List)): + if current_accumulator is not None and current_accumulator != "": + new.append(current_accumulator) + return new + + ls = [] + + if current_accumulator is not None and current_accumulator != "": + ls.append(current_accumulator) + + if new is not None and new != "": + ls.append(new) + + return ls + + def aggregate_block(self, block: Block) -> AggType: + block_acc = BlockAccessor.for_block(block) + ls = [] + + for row in block_acc.iter_rows(public_row_format=False): + ls.append(row.get(self._target_col_name)) + + return ls + + def finalize(self, accumulator: List[Any]) -> Optional[U]: + if self._ignore_nulls: + accumulator = [v for v in accumulator if not is_null(v)] + else: + nulls = [v for v in accumulator if is_null(v)] + if len(nulls) > 0: + # If nulls are present and not ignored, the quantile is undefined. + # Return the first null encountered to preserve column type. + return nulls[0] + + if not accumulator: + # If the list is empty (e.g., all values were null and ignored, or no values), + # quantile is undefined. + return None + + key = lambda x: x # noqa: E731 + input_values = sorted(accumulator) + k = (len(input_values) - 1) * self._q + f = math.floor(k) + c = math.ceil(k) + + if f == c: + return key(input_values[int(k)]) + + # Interpolate between the elements at floor and ceil indices. + d0 = key(input_values[int(f)]) * (c - k) + d1 = key(input_values[int(c)]) * (k - f) + + return round(d0 + d1, 5) + + +@PublicAPI +class Unique(AggregateFnV2): + """Defines unique aggregation. + + Example: + + .. testcode:: + + import ray + from ray.data.aggregate import Unique + + ds = ray.data.range(100) + ds = ds.add_column("group_key", lambda x: x % 3) + + # Calculating the unique values per group: + result = ds.groupby("group_key").aggregate(Unique(on="id")).take_all() + # result: [{'group_key': 0, 'unique(id)': ...}, + # {'group_key': 1, 'unique(id)': ...}, + # {'group_key': 2, 'unique(id)': ...}] + + Args: + on: The name of the column from which to collect unique values. + ignore_nulls: Whether to ignore null values when collecting unique items. + Default is True (nulls are excluded). + alias_name: Optional name for the resulting column. + """ + + def __init__( + self, + on: Optional[str] = None, + ignore_nulls: bool = True, + alias_name: Optional[str] = None, + ): + super().__init__( + alias_name if alias_name else f"unique({str(on)})", + on=on, + ignore_nulls=ignore_nulls, + zero_factory=set, + ) + + def combine(self, current_accumulator: AggType, new: AggType) -> AggType: + return self._to_set(current_accumulator) | self._to_set(new) + + def aggregate_block(self, block: Block) -> AggType: + import pyarrow.compute as pac + + col = BlockAccessor.for_block(block).to_arrow().column(self._target_col_name) + return pac.unique(col).to_pylist() + + @staticmethod + def _to_set(x): + if isinstance(x, set): + return x + elif isinstance(x, list): + return set(x) + else: + return {x} + + +def _null_safe_zero_factory(zero_factory, ignore_nulls: bool): + """NOTE: PLEASE READ CAREFULLY BEFORE CHANGING + + Null-safe zero factory is crucial for implementing proper aggregation + protocol (monoid) w/o the need for additional containers. + + Main hurdle for implementing proper aggregation semantic is to be able to encode + semantic of an "empty accumulator" and be able to tell it from the case when + accumulator is actually holding null value: + + - Empty container can be overridden with any value + - Container holding null can't be overridden if ignore_nulls=False + + However, it's possible for us to exploit asymmetry in cases of ignore_nulls being + True or False: + + - Case of ignore_nulls=False entails that if there's any "null" in the sequence, + aggregation is undefined and correspondingly expected to return null + + - Case of ignore_nulls=True in turn, entails that if aggregation returns "null" + if and only if the sequence does NOT have any non-null value + + Therefore, we apply this difference in semantic to zero-factory to make sure that + our aggregation protocol is adherent to that definition: + + - If ignore_nulls=True, zero-factory returns null, therefore encoding empty + container + - If ignore_nulls=False, couldn't return null as aggregation will incorrectly + prioritize it, and instead it returns true zero value for the aggregation + (ie 0 for count/sum, -inf for max, etc). + """ + + if ignore_nulls: + + def _safe_zero_factory(_): + return None + + else: + + def _safe_zero_factory(_): + return zero_factory() + + return _safe_zero_factory + + +def _null_safe_aggregate( + aggregate: Callable[[Block], AggType], + ignore_nulls: bool, +) -> Callable[[Block], Optional[AggType]]: + def _safe_aggregate(block: Block) -> Optional[AggType]: + result = aggregate(block) + # NOTE: If `ignore_nulls=True`, aggregation will only be returning + # null if the block does NOT contain any non-null elements + if is_null(result) and ignore_nulls: + return None + + return result + + return _safe_aggregate + + +def _null_safe_finalize( + finalize: Callable[[AggType], AggType] +) -> Callable[[Optional[AggType]], AggType]: + def _safe_finalize(acc: Optional[AggType]) -> AggType: + # If accumulator container is not null, finalize. + # Otherwise, return as is. + return acc if is_null(acc) else finalize(acc) + + return _safe_finalize + + +def _null_safe_combine( + combine: Callable[[AggType, AggType], AggType], ignore_nulls: bool +) -> Callable[[Optional[AggType], Optional[AggType]], Optional[AggType]]: + """Null-safe combination have to be an associative operation + with an identity element (zero) or in other words implement a monoid. + + To achieve that in the presence of null values following semantic is + established: + + - Case of ignore_nulls=True: + - If current accumulator is null (ie empty), return new accumulator + - If new accumulator is null (ie empty), return cur + - Otherwise combine (current and new) + + - Case of ignore_nulls=False: + - If new accumulator is null (ie has null in the sequence, b/c we're + NOT ignoring nulls), return it + - If current accumulator is null (ie had null in the prior sequence, + b/c we're NOT ignoring nulls), return it + - Otherwise combine (current and new) + """ + + if ignore_nulls: + + def _safe_combine( + cur: Optional[AggType], new: Optional[AggType] + ) -> Optional[AggType]: + + if is_null(cur): + return new + elif is_null(new): + return cur + else: + return combine(cur, new) + + else: + + def _safe_combine( + cur: Optional[AggType], new: Optional[AggType] + ) -> Optional[AggType]: + + if is_null(new): + return new + elif is_null(cur): + return cur + else: + return combine(cur, new) + + return _safe_combine diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/block.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/block.py new file mode 100644 index 0000000000000000000000000000000000000000..e2bcaa966cd7b4802b44afcb55282a5a0382cc1d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/block.py @@ -0,0 +1,748 @@ +import collections +import logging +import time +from dataclasses import dataclass, fields +from enum import Enum +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterator, + List, + Optional, + Protocol, + Tuple, + TypeVar, + Union, +) + +import numpy as np +import pyarrow as pa + +import ray +from ray.air.util.tensor_extensions.arrow import ArrowConversionError +from ray.data._internal.util import _check_pyarrow_version, _truncated_repr +from ray.types import ObjectRef +from ray.util import log_once +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + import pandas + import pyarrow + + from ray.data._internal.block_builder import BlockBuilder + from ray.data._internal.pandas_block import PandasBlockSchema + from ray.data._internal.planner.exchange.sort_task_spec import SortKey + from ray.data.aggregate import AggregateFn + + +T = TypeVar("T", contravariant=True) +U = TypeVar("U", covariant=True) + +KeyType = TypeVar("KeyType") +AggType = TypeVar("AggType") + + +# Represents a batch of records to be stored in the Ray object store. +# +# Block data can be accessed in a uniform way via ``BlockAccessors`` like` +# ``ArrowBlockAccessor``. +Block = Union["pyarrow.Table", "pandas.DataFrame"] + +# Represents the schema of a block, which can be either a Python type or a +# pyarrow schema. This is used to describe the structure of the data in a block. +Schema = Union[type, "PandasBlockSchema", "pyarrow.lib.Schema"] + +# Represents a single column of the ``Block`` +BlockColumn = Union["pyarrow.ChunkedArray", "pyarrow.Array", "pandas.Series"] + + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class BlockType(Enum): + ARROW = "arrow" + PANDAS = "pandas" + + +# User-facing data batch type. This is the data type for data that is supplied to and +# returned from batch UDFs. +DataBatch = Union["pyarrow.Table", "pandas.DataFrame", Dict[str, np.ndarray]] + +# User-facing data column type. This is the data type for data that is supplied to and +# returned from column UDFs. +DataBatchColumn = Union[BlockColumn, np.ndarray] + + +# A class type that implements __call__. +CallableClass = type + + +class _CallableClassProtocol(Protocol[T, U]): + def __call__(self, __arg: T) -> Union[U, Iterator[U]]: + ... + + +# A user defined function passed to map, map_batches, ec. +UserDefinedFunction = Union[ + Callable[[T], U], + Callable[[T], Iterator[U]], + "_CallableClassProtocol", +] + +# A list of block references pending computation by a single task. For example, +# this may be the output of a task reading a file. +BlockPartition = List[Tuple[ObjectRef[Block], "BlockMetadata"]] + +# The metadata that describes the output of a BlockPartition. This has the +# same type as the metadata that describes each block in the partition. +BlockPartitionMetadata = List["BlockMetadata"] + +VALID_BATCH_FORMATS = ["pandas", "pyarrow", "numpy", None] +DEFAULT_BATCH_FORMAT = "numpy" + + +def _apply_batch_format(given_batch_format: Optional[str]) -> str: + if given_batch_format == "default": + given_batch_format = DEFAULT_BATCH_FORMAT + if given_batch_format not in VALID_BATCH_FORMATS: + raise ValueError( + f"The given batch format {given_batch_format} isn't allowed (must be one of" + f" {VALID_BATCH_FORMATS})." + ) + return given_batch_format + + +@DeveloperAPI +def to_stats(metas: List["BlockMetadata"]) -> List["BlockStats"]: + return [m.to_stats() for m in metas] + + +@DeveloperAPI +class BlockExecStats: + """Execution stats for this block. + + Attributes: + wall_time_s: The wall-clock time it took to compute this block. + cpu_time_s: The CPU time it took to compute this block. + node_id: A unique id for the node that computed this block. + max_uss_bytes: An estimate of the maximum amount of physical memory that the + process was using while computing this block. + """ + + def __init__(self): + self.start_time_s: Optional[float] = None + self.end_time_s: Optional[float] = None + self.wall_time_s: Optional[float] = None + self.udf_time_s: Optional[float] = 0 + self.cpu_time_s: Optional[float] = None + self.node_id = ray.runtime_context.get_runtime_context().get_node_id() + self.max_uss_bytes: int = 0 + self.task_idx: Optional[int] = None + + @staticmethod + def builder() -> "_BlockExecStatsBuilder": + return _BlockExecStatsBuilder() + + def __repr__(self): + return repr( + { + "wall_time_s": self.wall_time_s, + "cpu_time_s": self.cpu_time_s, + "udf_time_s": self.udf_time_s, + "node_id": self.node_id, + } + ) + + +class _BlockExecStatsBuilder: + """Helper class for building block stats. + + When this class is created, we record the start time. When build() is + called, the time delta is saved as part of the stats. + """ + + def __init__(self): + self._start_time = time.perf_counter() + self._start_cpu = time.process_time() + + def build(self) -> "BlockExecStats": + # Record end times. + end_time = time.perf_counter() + end_cpu = time.process_time() + + # Build the stats. + stats = BlockExecStats() + stats.start_time_s = self._start_time + stats.end_time_s = end_time + stats.wall_time_s = end_time - self._start_time + stats.cpu_time_s = end_cpu - self._start_cpu + + return stats + + +@DeveloperAPI +@dataclass +class BlockStats: + """Statistics about the block produced""" + + #: The number of rows contained in this block, or None. + num_rows: Optional[int] + #: The approximate size in bytes of this block, or None. + size_bytes: Optional[int] + #: Execution stats for this block. + exec_stats: Optional[BlockExecStats] + + def __post_init__(self): + if self.size_bytes is not None: + # Require size_bytes to be int, ray.util.metrics objects + # will not take other types like numpy.int64 + assert isinstance(self.size_bytes, int) + + +_BLOCK_STATS_FIELD_NAMES = {f.name for f in fields(BlockStats)} + + +@DeveloperAPI +@dataclass +class BlockMetadata(BlockStats): + """Metadata about the block.""" + + #: The pyarrow schema or types of the block elements, or None. + #: The list of file paths used to generate this block, or + #: the empty list if indeterminate. + input_files: Optional[List[str]] + + def to_stats(self): + return BlockStats( + **{key: self.__getattribute__(key) for key in _BLOCK_STATS_FIELD_NAMES} + ) + + def __post_init__(self): + super().__post_init__() + + if self.input_files is None: + self.input_files = [] + + +@DeveloperAPI(stability="alpha") +@dataclass +class BlockMetadataWithSchema(BlockMetadata): + schema: Optional[Schema] = None + + def __init__(self, metadata: BlockMetadata, schema: Optional["Schema"] = None): + super().__init__( + input_files=metadata.input_files, + size_bytes=metadata.size_bytes, + num_rows=metadata.num_rows, + exec_stats=metadata.exec_stats, + ) + self.schema = schema + + def from_block( + block: Block, stats: Optional["BlockExecStats"] = None + ) -> "BlockMetadataWithSchema": + accessor = BlockAccessor.for_block(block) + meta = accessor.get_metadata(exec_stats=stats) + schema = accessor.schema() + return BlockMetadataWithSchema(metadata=meta, schema=schema) + + @property + def metadata(self) -> BlockMetadata: + return BlockMetadata( + num_rows=self.num_rows, + size_bytes=self.size_bytes, + exec_stats=self.exec_stats, + input_files=self.input_files, + ) + + +@DeveloperAPI +class BlockAccessor: + """Provides accessor methods for a specific block. + + Ideally, we wouldn't need a separate accessor classes for blocks. However, + this is needed if we want to support storing ``pyarrow.Table`` directly + as a top-level Ray object, without a wrapping class (issue #17186). + """ + + def num_rows(self) -> int: + """Return the number of rows contained in this block.""" + raise NotImplementedError + + def iter_rows(self, public_row_format: bool) -> Iterator[T]: + """Iterate over the rows of this block. + + Args: + public_row_format: Whether to cast rows into the public Dict row + format (this incurs extra copy conversions). + """ + raise NotImplementedError + + def slice(self, start: int, end: int, copy: bool = False) -> Block: + """Return a slice of this block. + + Args: + start: The starting index of the slice (inclusive). + end: The ending index of the slice (exclusive). + copy: Whether to perform a data copy for the slice. + + Returns: + The sliced block result. + """ + raise NotImplementedError + + def take(self, indices: List[int]) -> Block: + """Return a new block containing the provided row indices. + + Args: + indices: The row indices to return. + + Returns: + A new block containing the provided row indices. + """ + raise NotImplementedError + + def select(self, columns: List[Optional[str]]) -> Block: + """Return a new block containing the provided columns.""" + raise NotImplementedError + + def rename_columns(self, columns_rename: Dict[str, str]) -> Block: + """Return the block reflecting the renamed columns.""" + raise NotImplementedError + + def random_shuffle(self, random_seed: Optional[int]) -> Block: + """Randomly shuffle this block.""" + raise NotImplementedError + + def to_pandas(self) -> "pandas.DataFrame": + """Convert this block into a Pandas dataframe.""" + raise NotImplementedError + + def to_numpy( + self, columns: Optional[Union[str, List[str]]] = None + ) -> Union[np.ndarray, Dict[str, np.ndarray]]: + """Convert this block (or columns of block) into a NumPy ndarray. + + Args: + columns: Name of columns to convert, or None if converting all columns. + """ + raise NotImplementedError + + def to_arrow(self) -> "pyarrow.Table": + """Convert this block into an Arrow table.""" + raise NotImplementedError + + def to_block(self) -> Block: + """Return the base block that this accessor wraps.""" + raise NotImplementedError + + def to_default(self) -> Block: + """Return the default data format for this accessor.""" + return self.to_block() + + def to_batch_format(self, batch_format: Optional[str]) -> DataBatch: + """Convert this block into the provided batch format. + + Args: + batch_format: The batch format to convert this block to. + + Returns: + This block formatted as the provided batch format. + """ + if batch_format is None: + return self.to_block() + elif batch_format == "default" or batch_format == "native": + return self.to_default() + elif batch_format == "pandas": + return self.to_pandas() + elif batch_format == "pyarrow": + return self.to_arrow() + elif batch_format == "numpy": + return self.to_numpy() + else: + raise ValueError( + f"The batch format must be one of {VALID_BATCH_FORMATS}, got: " + f"{batch_format}" + ) + + def size_bytes(self) -> int: + """Return the approximate size in bytes of this block.""" + raise NotImplementedError + + def schema(self) -> Union[type, "pyarrow.lib.Schema"]: + """Return the Python type or pyarrow schema of this block.""" + raise NotImplementedError + + def get_metadata( + self, + input_files: Optional[List[str]] = None, + exec_stats: Optional[BlockExecStats] = None, + ) -> BlockMetadata: + """Create a metadata object from this block.""" + return BlockMetadata( + num_rows=self.num_rows(), + size_bytes=self.size_bytes(), + input_files=input_files, + exec_stats=exec_stats, + ) + + def zip(self, other: "Block") -> "Block": + """Zip this block with another block of the same type and size.""" + raise NotImplementedError + + @staticmethod + def builder() -> "BlockBuilder": + """Create a builder for this block type.""" + raise NotImplementedError + + @classmethod + def batch_to_block( + cls, + batch: DataBatch, + block_type: Optional[BlockType] = None, + ) -> Block: + """Create a block from user-facing data formats.""" + + if isinstance(batch, np.ndarray): + raise ValueError( + f"Error validating {_truncated_repr(batch)}: " + "Standalone numpy arrays are not " + "allowed in Ray 2.5. Return a dict of field -> array, " + "e.g., `{'data': array}` instead of `array`." + ) + + elif isinstance(batch, collections.abc.Mapping): + if block_type is None or block_type == BlockType.ARROW: + try: + return cls.batch_to_arrow_block(batch) + except ArrowConversionError as e: + if log_once("_fallback_to_pandas_block_warning"): + logger.warning( + f"Failed to convert batch to Arrow due to: {e}; " + f"falling back to Pandas block" + ) + + if block_type is None: + return cls.batch_to_pandas_block(batch) + else: + raise e + else: + assert block_type == BlockType.PANDAS + return cls.batch_to_pandas_block(batch) + return batch + + @classmethod + def batch_to_arrow_block(cls, batch: Dict[str, Any]) -> Block: + """Create an Arrow block from user-facing data formats.""" + from ray.data._internal.arrow_block import ArrowBlockBuilder + + return ArrowBlockBuilder._table_from_pydict(batch) + + @classmethod + def batch_to_pandas_block(cls, batch: Dict[str, Any]) -> Block: + """Create a Pandas block from user-facing data formats.""" + from ray.data._internal.pandas_block import PandasBlockBuilder + + return PandasBlockBuilder._table_from_pydict(batch) + + @staticmethod + def for_block(block: Block) -> "BlockAccessor[T]": + """Create a block accessor for the given block.""" + _check_pyarrow_version() + import pandas + import pyarrow + + if isinstance(block, pyarrow.Table): + from ray.data._internal.arrow_block import ArrowBlockAccessor + + return ArrowBlockAccessor(block) + elif isinstance(block, pandas.DataFrame): + from ray.data._internal.pandas_block import PandasBlockAccessor + + return PandasBlockAccessor(block) + elif isinstance(block, bytes): + from ray.data._internal.arrow_block import ArrowBlockAccessor + + return ArrowBlockAccessor.from_bytes(block) + elif isinstance(block, list): + raise ValueError( + f"Error validating {_truncated_repr(block)}: " + "Standalone Python objects are not " + "allowed in Ray 2.5. To use Python objects in a dataset, " + "wrap them in a dict of numpy arrays, e.g., " + "return `{'item': batch}` instead of just `batch`." + ) + else: + raise TypeError("Not a block type: {} ({})".format(block, type(block))) + + def sample(self, n_samples: int, sort_key: "SortKey") -> "Block": + """Return a random sample of items from this block.""" + raise NotImplementedError + + def count(self, on: str, ignore_nulls: bool = False) -> Optional[U]: + """Returns a count of the distinct values in the provided column""" + raise NotImplementedError + + def sum(self, on: str, ignore_nulls: bool) -> Optional[U]: + """Returns a sum of the values in the provided column""" + raise NotImplementedError + + def min(self, on: str, ignore_nulls: bool) -> Optional[U]: + """Returns a min of the values in the provided column""" + raise NotImplementedError + + def max(self, on: str, ignore_nulls: bool) -> Optional[U]: + """Returns a max of the values in the provided column""" + raise NotImplementedError + + def mean(self, on: str, ignore_nulls: bool) -> Optional[U]: + """Returns a mean of the values in the provided column""" + raise NotImplementedError + + def sum_of_squared_diffs_from_mean( + self, + on: str, + ignore_nulls: bool, + mean: Optional[U] = None, + ) -> Optional[U]: + """Returns a sum of diffs (from mean) squared for the provided column""" + raise NotImplementedError + + def sort(self, sort_key: "SortKey") -> "Block": + """Returns new block sorted according to provided `sort_key`""" + raise NotImplementedError + + def sort_and_partition( + self, boundaries: List[T], sort_key: "SortKey" + ) -> List["Block"]: + """Return a list of sorted partitions of this block.""" + raise NotImplementedError + + def _aggregate(self, key: "SortKey", aggs: Tuple["AggregateFn"]) -> Block: + """Combine rows with the same key into an accumulator.""" + raise NotImplementedError + + @staticmethod + def merge_sorted_blocks( + blocks: List["Block"], sort_key: "SortKey" + ) -> Tuple[Block, BlockMetadataWithSchema]: + """Return a sorted block by merging a list of sorted blocks.""" + raise NotImplementedError + + @staticmethod + def _combine_aggregated_blocks( + blocks: List[Block], + sort_key: "SortKey", + aggs: Tuple["AggregateFn"], + finalize: bool = True, + ) -> Tuple[Block, BlockMetadataWithSchema]: + """Aggregate partially combined and sorted blocks.""" + raise NotImplementedError + + def _find_partitions_sorted( + self, + boundaries: List[Tuple[Any]], + sort_key: "SortKey", + ) -> List[Block]: + """NOTE: PLEASE READ CAREFULLY + + Returns dataset partitioned using list of boundaries + + This method requires that + - Block being sorted (according to `sort_key`) + - Boundaries is a sorted list of tuples + """ + raise NotImplementedError + + def block_type(self) -> BlockType: + """Return the block type of this block.""" + raise NotImplementedError + + def _get_group_boundaries_sorted(self, keys: List[str]) -> np.ndarray: + """ + NOTE: THIS METHOD ASSUMES THAT PROVIDED BLOCK IS ALREADY SORTED + + Compute boundaries of the groups within a block based on provided + key (a column or a list of columns) + + NOTE: In each column, NaNs/None are considered to be the same group. + + Args: + block: sorted block for which grouping of rows will be determined + based on provided key + keys: list of columns determining the key for every row based on + which the block will be grouped + + Returns: + A list of starting indices of each group and an end index of the last + group, i.e., there are ``num_groups + 1`` entries and the first and last + entries are 0 and ``len(array)`` respectively. + """ + + if self.num_rows() == 0: + return np.array([], dtype=np.int32) + elif not keys: + # If no keys are specified, whole block is considered a single group + return np.array([0, self.num_rows()]) + + # Convert key columns to Numpy (to perform vectorized + # ops on them) + projected_block = self.to_numpy(keys) + + return _get_group_boundaries_sorted_numpy(list(projected_block.values())) + + +@DeveloperAPI(stability="beta") +class BlockColumnAccessor: + """Provides vendor-neutral interface to apply common operations + to block's (Pandas/Arrow) columns""" + + def __init__(self, col: BlockColumn): + self._column = col + + def count(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: + """Returns a count of the distinct values in the column""" + raise NotImplementedError() + + def sum(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: + """Returns a sum of the values in the column""" + return NotImplementedError() + + def min(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: + """Returns a min of the values in the column""" + raise NotImplementedError() + + def max(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: + """Returns a max of the values in the column""" + raise NotImplementedError() + + def mean(self, *, ignore_nulls: bool, as_py: bool = True) -> Optional[U]: + """Returns a mean of the values in the column""" + raise NotImplementedError() + + def quantile( + self, *, q: float, ignore_nulls: bool, as_py: bool = True + ) -> Optional[U]: + """Returns requested quantile of the given column""" + raise NotImplementedError() + + def unique(self) -> BlockColumn: + """Returns new column holding only distinct values of the current one""" + raise NotImplementedError() + + def flatten(self) -> BlockColumn: + """Flattens nested lists merging them into top-level container""" + + raise NotImplementedError() + + def sum_of_squared_diffs_from_mean( + self, + *, + ignore_nulls: bool, + mean: Optional[U] = None, + as_py: bool = True, + ) -> Optional[U]: + """Returns a sum of diffs (from mean) squared for the column""" + raise NotImplementedError() + + def to_pylist(self) -> List[Any]: + """Converts block column to a list of Python native objects""" + raise NotImplementedError() + + def to_numpy(self, zero_copy_only: bool = False) -> np.ndarray: + """Converts underlying column to Numpy""" + raise NotImplementedError() + + def _as_arrow_compatible(self) -> Union[List[Any], "pyarrow.Array"]: + """Converts block column into a representation compatible with Arrow""" + raise NotImplementedError() + + @staticmethod + def for_column(col: BlockColumn) -> "BlockColumnAccessor": + """Create a column accessor for the given column""" + _check_pyarrow_version() + + import pandas as pd + + if isinstance(col, pa.Array) or isinstance(col, pa.ChunkedArray): + from ray.data._internal.arrow_block import ArrowBlockColumnAccessor + + return ArrowBlockColumnAccessor(col) + elif isinstance(col, pd.Series): + from ray.data._internal.pandas_block import PandasBlockColumnAccessor + + return PandasBlockColumnAccessor(col) + else: + raise TypeError( + f"Expected either a pandas.Series or pyarrow.Array (ChunkedArray) " + f"(got {type(col)})" + ) + + +def _get_group_boundaries_sorted_numpy(columns: list[np.ndarray]) -> np.ndarray: + # There are 3 categories: general, numerics with NaN, and categorical with None. + # We only needed to check the last element for NaNs/None, as they are assumed to + # be sorted. + general_arrays = [] + num_arrays_with_nan = [] + cat_arrays_with_none = [] + for arr in columns: + if np.issubdtype(arr.dtype, np.number) and np.isnan(arr[-1]): + num_arrays_with_nan.append(arr) + elif not np.issubdtype(arr.dtype, np.number) and arr[-1] is None: + cat_arrays_with_none.append(arr) + else: + general_arrays.append(arr) + + # Compute the difference between each pair of elements. Handle the cases + # where neighboring elements are both NaN or None. Output as a list of + # boolean arrays. + diffs = [] + if len(general_arrays) > 0: + diffs.append( + np.vstack([arr[1:] != arr[:-1] for arr in general_arrays]).any(axis=0) + ) + if len(num_arrays_with_nan) > 0: + # Two neighboring numeric elements belong to the same group when they are + # 1) both finite and equal + # or 2) both np.nan + diffs.append( + np.vstack( + [ + (arr[1:] != arr[:-1]) + & (np.isfinite(arr[1:]) | np.isfinite(arr[:-1])) + for arr in num_arrays_with_nan + ] + ).any(axis=0) + ) + if len(cat_arrays_with_none) > 0: + # Two neighboring str/object elements belong to the same group when they are + # 1) both finite and equal + # or 2) both None + diffs.append( + np.vstack( + [ + (arr[1:] != arr[:-1]) + & ~(np.equal(arr[1:], None) & np.equal(arr[:-1], None)) + for arr in cat_arrays_with_none + ] + ).any(axis=0) + ) + + # A series of vectorized operations to compute the boundaries: + # - column_stack: stack the bool arrays into a single 2D bool array + # - any() and nonzero(): find the indices where any of the column diffs are True + # - add 1 to get the index of the first element of the next group + # - hstack(): include the 0 and last indices to the boundaries + boundaries = np.hstack( + [ + [0], + (np.column_stack(diffs).any(axis=1).nonzero()[0] + 1), + [len(columns[0])], + ] + ).astype(int) + + return boundaries diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/collate_fn.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/collate_fn.py new file mode 100644 index 0000000000000000000000000000000000000000..93290b908a2daae230995648951d39c2eac93a57 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/collate_fn.py @@ -0,0 +1,275 @@ +import abc +from typing import ( + TYPE_CHECKING, + Any, + Dict, + Generic, + List, + Mapping, + Optional, + Tuple, + TypeVar, + Union, +) + +import numpy as np + +from ray.data.block import DataBatch +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + import pandas + import pyarrow + import torch + + from ray.data.dataset import CollatedData + + +DataBatchType = TypeVar("DataBatchType", bound=DataBatch) + +TensorSequenceType = Union[ + List["torch.Tensor"], + Tuple["torch.Tensor", ...], +] + +TensorBatchType = Union[ + "torch.Tensor", + TensorSequenceType, + # For nested sequences of tensors, the inner sequence of tensors is combined during + # GPU transfer in `move_tensors_to_device`. + List[TensorSequenceType], + Tuple[TensorSequenceType, ...], + Mapping[str, "torch.Tensor"], + # For mapping (e.g., dict) of keys to sequences of tensors, the sequence of tensors + # is combined during GPU transfer in `move_tensors_to_device`. + Mapping[str, TensorSequenceType], +] + + +def _is_tensor(batch: Any) -> bool: + """Check if a batch is a single torch.Tensor.""" + import torch + + return isinstance(batch, torch.Tensor) + + +def _is_tensor_sequence(batch: Any) -> bool: + """Check if a batch is a sequence of torch.Tensors. + + >>> import torch + >>> _is_tensor_sequence(torch.ones(1)) + False + >>> _is_tensor_sequence([torch.ones(1), torch.ones(1)]) + True + >>> _is_tensor_sequence((torch.ones(1), torch.ones(1))) + True + >>> _is_tensor_sequence([torch.ones(1), 1]) + False + """ + return isinstance(batch, (list, tuple)) and all(_is_tensor(t) for t in batch) + + +def _is_nested_tensor_sequence(batch: Any) -> bool: + """Check if a batch is a sequence of sequences of torch.Tensors. + + Stops at one level of nesting. + + >>> import torch + >>> _is_nested_tensor_sequence([torch.ones(1), torch.ones(1)]) + False + >>> _is_nested_tensor_sequence( + ... ([torch.ones(1), torch.ones(1)], [torch.ones(1)]) + ... ) + True + """ + return isinstance(batch, (list, tuple)) and all( + _is_tensor_sequence(t) for t in batch + ) + + +def _is_tensor_mapping(batch: Any) -> bool: + """Check if a batch is a mapping of keys to torch.Tensors. + + >>> import torch + >>> _is_tensor_mapping({"a": torch.ones(1), "b": torch.ones(1)}) + True + >>> _is_tensor_mapping({"a": torch.ones(1), "b": [torch.ones(1), torch.ones(1)]}) + False + """ + return isinstance(batch, Mapping) and all(_is_tensor(v) for v in batch.values()) + + +def _is_tensor_sequence_mapping(batch: Any) -> bool: + """Check if a batch is a mapping of keys to sequences of torch.Tensors. + + >>> import torch + >>> _is_tensor_sequence_mapping({"a": torch.ones(1), "b": torch.ones(1)}) + False + >>> _is_tensor_sequence_mapping( + ... {"a": (torch.ones(1), torch.ones(1)), "b": [torch.ones(1), torch.ones(1)]} + ... ) + True + """ + return isinstance(batch, Mapping) and all( + _is_tensor_sequence(v) for v in batch.values() + ) + + +@DeveloperAPI +def is_tensor_batch_type(batch: Any) -> bool: + """Check if a batch matches any of the TensorBatchType variants. + + This function checks if the input batch is one of the following types: + 1. A single torch.Tensor + 2. A sequence of torch.Tensors + 3. A sequence of sequences of torch.Tensors + 4. A mapping (e.g., dict) of keys to torch.Tensors + 5. A mapping (e.g., dict) of keys to sequences of torch.Tensors + + Args: + batch: The input batch to check. Can be any type. + + Returns: + bool: True if the batch matches any TensorBatchType variant, False otherwise. + """ + return ( + _is_tensor(batch) + or _is_tensor_sequence(batch) + or _is_nested_tensor_sequence(batch) + or _is_tensor_mapping(batch) + or _is_tensor_sequence_mapping(batch) + ) + + +TensorBatchReturnType = Union[ + "torch.Tensor", + Tuple["torch.Tensor", ...], + Dict[str, "torch.Tensor"], +] + + +@DeveloperAPI +class CollateFn(Generic[DataBatchType]): + """Abstract interface for collate_fn for `iter_torch_batches`. See doc-string of + `collate_fn` in `iter_torch_batches` API for more details. + """ + + @abc.abstractmethod + def __call__(self, batch: DataBatchType) -> "CollatedData": + """Convert a batch of data to collated format. + + Args: + batch: The input batch to collate. + + Returns: + The collated data in the format expected by the model. + """ + ... + + +@DeveloperAPI +class ArrowBatchCollateFn(CollateFn["pyarrow.Table"]): + """Collate function that takes pyarrow.Table as the input batch type. + Arrow tables with chunked arrays can be efficiently transferred to GPUs without + combining the chunks with the `arrow_batch_to_tensors` utility function. + See `DefaultCollateFn` for example. + """ + + def __call__(self, batch: "pyarrow.Table") -> "CollatedData": + """Convert a batch of pyarrow.Table to collated format. + + Args: + batch: The input pyarrow.Table batch to collate. + + Returns: + The collated data in the format expected by the model. + """ + ... + + +@DeveloperAPI +class NumpyBatchCollateFn(CollateFn[Dict[str, np.ndarray]]): + """Collate function that takes a dictionary of numpy arrays as the input batch type.""" + + def __call__(self, batch: Dict[str, np.ndarray]) -> "CollatedData": + """Convert a batch of numpy arrays to collated format. + + Args: + batch: The input dictionary of numpy arrays batch to collate. + + Returns: + The collated data in the format expected by the model. + """ + ... + + +@DeveloperAPI +class PandasBatchCollateFn(CollateFn["pandas.DataFrame"]): + """Collate function that takes a pandas.DataFrame as the input batch type.""" + + def __call__(self, batch: "pandas.DataFrame") -> "CollatedData": + """Convert a batch of pandas.DataFrame to collated format. + + Args: + batch: The input pandas.DataFrame batch to collate. + + Returns: + The collated data in the format expected by the model. + """ + ... + + +@DeveloperAPI +class DefaultCollateFn(ArrowBatchCollateFn): + """Default collate function for converting Arrow batches to PyTorch tensors.""" + + def __init__( + self, + dtypes: Optional[Union["torch.dtype", Dict[str, "torch.dtype"]]] = None, + device: Optional[Union[str, "torch.device"]] = None, + pin_memory: bool = False, + ): + """Initialize the collate function. + + Args: + dtypes: The torch dtype(s) for the created tensor(s); if None, the dtype + will be inferred from the tensor data. + device: The device on which the tensor should be placed. Can be a string + (e.g. "cpu", "cuda:0") or a torch.device object. + pin_memory: Whether to pin the memory of the created tensors. + """ + import torch + + super().__init__() + self.dtypes = dtypes + if isinstance(device, str): + self.device = torch.device(device) + else: + self.device = device + self.pin_memory = pin_memory + + def __call__(self, batch: "pyarrow.Table") -> Dict[str, List["torch.Tensor"]]: + """Convert an Arrow batch to PyTorch tensors. + + Args: + batch: PyArrow Table to convert + + Returns: + Dictionary mapping column names to lists of tensors + """ + from ray.air._internal.torch_utils import ( + arrow_batch_to_tensors, + ) + + # For GPU transfer, we can skip the combining chunked arrays. This is because + # we can convert the chunked arrays to corresponding numpy format and then to + # Tensors and transfer the corresponding list of Tensors to GPU directly. + # However, for CPU transfer, we need to combine the chunked arrays first + # before converting to numpy format and then to Tensors. + combine_chunks = self.device.type == "cpu" + return arrow_batch_to_tensors( + batch, + dtypes=self.dtypes, + combine_chunks=combine_chunks, + pin_memory=self.pin_memory, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/context.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/context.py new file mode 100644 index 0000000000000000000000000000000000000000..0a693c1e89fac718855201b1ec47968f7198f5ae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/context.py @@ -0,0 +1,695 @@ +import copy +import enum +import logging +import os +import threading +import warnings +from dataclasses import dataclass, field +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union + +import ray +from ray._private.ray_constants import env_bool, env_float, env_integer +from ray._private.worker import WORKER_MODE +from ray.data._internal.logging import update_dataset_logger_for_worker +from ray.util.annotations import DeveloperAPI +from ray.util.debug import log_once +from ray.util.scheduling_strategies import SchedulingStrategyT + +if TYPE_CHECKING: + from ray.data._internal.execution.interfaces import ExecutionOptions + +logger = logging.getLogger(__name__) + +# The context singleton on this process. +_default_context: "Optional[DataContext]" = None +_context_lock = threading.Lock() + + +@DeveloperAPI(stability="alpha") +class ShuffleStrategy(str, enum.Enum): + """Shuffle strategy determines shuffling algorithm employed by operations + like aggregate, repartition, etc""" + + SORT_SHUFFLE_PULL_BASED = "sort_shuffle_pull_based" + SORT_SHUFFLE_PUSH_BASED = "sort_shuffle_push_based" + HASH_SHUFFLE = "hash_shuffle" + + +# We chose 128MiB for default: With streaming execution and num_cpus many concurrent +# tasks, the memory footprint will be about 2 * num_cpus * target_max_block_size ~= RAM +# * DEFAULT_OBJECT_STORE_MEMORY_LIMIT_FRACTION * 0.3 (default object store memory +# fraction set by Ray core), assuming typical memory:core ratio of 4:1. +DEFAULT_TARGET_MAX_BLOCK_SIZE = 128 * 1024 * 1024 + +# We set a higher target block size because we have to materialize +# all input blocks anyway, so there is no performance advantage to having +# smaller blocks. Setting a larger block size allows avoiding overhead from an +# excessive number of partitions. +# We choose 1GiB as 4x less than the typical memory:core ratio (4:1). +DEFAULT_SHUFFLE_TARGET_MAX_BLOCK_SIZE = 1024 * 1024 * 1024 + +# We will attempt to slice blocks whose size exceeds this factor * +# target_max_block_size. We will warn the user if slicing fails and we produce +# blocks larger than this threshold. +MAX_SAFE_BLOCK_SIZE_FACTOR = 1.5 + +# We will attempt to slice blocks whose size exceeds this factor * +# target_num_rows_per_block. We will warn the user if slicing fails and we produce +# blocks with more rows than this threshold. +MAX_SAFE_ROWS_PER_BLOCK_FACTOR = 1.5 + + +DEFAULT_TARGET_MIN_BLOCK_SIZE = 1 * 1024 * 1024 + +# This default appears to work well with most file sizes on remote storage systems, +# which is very sensitive to the buffer size. +DEFAULT_STREAMING_READ_BUFFER_SIZE = 32 * 1024 * 1024 + +DEFAULT_ENABLE_PANDAS_BLOCK = True + +DEFAULT_READ_OP_MIN_NUM_BLOCKS = 200 + +DEFAULT_ACTOR_PREFETCHER_ENABLED = False + +DEFAULT_USE_PUSH_BASED_SHUFFLE = bool( + os.environ.get("RAY_DATA_PUSH_BASED_SHUFFLE", None) +) + +DEFAULT_SHUFFLE_STRATEGY = os.environ.get( + "RAY_DATA_DEFAULT_SHUFFLE_STRATEGY", ShuffleStrategy.SORT_SHUFFLE_PULL_BASED +) + +DEFAULT_MAX_HASH_SHUFFLE_AGGREGATORS = env_integer( + "RAY_DATA_MAX_HASH_SHUFFLE_AGGREGATORS", 64 +) + +DEFAULT_SCHEDULING_STRATEGY = "SPREAD" + +# This default enables locality-based scheduling in Ray for tasks where arg data +# transfer is a bottleneck. +DEFAULT_SCHEDULING_STRATEGY_LARGE_ARGS = "DEFAULT" + +DEFAULT_LARGE_ARGS_THRESHOLD = 50 * 1024 * 1024 + +DEFAULT_USE_POLARS = False + +DEFAULT_USE_POLARS_SORT = False + +DEFAULT_EAGER_FREE = bool(int(os.environ.get("RAY_DATA_EAGER_FREE", "0"))) + +DEFAULT_DECODING_SIZE_ESTIMATION_ENABLED = True + +DEFAULT_MIN_PARALLELISM = env_integer("RAY_DATA_DEFAULT_MIN_PARALLELISM", 200) + +DEFAULT_ENABLE_TENSOR_EXTENSION_CASTING = env_bool( + "RAY_DATA_ENABLE_TENSOR_EXTENSION_CASTING", + True, +) + +# NOTE: V1 tensor type format only supports tensors of no more than 2Gb in +# total cumulative size (due to it internally utilizing int32 offsets) +# +# V2 in turn relies on int64 offsets, therefore having a limit of ~9Eb (exabytes) +DEFAULT_USE_ARROW_TENSOR_V2 = env_bool("RAY_DATA_USE_ARROW_TENSOR_V2", True) + +DEFAULT_AUTO_LOG_STATS = False + +DEFAULT_VERBOSE_STATS_LOG = False + +DEFAULT_TRACE_ALLOCATIONS = bool(int(os.environ.get("RAY_DATA_TRACE_ALLOCATIONS", "0"))) + +DEFAULT_LOG_INTERNAL_STACK_TRACE_TO_STDOUT = env_bool( + "RAY_DATA_LOG_INTERNAL_STACK_TRACE_TO_STDOUT", False +) + +DEFAULT_RAY_DATA_RAISE_ORIGINAL_MAP_EXCEPTION = env_bool( + "RAY_DATA_RAISE_ORIGINAL_MAP_EXCEPTION", False +) + +DEFAULT_USE_RAY_TQDM = bool(int(os.environ.get("RAY_TQDM", "1"))) + +# Globally enable or disable all progress bars. +# If this is False, both the global and operator-level progress bars are disabled. +DEFAULT_ENABLE_PROGRESS_BARS = not bool( + env_integer("RAY_DATA_DISABLE_PROGRESS_BARS", 0) +) +DEFAULT_ENABLE_PROGRESS_BAR_NAME_TRUNCATION = env_bool( + "RAY_DATA_ENABLE_PROGRESS_BAR_NAME_TRUNCATION", True +) + +DEFAULT_ENABLE_GET_OBJECT_LOCATIONS_FOR_METRICS = False + + +# `write_file_retry_on_errors` is deprecated in favor of `retried_io_errors`. You +# shouldn't need to modify `DEFAULT_WRITE_FILE_RETRY_ON_ERRORS`. +DEFAULT_WRITE_FILE_RETRY_ON_ERRORS = ( + "AWS Error INTERNAL_FAILURE", + "AWS Error NETWORK_CONNECTION", + "AWS Error SLOW_DOWN", + "AWS Error UNKNOWN (HTTP status 503)", +) + +DEFAULT_RETRIED_IO_ERRORS = ( + "AWS Error INTERNAL_FAILURE", + "AWS Error NETWORK_CONNECTION", + "AWS Error SLOW_DOWN", + "AWS Error UNKNOWN (HTTP status 503)", + "AWS Error SERVICE_UNAVAILABLE", +) + +DEFAULT_WARN_ON_DRIVER_MEMORY_USAGE_BYTES = 2 * 1024 * 1024 * 1024 + +DEFAULT_ACTOR_TASK_RETRY_ON_ERRORS = False + +DEFAULT_ENABLE_OP_RESOURCE_RESERVATION = env_bool( + "RAY_DATA_ENABLE_OP_RESOURCE_RESERVATION", True +) + +DEFAULT_OP_RESOURCE_RESERVATION_RATIO = float( + os.environ.get("RAY_DATA_OP_RESERVATION_RATIO", "0.5") +) + +DEFAULT_MAX_ERRORED_BLOCKS = 0 + +# Use this to prefix important warning messages for the user. +WARN_PREFIX = "⚠️ " + +# Use this to prefix important success messages for the user. +OK_PREFIX = "✔️ " + +# The default batch size for batch transformations before it was changed to `None`. +LEGACY_DEFAULT_BATCH_SIZE = 1024 + +# Default value of the max number of blocks that can be buffered at the +# streaming generator of each `DataOpTask`. +# Note, if this value is too large, we'll need to allocate more memory +# buffer for the pending task outputs, which may lead to bad performance +# as we may not have enough memory buffer for the operator outputs. +# If the value is too small, the task may be frequently blocked due to +# streaming generator backpressure. +DEFAULT_MAX_NUM_BLOCKS_IN_STREAMING_GEN_BUFFER = 2 + +# Default value for whether or not to try to create directories for write +# calls if the URI is an S3 URI. +DEFAULT_S3_TRY_CREATE_DIR = False + +DEFAULT_WAIT_FOR_MIN_ACTORS_S = env_integer( + "RAY_DATA_DEFAULT_WAIT_FOR_MIN_ACTORS_S", -1 +) + +DEFAULT_MAX_TASKS_IN_FLIGHT_PER_ACTOR = 4 + +# Enable per node metrics reporting for Ray Data, disabled by default. +DEFAULT_ENABLE_PER_NODE_METRICS = bool( + int(os.environ.get("RAY_DATA_PER_NODE_METRICS", "0")) +) + +DEFAULT_MIN_HASH_SHUFFLE_AGGREGATOR_WAIT_TIME_IN_S = env_integer( + "RAY_DATA_MIN_HASH_SHUFFLE_AGGREGATOR_WAIT_TIME_IN_S", 300 +) + +DEFAULT_HASH_SHUFFLE_AGGREGATOR_HEALTH_WARNING_INTERVAL_S = env_integer( + "RAY_DATA_HASH_SHUFFLE_AGGREGATOR_HEALTH_WARNING_INTERVAL_S", 30 +) + + +DEFAULT_ACTOR_POOL_UTIL_UPSCALING_THRESHOLD: float = env_float( + "RAY_DATA_DEFAULT_ACTOR_POOL_UTIL_UPSCALING_THRESHOLD", + 2.0, +) + +DEFAULT_ACTOR_POOL_UTIL_DOWNSCALING_THRESHOLD: float = env_float( + "RAY_DATA_DEFAULT_ACTOR_POOL_UTIL_DOWNSCALING_THRESHOLD", + 0.5, +) + + +@DeveloperAPI +@dataclass +class AutoscalingConfig: + # Actor Pool utilization threshold for upscaling. Once Actor Pool + # exceeds this utilization threshold it will start adding new actors. + # + # NOTE: Actor Pool utilization is defined as ratio of + # + # - Number of submitted tasks to + # - Max number of tasks the current set of Actors in the pool could run + # (defined as Ray Actor's `max_concurrency` * `pool.num_running_actors`) + # + # This utilization value could exceed 100%, when the number of submitted tasks + # exceed available concurrency-slots to run them in the current set of actors. + # + # This is possible when `max_tasks_in_flight_per_actor` (defaults to 2 x + # of `max_concurrency`) > Actor's `max_concurrency` and allows to overlap + # task execution with the fetching of the blocks for the next task providing + # for ability to negotiate a trade-off between autoscaling speed and resource + # efficiency (ie making tasks wait instead of immediately triggering execution) + actor_pool_util_upscaling_threshold: float = ( + DEFAULT_ACTOR_POOL_UTIL_UPSCALING_THRESHOLD + ) + + # Actor Pool utilization threshold for downscaling + actor_pool_util_downscaling_threshold: float = ( + DEFAULT_ACTOR_POOL_UTIL_DOWNSCALING_THRESHOLD + ) + + +def _execution_options_factory() -> "ExecutionOptions": + # Lazily import to avoid circular dependencies. + from ray.data._internal.execution.interfaces import ExecutionOptions + + return ExecutionOptions() + + +def _deduce_default_shuffle_algorithm() -> ShuffleStrategy: + if DEFAULT_USE_PUSH_BASED_SHUFFLE: + logger.warning( + "RAY_DATA_PUSH_BASED_SHUFFLE is deprecated, please use " + "RAY_DATA_DEFAULT_SHUFFLE_STRATEGY to set shuffling strategy" + ) + + return ShuffleStrategy.SORT_SHUFFLE_PUSH_BASED + else: + vs = [s for s in ShuffleStrategy] # noqa: C416 + + assert DEFAULT_SHUFFLE_STRATEGY in vs, ( + f"RAY_DATA_DEFAULT_SHUFFLE_STRATEGY has to be one of the [{','.join(vs)}] " + f"(got {DEFAULT_SHUFFLE_STRATEGY})" + ) + + return DEFAULT_SHUFFLE_STRATEGY + + +@DeveloperAPI +@dataclass +class DataContext: + """Global settings for Ray Data. + + Configure this class to enable advanced features and tune performance. + + .. warning:: + Apply changes before creating a :class:`~ray.data.Dataset`. Changes made after + won't take effect. + + .. note:: + This object is automatically propagated to workers. Access it from the driver + and remote workers with :meth:`DataContext.get_current()`. + + Examples: + >>> from ray.data import DataContext + >>> DataContext.get_current().enable_progress_bars = False + + Args: + target_max_block_size: The max target block size in bytes for reads and + transformations. + target_shuffle_max_block_size: The max target block size in bytes for shuffle + ops like ``random_shuffle``, ``sort``, and ``repartition``. + target_min_block_size: Ray Data avoids creating blocks smaller than this + size in bytes on read. This takes precedence over + ``read_op_min_num_blocks``. + streaming_read_buffer_size: Buffer size when doing streaming reads from local or + remote storage. + enable_pandas_block: Whether pandas block format is enabled. + actor_prefetcher_enabled: Whether to use actor based block prefetcher. + autoscaling_config: Autoscaling configuration. + use_push_based_shuffle: Whether to use push-based shuffle. + pipeline_push_based_shuffle_reduce_tasks: + scheduling_strategy: The global scheduling strategy. For tasks with large args, + ``scheduling_strategy_large_args`` takes precedence. + scheduling_strategy_large_args: Scheduling strategy for tasks with large args. + large_args_threshold: Size in bytes after which point task arguments are + considered large. Choose a value so that the data transfer overhead is + significant in comparison to task scheduling (i.e., low tens of ms). + use_polars: Whether to use Polars for tabular dataset sorts, groupbys, and + aggregations. + eager_free: Whether to eagerly free memory. + decoding_size_estimation: Whether to estimate in-memory decoding data size for + data source. + min_parallelism: This setting is deprecated. Use ``read_op_min_num_blocks`` + instead. + read_op_min_num_blocks: Minimum number of read output blocks for a dataset. + enable_tensor_extension_casting: Whether to automatically cast NumPy ndarray + columns in Pandas DataFrames to tensor extension columns. + use_arrow_tensor_v2: Config enabling V2 version of ArrowTensorArray supporting + tensors > 2Gb in size (off by default) + enable_fallback_to_arrow_object_ext_type: Enables fallback to serialize column + values not suppported by Arrow natively (like user-defined custom Python + classes for ex, etc) using `ArrowPythonObjectType` (simply serializing + these as bytes) + enable_auto_log_stats: Whether to automatically log stats after execution. If + disabled, you can still manually print stats with ``Dataset.stats()``. + verbose_stats_logs: Whether stats logs should be verbose. This includes fields + such as `extra_metrics` in the stats output, which are excluded by default. + trace_allocations: Whether to trace allocations / eager free. This adds + significant performance overheads and should only be used for debugging. + execution_options: The + :class:`~ray.data._internal.execution.interfaces.execution_options.ExecutionOptions` + to use. + use_ray_tqdm: Whether to enable distributed tqdm. + enable_progress_bars: Whether to enable progress bars. + enable_progress_bar_name_truncation: If True, the name of the progress bar + (often the operator name) will be truncated if it exceeds + `ProgressBar.MAX_NAME_LENGTH`. Otherwise, the full operator name is shown. + enable_get_object_locations_for_metrics: Whether to enable + ``get_object_locations`` for metrics. + write_file_retry_on_errors: A list of substrings of error messages that should + trigger a retry when writing files. This is useful for handling transient + errors when writing to remote storage systems. + warn_on_driver_memory_usage_bytes: If driver memory exceeds this threshold, + Ray Data warns you. For now, this only applies to shuffle ops because most + other ops are unlikely to use as much driver memory. + actor_task_retry_on_errors: The application-level errors that actor task should + retry. This follows same format as :ref:`retry_exceptions ` in + Ray Core. Default to `False` to not retry on any errors. Set to `True` to + retry all errors, or set to a list of errors to retry. + enable_op_resource_reservation: Whether to reserve resources for each operator. + op_resource_reservation_ratio: The ratio of the total resources to reserve for + each operator. + max_errored_blocks: Max number of blocks that are allowed to have errors, + unlimited if negative. This option allows application-level exceptions in + block processing tasks. These exceptions may be caused by UDFs (e.g., due to + corrupted data samples) or IO errors. Data in the failed blocks are dropped. + This option can be useful to prevent a long-running job from failing due to + a small number of bad blocks. + log_internal_stack_trace_to_stdout: Whether to include internal Ray Data/Ray + Core code stack frames when logging to stdout. The full stack trace is + always written to the Ray Data log file. + raise_original_map_exception: Whether to raise the original exception + encountered in map UDF instead of wrapping it in a `UserCodeException`. + print_on_execution_start: If ``True``, print execution information when + execution starts. + s3_try_create_dir: If ``True``, try to create directories on S3 when a write + call is made with a S3 URI. + wait_for_min_actors_s: The default time to wait for minimum requested + actors to start before raising a timeout, in seconds. + max_tasks_in_flight_per_actor: Max number of tasks that could be submitted + for execution to individual actor at the same time. Note that only up to + `max_concurrency` number of these tasks will be executing concurrently + while remaining ones will be waiting in the Actor's queue. Buffering + tasks in the queue allows us to overlap pulling of the blocks (which are + tasks arguments) with the execution of the prior tasks maximizing + individual Actor's utilization + retried_io_errors: A list of substrings of error messages that should + trigger a retry when reading or writing files. This is useful for handling + transient errors when reading from remote storage systems. + enable_per_node_metrics: Enable per node metrics reporting for Ray Data, + disabled by default. + memory_usage_poll_interval_s: The interval to poll the USS of map tasks. If `None`, + map tasks won't record memory stats. + """ + + target_max_block_size: int = DEFAULT_TARGET_MAX_BLOCK_SIZE + target_shuffle_max_block_size: int = DEFAULT_SHUFFLE_TARGET_MAX_BLOCK_SIZE + target_min_block_size: int = DEFAULT_TARGET_MIN_BLOCK_SIZE + streaming_read_buffer_size: int = DEFAULT_STREAMING_READ_BUFFER_SIZE + enable_pandas_block: bool = DEFAULT_ENABLE_PANDAS_BLOCK + actor_prefetcher_enabled: bool = DEFAULT_ACTOR_PREFETCHER_ENABLED + + autoscaling_config: AutoscalingConfig = field(default_factory=AutoscalingConfig) + + ################################################################ + # Sort-based shuffling configuration + ################################################################ + + use_push_based_shuffle: bool = DEFAULT_USE_PUSH_BASED_SHUFFLE + + _shuffle_strategy: ShuffleStrategy = _deduce_default_shuffle_algorithm() + + pipeline_push_based_shuffle_reduce_tasks: bool = True + + ################################################################ + # Hash-based shuffling configuration + ################################################################ + + # Default hash-shuffle parallelism level (will be used when not + # provided explicitly) + default_hash_shuffle_parallelism = DEFAULT_MIN_PARALLELISM + + # Max number of aggregating actors that could be provisioned + # to perform aggregations on partitions produced during hash-shuffling + # + # When unset defaults to `DataContext.min_parallelism` + max_hash_shuffle_aggregators: Optional[int] = DEFAULT_MAX_HASH_SHUFFLE_AGGREGATORS + + min_hash_shuffle_aggregator_wait_time_in_s: int = ( + DEFAULT_MIN_HASH_SHUFFLE_AGGREGATOR_WAIT_TIME_IN_S + ) + + hash_shuffle_aggregator_health_warning_interval_s: int = ( + DEFAULT_HASH_SHUFFLE_AGGREGATOR_HEALTH_WARNING_INTERVAL_S + ) + + # Max number of *concurrent* hash-shuffle finalization tasks running + # at the same time. This config is helpful to control concurrency of + # finalization tasks to prevent single aggregator running multiple tasks + # concurrently (for ex, to prevent it failing w/ OOM) + # + # When unset defaults to `DataContext.max_hash_shuffle_aggregators` + max_hash_shuffle_finalization_batch_size: Optional[int] = None + + join_operator_actor_num_cpus_per_partition_override: float = None + hash_shuffle_operator_actor_num_cpus_per_partition_override: float = None + hash_aggregate_operator_actor_num_cpus_per_partition_override: float = None + + scheduling_strategy: SchedulingStrategyT = DEFAULT_SCHEDULING_STRATEGY + scheduling_strategy_large_args: SchedulingStrategyT = ( + DEFAULT_SCHEDULING_STRATEGY_LARGE_ARGS + ) + large_args_threshold: int = DEFAULT_LARGE_ARGS_THRESHOLD + use_polars: bool = DEFAULT_USE_POLARS + use_polars_sort: bool = DEFAULT_USE_POLARS_SORT + eager_free: bool = DEFAULT_EAGER_FREE + decoding_size_estimation: bool = DEFAULT_DECODING_SIZE_ESTIMATION_ENABLED + min_parallelism: int = DEFAULT_MIN_PARALLELISM + read_op_min_num_blocks: int = DEFAULT_READ_OP_MIN_NUM_BLOCKS + enable_tensor_extension_casting: bool = DEFAULT_ENABLE_TENSOR_EXTENSION_CASTING + use_arrow_tensor_v2: bool = DEFAULT_USE_ARROW_TENSOR_V2 + enable_fallback_to_arrow_object_ext_type: Optional[bool] = None + enable_auto_log_stats: bool = DEFAULT_AUTO_LOG_STATS + verbose_stats_logs: bool = DEFAULT_VERBOSE_STATS_LOG + trace_allocations: bool = DEFAULT_TRACE_ALLOCATIONS + execution_options: "ExecutionOptions" = field( + default_factory=_execution_options_factory + ) + use_ray_tqdm: bool = DEFAULT_USE_RAY_TQDM + enable_progress_bars: bool = DEFAULT_ENABLE_PROGRESS_BARS + # By default, enable the progress bar for operator-level progress. + # In __post_init__(), we disable operator-level progress + # bars when running in a Ray job. + enable_operator_progress_bars: bool = True + enable_progress_bar_name_truncation: bool = ( + DEFAULT_ENABLE_PROGRESS_BAR_NAME_TRUNCATION + ) + enable_get_object_locations_for_metrics: bool = ( + DEFAULT_ENABLE_GET_OBJECT_LOCATIONS_FOR_METRICS + ) + write_file_retry_on_errors: List[str] = DEFAULT_WRITE_FILE_RETRY_ON_ERRORS + warn_on_driver_memory_usage_bytes: int = DEFAULT_WARN_ON_DRIVER_MEMORY_USAGE_BYTES + actor_task_retry_on_errors: Union[ + bool, List[BaseException] + ] = DEFAULT_ACTOR_TASK_RETRY_ON_ERRORS + op_resource_reservation_enabled: bool = DEFAULT_ENABLE_OP_RESOURCE_RESERVATION + op_resource_reservation_ratio: float = DEFAULT_OP_RESOURCE_RESERVATION_RATIO + max_errored_blocks: int = DEFAULT_MAX_ERRORED_BLOCKS + log_internal_stack_trace_to_stdout: bool = ( + DEFAULT_LOG_INTERNAL_STACK_TRACE_TO_STDOUT + ) + raise_original_map_exception: bool = DEFAULT_RAY_DATA_RAISE_ORIGINAL_MAP_EXCEPTION + print_on_execution_start: bool = True + s3_try_create_dir: bool = DEFAULT_S3_TRY_CREATE_DIR + # Timeout threshold (in seconds) for how long it should take for actors in the + # Actor Pool to start up. Exceeding this threshold will lead to execution being + # terminated with exception due to inability to secure min required capacity. + # + # Setting non-positive value here (ie <= 0) disables this functionality + # (defaults to -1). + wait_for_min_actors_s: int = DEFAULT_WAIT_FOR_MIN_ACTORS_S + max_tasks_in_flight_per_actor: Optional[int] = DEFAULT_MAX_TASKS_IN_FLIGHT_PER_ACTOR + retried_io_errors: List[str] = field( + default_factory=lambda: list(DEFAULT_RETRIED_IO_ERRORS) + ) + enable_per_node_metrics: bool = DEFAULT_ENABLE_PER_NODE_METRICS + override_object_store_memory_limit_fraction: float = None + memory_usage_poll_interval_s: Optional[float] = 1 + dataset_logger_id: Optional[str] = None + # This is a temporary workaround to allow actors to perform cleanup + # until https://github.com/ray-project/ray/issues/53169 is fixed. + # This hook is known to have a race condition bug in fault tolerance. + # I.E., after the hook is triggered and the UDF is deleted, another + # retry task may still be scheduled to this actor and it will fail. + _enable_actor_pool_on_exit_hook: bool = False + + def __post_init__(self): + # The additonal ray remote args that should be added to + # the task-pool-based data tasks. + self._task_pool_data_task_remote_args: Dict[str, Any] = {} + # The extra key-value style configs. + # These configs are managed by individual components or plugins via + # `set_config`, `get_config` and `remove_config`. + # The reason why we use a dict instead of individual fields is to decouple + # the DataContext from the plugin implementations, as well as to avoid + # circular dependencies. + self._kv_configs: Dict[str, Any] = {} + self._max_num_blocks_in_streaming_gen_buffer = ( + DEFAULT_MAX_NUM_BLOCKS_IN_STREAMING_GEN_BUFFER + ) + + is_ray_job = os.environ.get("RAY_JOB_ID") is not None + if is_ray_job: + is_driver = ray.get_runtime_context().worker.mode != WORKER_MODE + if is_driver and log_once( + "ray_data_disable_operator_progress_bars_in_ray_jobs" + ): + logger.info( + "Disabling operator-level progress bars by default in Ray Jobs. " + "To enable progress bars for all operators, set " + "`ray.data.DataContext.get_current()" + ".enable_operator_progress_bars = True`." + ) + # Disable operator-level progress bars by default in Ray jobs. + # The global progress bar for the overall Dataset execution will + # still be enabled, unless the user also sets + # `ray.data.DataContext.get_current().enable_progress_bars = False`. + self.enable_operator_progress_bars = False + else: + # When not running in Ray job, operator-level progress + # bars are enabled by default. + self.enable_operator_progress_bars = True + + def __setattr__(self, name: str, value: Any) -> None: + if ( + name == "write_file_retry_on_errors" + and value != DEFAULT_WRITE_FILE_RETRY_ON_ERRORS + ): + warnings.warn( + "`write_file_retry_on_errors` is deprecated. Configure " + "`retried_io_errors` instead.", + DeprecationWarning, + ) + elif name == "use_push_based_shuffle": + warnings.warn( + "`use_push_based_shuffle` is deprecated, please configure " + "`shuffle_strategy` instead.", + DeprecationWarning, + ) + + elif name == "use_polars": + warnings.warn( + "`use_polars` is deprecated, please configure " + "`use_polars_sort` instead.", + DeprecationWarning, + ) + self.use_polars_sort = value + + super().__setattr__(name, value) + + @staticmethod + def get_current() -> "DataContext": + """Get or create the current DataContext. + + When a Dataset is created, the current DataContext will be sealed. + Changes to `DataContext.get_current()` will not impact existing Datasets. + + Examples: + + .. testcode:: + import ray + + context = ray.data.DataContext.get_current() + + context.target_max_block_size = 100 * 1024 ** 2 + ds1 = ray.data.range(1) + context.target_max_block_size = 1 * 1024 ** 2 + ds2 = ray.data.range(1) + + # ds1's target_max_block_size will be 100MB + ds1.take_all() + # ds2's target_max_block_size will be 1MB + ds2.take_all() + + Developer notes: Avoid using `DataContext.get_current()` in data + internal components, use the DataContext object captured in the + Dataset and pass it around as arguments. + """ + + global _default_context + + with _context_lock: + if _default_context is None: + _default_context = DataContext() + + return _default_context + + @staticmethod + def _set_current(context: "DataContext") -> None: + """Set the current context in a remote worker. + + This is used internally by Dataset to propagate the driver context to + remote workers used for parallelization. + """ + global _default_context + if ( + not _default_context + or _default_context.dataset_logger_id != context.dataset_logger_id + ): + update_dataset_logger_for_worker(context.dataset_logger_id) + _default_context = context + + @property + def shuffle_strategy(self) -> ShuffleStrategy: + if self.use_push_based_shuffle: + logger.warning( + "`use_push_based_shuffle` is deprecated, please configure " + "`shuffle_strategy` instead.", + ) + + return ShuffleStrategy.SORT_SHUFFLE_PUSH_BASED + + return self._shuffle_strategy + + @shuffle_strategy.setter + def shuffle_strategy(self, value: ShuffleStrategy) -> None: + self._shuffle_strategy = value + + def get_config(self, key: str, default: Any = None) -> Any: + """Get the value for a key-value style config. + + Args: + key: The key of the config. + default: The default value to return if the key is not found. + Returns: The value for the key, or the default value if the key is not found. + """ + return self._kv_configs.get(key, default) + + def set_config(self, key: str, value: Any) -> None: + """Set the value for a key-value style config. + + Args: + key: The key of the config. + value: The value of the config. + """ + self._kv_configs[key] = value + + def remove_config(self, key: str) -> None: + """Remove a key-value style config. + + Args: + key: The key of the config. + """ + self._kv_configs.pop(key, None) + + def copy(self) -> "DataContext": + """Create a copy of the current DataContext.""" + return copy.deepcopy(self) + + def set_dataset_logger_id(self, dataset_id: str) -> None: + """Set the current dataset logger id. + + This is used internally to propagate the current dataset logger id to remote + workers. + """ + self.dataset_logger_id = dataset_id + + +# Backwards compatibility alias. +DatasetContext = DataContext diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/dataset.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..089049ee64f5ca23c556dc3f25ed462e42a794e0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/dataset.py @@ -0,0 +1,6270 @@ +import collections +import copy +import html +import itertools +import logging +import time +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Generic, + Iterable, + Iterator, + List, + Literal, + Mapping, + Optional, + Tuple, + TypeVar, + Union, +) + +import numpy as np + +import ray +import ray.cloudpickle as pickle +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray._private.usage import usage_lib +from ray.air.util.tensor_extensions.arrow import ( + ArrowTensorTypeV2, + get_arrow_extension_fixed_shape_tensor_types, +) +from ray.data._internal.compute import ComputeStrategy +from ray.data._internal.datasource.bigquery_datasink import BigQueryDatasink +from ray.data._internal.datasource.clickhouse_datasink import ( + ClickHouseDatasink, + ClickHouseTableSettings, + SinkMode, +) +from ray.data._internal.datasource.csv_datasink import CSVDatasink +from ray.data._internal.datasource.iceberg_datasink import IcebergDatasink +from ray.data._internal.datasource.image_datasink import ImageDatasink +from ray.data._internal.datasource.json_datasink import JSONDatasink +from ray.data._internal.datasource.lance_datasink import LanceDatasink +from ray.data._internal.datasource.mongo_datasink import MongoDatasink +from ray.data._internal.datasource.numpy_datasink import NumpyDatasink +from ray.data._internal.datasource.parquet_datasink import ParquetDatasink +from ray.data._internal.datasource.sql_datasink import SQLDatasink +from ray.data._internal.datasource.tfrecords_datasink import TFRecordDatasink +from ray.data._internal.datasource.webdataset_datasink import WebDatasetDatasink +from ray.data._internal.equalize import _equalize +from ray.data._internal.execution.interfaces import RefBundle +from ray.data._internal.execution.interfaces.ref_bundle import ( + _ref_bundles_iterator_to_block_refs_list, +) +from ray.data._internal.execution.util import memory_string +from ray.data._internal.iterator.iterator_impl import DataIteratorImpl +from ray.data._internal.iterator.stream_split_iterator import StreamSplitDataIterator +from ray.data._internal.logical.interfaces import LogicalPlan +from ray.data._internal.logical.operators.all_to_all_operator import ( + RandomizeBlocks, + RandomShuffle, + Repartition, + Sort, +) +from ray.data._internal.logical.operators.count_operator import Count +from ray.data._internal.logical.operators.input_data_operator import InputData +from ray.data._internal.logical.operators.join_operator import Join +from ray.data._internal.logical.operators.map_operator import ( + Filter, + FlatMap, + MapBatches, + MapRows, + Project, + StreamingRepartition, +) +from ray.data._internal.logical.operators.n_ary_operator import ( + Union as UnionLogicalOperator, + Zip, +) +from ray.data._internal.logical.operators.one_to_one_operator import Limit +from ray.data._internal.logical.operators.write_operator import Write +from ray.data._internal.pandas_block import PandasBlockBuilder, PandasBlockSchema +from ray.data._internal.plan import ExecutionPlan +from ray.data._internal.planner.exchange.sort_task_spec import SortKey +from ray.data._internal.planner.plan_write_op import gen_datasink_write_result +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data._internal.split import _get_num_rows, _split_at_indices +from ray.data._internal.stats import DatasetStats, DatasetStatsSummary, StatsManager +from ray.data._internal.util import ( + AllToAllAPI, + ConsumptionAPI, + _validate_rows_per_file_args, + get_compute_strategy, +) +from ray.data.aggregate import AggregateFn, Max, Mean, Min, Std, Sum, Unique +from ray.data.block import ( + VALID_BATCH_FORMATS, + Block, + BlockAccessor, + DataBatch, + DataBatchColumn, + T, + U, + UserDefinedFunction, + _apply_batch_format, +) +from ray.data.context import DataContext +from ray.data.datasource import Connection, Datasink, FilenameProvider, SaveMode +from ray.data.datasource.file_datasink import _FileDatasink +from ray.data.iterator import DataIterator +from ray.data.random_access_dataset import RandomAccessDataset +from ray.types import ObjectRef +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy +from ray.widgets import Template +from ray.widgets.util import repr_with_fallback + +if TYPE_CHECKING: + import daft + import dask + import mars + import modin + import pandas + import pyarrow + import pyspark + import tensorflow as tf + import torch + import torch.utils.data + from tensorflow_metadata.proto.v0 import schema_pb2 + + from ray.data._internal.execution.interfaces import Executor, NodeIdStr + from ray.data.grouped_data import GroupedData + + +logger = logging.getLogger(__name__) + +TensorflowFeatureTypeSpec = Union[ + "tf.TypeSpec", List["tf.TypeSpec"], Dict[str, "tf.TypeSpec"] +] + +TensorFlowTensorBatchType = Union["tf.Tensor", Dict[str, "tf.Tensor"]] + +CollatedData = TypeVar("CollatedData") +TorchBatchType = Union[Dict[str, "torch.Tensor"], CollatedData] + +BT_API_GROUP = "Basic Transformations" +SSR_API_GROUP = "Sorting, Shuffling and Repartitioning" +SMJ_API_GROUP = "Splitting, Merging, Joining datasets" +GGA_API_GROUP = "Grouped and Global aggregations" +CD_API_GROUP = "Consuming Data" +IOC_API_GROUP = "I/O and Conversion" +IM_API_GROUP = "Inspecting Metadata" +E_API_GROUP = "Execution" + + +@PublicAPI +class Dataset: + """A Dataset is a distributed data collection for data loading and processing. + + Datasets are distributed pipelines that produce ``ObjectRef[Block]`` outputs, + where each block holds data in Arrow format, representing a shard of the overall + data collection. The block also determines the unit of parallelism. For more + details, see :ref:`Ray Data Key Concepts `. + + Datasets can be created in multiple ways: + + * from external storage systems such as local disk, S3, HDFS etc. via the ``read_*()`` APIs. + * from existing memory data via ``from_*()`` APIs + * from synthetic data via ``range_*()`` APIs + + The (potentially processed) Dataset can be saved back to external storage systems + via the ``write_*()`` APIs. + + Examples: + .. testcode:: + :skipif: True + + import ray + # Create dataset from synthetic data. + ds = ray.data.range(1000) + # Create dataset from in-memory data. + ds = ray.data.from_items( + [{"col1": i, "col2": i * 2} for i in range(1000)] + ) + # Create dataset from external storage system. + ds = ray.data.read_parquet("s3://bucket/path") + # Save dataset back to external storage system. + ds.write_csv("s3://bucket/output") + + Dataset has two kinds of operations: transformation, which takes in Dataset + and outputs a new Dataset (e.g. :py:meth:`.map_batches()`); and consumption, + which produces values (not a data stream) as output + (e.g. :meth:`.iter_batches()`). + + Dataset transformations are lazy, with execution of the transformations being + triggered by downstream consumption. + + Dataset supports parallel processing at scale: + + * transformations such as :py:meth:`.map_batches()` + * aggregations such as :py:meth:`.min()`/:py:meth:`.max()`/:py:meth:`.mean()`, + * grouping via :py:meth:`.groupby()`, + * shuffling operations such as :py:meth:`.sort()`, :py:meth:`.random_shuffle()`, and :py:meth:`.repartition()` + * joining via :py:meth:`.join()` + + Examples: + >>> import ray + >>> ds = ray.data.range(1000) + >>> # Transform batches (Dict[str, np.ndarray]) with map_batches(). + >>> ds.map_batches(lambda batch: {"id": batch["id"] * 2}) # doctest: +ELLIPSIS + MapBatches() + +- Dataset(num_rows=1000, schema={id: int64}) + >>> # Compute the maximum. + >>> ds.max("id") + 999 + >>> # Shuffle this dataset randomly. + >>> ds.random_shuffle() # doctest: +ELLIPSIS + RandomShuffle + +- Dataset(num_rows=1000, schema={id: int64}) + >>> # Sort it back in order. + >>> ds.sort("id") # doctest: +ELLIPSIS + Sort + +- Dataset(num_rows=1000, schema={id: int64}) + + Both unexecuted and materialized Datasets can be passed between Ray tasks and + actors without incurring a copy. Dataset supports conversion to/from several + more featureful dataframe libraries (e.g., Spark, Dask, Modin, MARS), and are also + compatible with distributed TensorFlow / PyTorch. + """ + + def __init__( + self, + plan: ExecutionPlan, + logical_plan: LogicalPlan, + ): + """Construct a Dataset (internal API). + + The constructor is not part of the Dataset API. Use the ``ray.data.*`` + read methods to construct a dataset. + """ + assert isinstance(plan, ExecutionPlan), type(plan) + usage_lib.record_library_usage("dataset") # Legacy telemetry name. + + self._plan = plan + self._logical_plan = logical_plan + self._plan.link_logical_plan(logical_plan) + + # Handle to currently running executor for this dataset. + self._current_executor: Optional["Executor"] = None + self._write_ds = None + + self._set_uuid(StatsManager.get_dataset_id_from_stats_actor()) + + @staticmethod + def copy( + ds: "Dataset", _deep_copy: bool = False, _as: Optional[type] = None + ) -> "Dataset": + if not _as: + _as = type(ds) + if _deep_copy: + return _as(ds._plan.deep_copy(), ds._logical_plan) + else: + return _as(ds._plan.copy(), ds._logical_plan) + + @PublicAPI(api_group=BT_API_GROUP) + def map( + self, + fn: UserDefinedFunction[Dict[str, Any], Dict[str, Any]], + *, + compute: Optional[ComputeStrategy] = None, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + num_cpus: Optional[float] = None, + num_gpus: Optional[float] = None, + memory: Optional[float] = None, + concurrency: Optional[Union[int, Tuple[int, int]]] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + **ray_remote_args, + ) -> "Dataset": + """Apply the given function to each row of this dataset. + + Use this method to transform your data. To learn more, see + :ref:`Transforming rows `. + + You can use either a function or a callable class to perform the transformation. + For functions, Ray Data uses stateless Ray tasks. For classes, Ray Data uses + stateful Ray actors. For more information, see + :ref:`Stateful Transforms `. + + .. tip:: + + If your transformation is vectorized like most NumPy or pandas operations, + :meth:`~Dataset.map_batches` might be faster. + + .. warning:: + Specifying both ``num_cpus`` and ``num_gpus`` for map tasks is experimental, + and may result in scheduling or stability issues. Please + `report any issues `_ + to the Ray team. + + Examples: + + .. testcode:: + + import os + from typing import Any, Dict + import ray + + def parse_filename(row: Dict[str, Any]) -> Dict[str, Any]: + row["filename"] = os.path.basename(row["path"]) + return row + + ds = ( + ray.data.read_images("s3://anonymous@ray-example-data/image-datasets/simple", include_paths=True) + .map(parse_filename) + ) + print(ds.schema()) + + .. testoutput:: + + Column Type + ------ ---- + image numpy.ndarray(shape=(32, 32, 3), dtype=uint8) + path string + filename string + + Time complexity: O(dataset size / parallelism) + + Args: + fn: The function to apply to each row, or a class type + that can be instantiated to create such a callable. + compute: This argument is deprecated. Use ``concurrency`` argument. + fn_args: Positional arguments to pass to ``fn`` after the first argument. + These arguments are top-level arguments to the underlying Ray task. + fn_kwargs: Keyword arguments to pass to ``fn``. These arguments are + top-level arguments to the underlying Ray task. + fn_constructor_args: Positional arguments to pass to ``fn``'s constructor. + You can only provide this if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + fn_constructor_kwargs: Keyword arguments to pass to ``fn``'s constructor. + This can only be provided if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + num_cpus: The number of CPUs to reserve for each parallel map worker. + num_gpus: The number of GPUs to reserve for each parallel map worker. For + example, specify `num_gpus=1` to request 1 GPU for each parallel map + worker. + memory: The heap memory in bytes to reserve for each parallel map worker. + concurrency: The semantics of this argument depend on the type of ``fn``: + + * If ``fn`` is a function and ``concurrency`` isn't set (default), the + actual concurrency is implicitly determined by the available + resources and number of input blocks. + + * If ``fn`` is a function and ``concurrency`` is an int ``n``, Ray Data + launches *at most* ``n`` concurrent tasks. + + * If ``fn`` is a class and ``concurrency`` is an int ``n``, Ray Data + uses an actor pool with *exactly* ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` is a tuple ``(m, n)``, Ray + Data uses an autoscaling actor pool from ``m`` to ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` isn't set (default), this + method raises an error. + + ray_remote_args_fn: A function that returns a dictionary of remote args + passed to each map worker. The purpose of this argument is to generate + dynamic arguments for each actor/task, and will be called each time prior + to initializing the worker. Args returned from this dict will always + override the args in ``ray_remote_args``. Note: this is an advanced, + experimental feature. + ray_remote_args: Additional resource requirements to request from + Ray for each map worker. See :func:`ray.remote` for details. + + .. seealso:: + + :meth:`~Dataset.flat_map` + Call this method to create new rows from existing ones. Unlike + :meth:`~Dataset.map`, a function passed to + :meth:`~Dataset.flat_map` can return multiple rows. + + :meth:`~Dataset.map_batches` + Call this method to transform batches of data. + """ # noqa: E501 + compute = get_compute_strategy( + fn, + fn_constructor_args=fn_constructor_args, + compute=compute, + concurrency=concurrency, + ) + + if num_cpus is not None: + ray_remote_args["num_cpus"] = num_cpus + + if num_gpus is not None: + ray_remote_args["num_gpus"] = num_gpus + + if memory is not None: + ray_remote_args["memory"] = memory + + plan = self._plan.copy() + map_op = MapRows( + self._logical_plan.dag, + fn, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + logical_plan = LogicalPlan(map_op, self.context) + return Dataset(plan, logical_plan) + + @Deprecated(message="Use set_name() instead", warning=True) + def _set_name(self, name: Optional[str]): + self.set_name(name) + + def set_name(self, name: Optional[str]): + """Set the name of the dataset. + + Used as a prefix for metrics tags. + """ + self._plan._dataset_name = name + + @property + @Deprecated(message="Use name() instead", warning=True) + def _name(self) -> Optional[str]: + return self.name + + @property + def name(self) -> Optional[str]: + """Returns the user-defined dataset name""" + return self._plan._dataset_name + + def get_dataset_id(self) -> str: + """Unique ID of the dataset, including the dataset name, + UUID, and current execution index. + """ + return self._plan.get_dataset_id() + + @PublicAPI(api_group=BT_API_GROUP) + def map_batches( + self, + fn: UserDefinedFunction[DataBatch, DataBatch], + *, + batch_size: Union[int, None, Literal["default"]] = None, + compute: Optional[ComputeStrategy] = None, + batch_format: Optional[str] = "default", + zero_copy_batch: bool = False, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + num_cpus: Optional[float] = None, + num_gpus: Optional[float] = None, + memory: Optional[float] = None, + concurrency: Optional[Union[int, Tuple[int, int]]] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + **ray_remote_args, + ) -> "Dataset": + """Apply the given function to batches of data. + + This method is useful for preprocessing data and performing inference. To learn + more, see :ref:`Transforming batches `. + + You can use either a function or a callable class to perform the transformation. + For functions, Ray Data uses stateless Ray tasks. For classes, Ray Data uses + stateful Ray actors. For more information, see + :ref:`Stateful Transforms `. + + .. tip:: + To understand the format of the input to ``fn``, call :meth:`~Dataset.take_batch` + on the dataset to get a batch in the same format as will be passed to ``fn``. + + .. tip:: + If ``fn`` doesn't mutate its input, set ``zero_copy_batch=True`` to improve + performance and decrease memory utilization. + + .. warning:: + Specifying both ``num_cpus`` and ``num_gpus`` for map tasks is experimental, + and may result in scheduling or stability issues. Please + `report any issues `_ + to the Ray team. + + Examples: + + Call :meth:`~Dataset.map_batches` to transform your data. + + .. testcode:: + + from typing import Dict + import numpy as np + import ray + + def add_dog_years(batch: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]: + batch["age_in_dog_years"] = 7 * batch["age"] + return batch + + ds = ( + ray.data.from_items([ + {"name": "Luna", "age": 4}, + {"name": "Rory", "age": 14}, + {"name": "Scout", "age": 9}, + ]) + .map_batches(add_dog_years) + ) + ds.show() + + .. testoutput:: + + {'name': 'Luna', 'age': 4, 'age_in_dog_years': 28} + {'name': 'Rory', 'age': 14, 'age_in_dog_years': 98} + {'name': 'Scout', 'age': 9, 'age_in_dog_years': 63} + + If your function returns large objects, yield outputs in chunks. + + .. testcode:: + + from typing import Dict + import ray + import numpy as np + + def map_fn_with_large_output(batch: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]: + for i in range(3): + yield {"large_output": np.ones((100, 1000))} + + ds = ( + ray.data.from_items([1]) + .map_batches(map_fn_with_large_output) + ) + + If you require stateful transfomation, + use Python callable class. Here is an example showing how to use stateful transforms to create model inference workers, without having to reload the model on each call. + + .. testcode:: + + from typing import Dict + import numpy as np + import torch + import ray + + class TorchPredictor: + + def __init__(self): + self.model = torch.nn.Identity().cuda() + self.model.eval() + + def __call__(self, batch: Dict[str, np.ndarray]) -> Dict[str, np.ndarray]: + inputs = torch.as_tensor(batch["data"], dtype=torch.float32).cuda() + with torch.inference_mode(): + batch["output"] = self.model(inputs).detach().cpu().numpy() + return batch + + ds = ( + ray.data.from_numpy(np.ones((32, 100))) + .map_batches( + TorchPredictor, + # Two workers with one GPU each + concurrency=2, + # Batch size is required if you're using GPUs. + batch_size=4, + num_gpus=1 + ) + ) + + To learn more, see + :ref:`End-to-end: Offline Batch Inference `. + + Args: + fn: The function or generator to apply to a record batch, or a class type + that can be instantiated to create such a callable. Note ``fn`` must be + pickle-able. + batch_size: The desired number of rows in each batch, or ``None`` to use + entire blocks as batches (blocks may contain different numbers of rows). + The actual size of the batch provided to ``fn`` may be smaller than + ``batch_size`` if ``batch_size`` doesn't evenly divide the block(s) sent + to a given map task. Default ``batch_size`` is ``None``. + compute: This argument is deprecated. Use ``concurrency`` argument. + batch_format: If ``"default"`` or ``"numpy"``, batches are + ``Dict[str, numpy.ndarray]``. If ``"pandas"``, batches are + ``pandas.DataFrame``. If ``"pyarrow"``, batches are + ``pyarrow.Table``. + zero_copy_batch: Whether ``fn`` should be provided zero-copy, read-only + batches. If this is ``True`` and no copy is required for the + ``batch_format`` conversion, the batch is a zero-copy, read-only + view on data in Ray's object store, which can decrease memory + utilization and improve performance. If this is ``False``, the batch + is writable, which requires an extra copy to guarantee. + If ``fn`` mutates its input, this needs to be ``False`` in order to + avoid "assignment destination is read-only" or "buffer source array is + read-only" errors. Default is ``False``. + fn_args: Positional arguments to pass to ``fn`` after the first argument. + These arguments are top-level arguments to the underlying Ray task. + fn_kwargs: Keyword arguments to pass to ``fn``. These arguments are + top-level arguments to the underlying Ray task. + fn_constructor_args: Positional arguments to pass to ``fn``'s constructor. + You can only provide this if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + fn_constructor_kwargs: Keyword arguments to pass to ``fn``'s constructor. + This can only be provided if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + num_cpus: The number of CPUs to reserve for each parallel map worker. + num_gpus: The number of GPUs to reserve for each parallel map worker. For + example, specify `num_gpus=1` to request 1 GPU for each parallel map + worker. + memory: The heap memory in bytes to reserve for each parallel map worker. + concurrency: The semantics of this argument depend on the type of ``fn``: + + * If ``fn`` is a function and ``concurrency`` isn't set (default), the + actual concurrency is implicitly determined by the available + resources and number of input blocks. + + * If ``fn`` is a function and ``concurrency`` is an int ``n``, Ray Data + launches *at most* ``n`` concurrent tasks. + + * If ``fn`` is a class and ``concurrency`` is an int ``n``, Ray Data + uses an actor pool with *exactly* ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` is a tuple ``(m, n)``, Ray + Data uses an autoscaling actor pool from ``m`` to ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` isn't set (default), this + method raises an error. + + ray_remote_args_fn: A function that returns a dictionary of remote args + passed to each map worker. The purpose of this argument is to generate + dynamic arguments for each actor/task, and will be called each time prior + to initializing the worker. Args returned from this dict will always + override the args in ``ray_remote_args``. Note: this is an advanced, + experimental feature. + ray_remote_args: Additional resource requirements to request from + Ray for each map worker. See :func:`ray.remote` for details. + + .. note:: + + The size of the batches provided to ``fn`` might be smaller than the + specified ``batch_size`` if ``batch_size`` doesn't evenly divide the + block(s) sent to a given map task. + + If ``batch_size`` is set and each input block is smaller than the + ``batch_size``, Ray Data will bundle up many blocks as the input for one + task, until their total size is equal to or greater than the given + ``batch_size``. + If ``batch_size`` is not set, the bundling will not be performed. Each task + will receive only one input block. + + .. seealso:: + + :meth:`~Dataset.iter_batches` + Call this function to iterate over batches of data. + + :meth:`~Dataset.take_batch` + Call this function to get a batch of data from the dataset + in the same format as will be passed to the `fn` function of + :meth:`~Dataset.map_batches`. + + :meth:`~Dataset.flat_map` + Call this method to create new records from existing ones. Unlike + :meth:`~Dataset.map`, a function passed to :meth:`~Dataset.flat_map` + can return multiple records. + + :meth:`~Dataset.map` + Call this method to transform one record at time. + + """ # noqa: E501 + use_gpus = num_gpus is not None and num_gpus > 0 + if use_gpus and (batch_size is None or batch_size == "default"): + raise ValueError( + "You must provide `batch_size` to `map_batches` when requesting GPUs. " + "The optimal batch size depends on the model, data, and GPU used. " + "We recommend using the largest batch size that doesn't result " + "in your GPU device running out of memory. You can view the GPU memory " + "usage via the Ray dashboard." + ) + + if isinstance(batch_size, int) and batch_size < 1: + raise ValueError("Batch size can't be negative or 0") + + return self._map_batches_without_batch_size_validation( + fn, + batch_size=batch_size, + compute=compute, + batch_format=batch_format, + zero_copy_batch=zero_copy_batch, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + num_cpus=num_cpus, + num_gpus=num_gpus, + memory=memory, + concurrency=concurrency, + ray_remote_args_fn=ray_remote_args_fn, + **ray_remote_args, + ) + + def _map_batches_without_batch_size_validation( + self, + fn: UserDefinedFunction[DataBatch, DataBatch], + *, + batch_size: Union[int, None, Literal["default"]], + compute: Optional[ComputeStrategy], + batch_format: Optional[str], + zero_copy_batch: bool, + fn_args: Optional[Iterable[Any]], + fn_kwargs: Optional[Dict[str, Any]], + fn_constructor_args: Optional[Iterable[Any]], + fn_constructor_kwargs: Optional[Dict[str, Any]], + num_cpus: Optional[float], + num_gpus: Optional[float], + memory: Optional[float], + concurrency: Optional[Union[int, Tuple[int, int]]], + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]], + **ray_remote_args, + ): + # NOTE: The `map_groups` implementation calls `map_batches` with + # `batch_size=None`. The issue is that if you request GPUs with + # `batch_size=None`, then `map_batches` raises a value error. So, to allow users + # to call `map_groups` with GPUs, we need a separate method that doesn't + # perform batch size validation. + + if batch_size == "default": + warnings.warn( + "Passing 'default' to `map_batches` is deprecated and won't be " + "supported after September 2025. Use `batch_size=None` instead.", + DeprecationWarning, + ) + batch_size = None + + compute = get_compute_strategy( + fn, + fn_constructor_args=fn_constructor_args, + compute=compute, + concurrency=concurrency, + ) + + if num_cpus is not None: + ray_remote_args["num_cpus"] = num_cpus + + if num_gpus is not None: + ray_remote_args["num_gpus"] = num_gpus + + if memory is not None: + ray_remote_args["memory"] = memory + + batch_format = _apply_batch_format(batch_format) + if batch_format not in VALID_BATCH_FORMATS: + raise ValueError( + f"The batch format must be one of {VALID_BATCH_FORMATS}, got: " + f"{batch_format}" + ) + + plan = self._plan.copy() + map_batches_op = MapBatches( + self._logical_plan.dag, + fn, + batch_size=batch_size, + batch_format=batch_format, + zero_copy_batch=zero_copy_batch, + min_rows_per_bundled_input=batch_size, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + logical_plan = LogicalPlan(map_batches_op, self.context) + return Dataset(plan, logical_plan) + + @PublicAPI(api_group=BT_API_GROUP) + def add_column( + self, + col: str, + fn: Callable[ + [DataBatch], + DataBatchColumn, + ], + *, + batch_format: Optional[str] = "pandas", + compute: Optional[str] = None, + concurrency: Optional[int] = None, + **ray_remote_args, + ) -> "Dataset": + """Add the given column to the dataset. + + A function generating the new column values given the batch in pyarrow or pandas + format must be specified. This function must operate on batches of + `batch_format`. + + Examples: + + + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.schema() + Column Type + ------ ---- + id int64 + + Add a new column equal to ``id * 2``. + + >>> ds.add_column("new_id", lambda df: df["id"] * 2).schema() + Column Type + ------ ---- + id int64 + new_id int64 + + Time complexity: O(dataset size / parallelism) + + Args: + col: Name of the column to add. If the name already exists, the + column is overwritten. + fn: Map function generating the column values given a batch of + records in pandas format. + batch_format: If ``"default"`` or ``"numpy"``, batches are + ``Dict[str, numpy.ndarray]``. If ``"pandas"``, batches are + ``pandas.DataFrame``. If ``"pyarrow"``, batches are + ``pyarrow.Table``. If ``"numpy"``, batches are + ``Dict[str, numpy.ndarray]``. + compute: This argument is deprecated. Use ``concurrency`` argument. + concurrency: The maximum number of Ray workers to use concurrently. + ray_remote_args: Additional resource requirements to request from + Ray (e.g., num_gpus=1 to request GPUs for the map tasks). See + :func:`ray.remote` for details. + """ + # Check that batch_format + accepted_batch_formats = ["pandas", "pyarrow", "numpy"] + if batch_format not in accepted_batch_formats: + raise ValueError( + f"batch_format argument must be on of {accepted_batch_formats}, " + f"got: {batch_format}" + ) + + def add_column(batch: DataBatch) -> DataBatch: + column = fn(batch) + if batch_format == "pandas": + import pandas as pd + + # The index of the column must be set + # to align with the index of the batch. + if ( + isinstance(column, pd.Series) + or isinstance(column, pd.DataFrame) + or isinstance(column, pd.Index) + ): + column.index = batch.index + batch.loc[:, col] = column + return batch + elif batch_format == "pyarrow": + import pyarrow as pa + + assert isinstance(column, (pa.Array, pa.ChunkedArray)), ( + f"For pyarrow batch format, the function must return a pyarrow " + f"Array, got: {type(column)}" + ) + # Historically, this method was written for pandas batch format. + # To resolve https://github.com/ray-project/ray/issues/48090, + # we also allow pyarrow batch format which is preferred but would be + # a breaking change to enforce. + + # For pyarrow, the index of the column will be -1 if it is missing in + # which case we'll want to append it + column_idx = batch.schema.get_field_index(col) + if column_idx == -1: + return batch.append_column(col, column) + else: + return batch.set_column(column_idx, col, column) + + else: + # batch format is assumed to be numpy since we checked at the + # beginning of the add_column function + assert isinstance(column, np.ndarray), ( + f"For numpy batch format, the function must return a " + f"numpy.ndarray, got: {type(column)}" + ) + batch[col] = column + return batch + + if not callable(fn): + raise ValueError("`fn` must be callable, got {}".format(fn)) + + return self.map_batches( + add_column, + batch_format=batch_format, + compute=compute, + concurrency=concurrency, + zero_copy_batch=False, + **ray_remote_args, + ) + + @PublicAPI(api_group=BT_API_GROUP) + def drop_columns( + self, + cols: List[str], + *, + compute: Optional[str] = None, + concurrency: Optional[int] = None, + **ray_remote_args, + ) -> "Dataset": + """Drop one or more columns from the dataset. + + Examples: + + >>> import ray + >>> ds = ray.data.read_parquet("s3://anonymous@ray-example-data/iris.parquet") + >>> ds.schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + petal.length double + petal.width double + variety string + >>> ds.drop_columns(["variety"]).schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + petal.length double + petal.width double + + Time complexity: O(dataset size / parallelism) + + Args: + cols: Names of the columns to drop. If any name does not exist, + an exception is raised. Column names must be unique. + compute: This argument is deprecated. Use ``concurrency`` argument. + concurrency: The maximum number of Ray workers to use concurrently. + ray_remote_args: Additional resource requirements to request from + Ray (e.g., num_gpus=1 to request GPUs for the map tasks). See + :func:`ray.remote` for details. + """ # noqa: E501 + + if len(cols) != len(set(cols)): + raise ValueError(f"drop_columns expects unique column names, got: {cols}") + + def drop_columns(batch): + return batch.drop(cols) + + return self.map_batches( + drop_columns, + batch_format="pyarrow", + zero_copy_batch=True, + compute=compute, + concurrency=concurrency, + **ray_remote_args, + ) + + @PublicAPI(api_group=BT_API_GROUP) + def select_columns( + self, + cols: Union[str, List[str]], + *, + compute: Union[str, ComputeStrategy] = None, + concurrency: Optional[int] = None, + **ray_remote_args, + ) -> "Dataset": + """Select one or more columns from the dataset. + + Specified columns must be in the dataset schema. + + .. tip:: + If you're reading parquet files with :meth:`ray.data.read_parquet`, + you might be able to speed it up by using projection pushdown; see + :ref:`Parquet column pruning ` for details. + + Examples: + + >>> import ray + >>> ds = ray.data.read_parquet("s3://anonymous@ray-example-data/iris.parquet") + >>> ds.schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + petal.length double + petal.width double + variety string + >>> ds.select_columns(["sepal.length", "sepal.width"]).schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + + Time complexity: O(dataset size / parallelism) + + Args: + cols: Names of the columns to select. If a name isn't in the + dataset schema, an exception is raised. Columns also should be unique. + compute: This argument is deprecated. Use ``concurrency`` argument. + concurrency: The maximum number of Ray workers to use concurrently. + ray_remote_args: Additional resource requirements to request from + Ray (e.g., num_gpus=1 to request GPUs for the map tasks). See + :func:`ray.remote` for details. + """ # noqa: E501 + if isinstance(cols, str): + cols = [cols] + elif isinstance(cols, list): + if not all(isinstance(col, str) for col in cols): + raise ValueError( + "select_columns requires all elements of 'cols' to be strings." + ) + else: + raise TypeError( + "select_columns requires 'cols' to be a string or a list of strings." + ) + + if not cols: + raise ValueError("select_columns requires at least one column to select.") + + if len(cols) != len(set(cols)): + raise ValueError( + "select_columns expected unique column names, " + f"got duplicate column names: {cols}" + ) + + # Don't feel like we really need this + from ray.data._internal.compute import TaskPoolStrategy + + compute = TaskPoolStrategy(size=concurrency) + + plan = self._plan.copy() + select_op = Project( + self._logical_plan.dag, + cols=cols, + cols_rename=None, + compute=compute, + ray_remote_args=ray_remote_args, + ) + logical_plan = LogicalPlan(select_op, self.context) + return Dataset(plan, logical_plan) + + @PublicAPI(api_group=BT_API_GROUP) + def rename_columns( + self, + names: Union[List[str], Dict[str, str]], + *, + concurrency: Optional[Union[int, Tuple[int, int]]] = None, + **ray_remote_args, + ): + """Rename columns in the dataset. + + Examples: + + >>> import ray + >>> ds = ray.data.read_parquet("s3://anonymous@ray-example-data/iris.parquet") + >>> ds.schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + petal.length double + petal.width double + variety string + + You can pass a dictionary mapping old column names to new column names. + + >>> ds.rename_columns({"variety": "category"}).schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + petal.length double + petal.width double + category string + + Or you can pass a list of new column names. + + >>> ds.rename_columns( + ... ["sepal_length", "sepal_width", "petal_length", "petal_width", "variety"] + ... ).schema() + Column Type + ------ ---- + sepal_length double + sepal_width double + petal_length double + petal_width double + variety string + + Args: + names: A dictionary that maps old column names to new column names, or a + list of new column names. + concurrency: The maximum number of Ray workers to use concurrently. + ray_remote_args: Additional resource requirements to request from + Ray (e.g., num_gpus=1 to request GPUs for the map tasks). See + :func:`ray.remote` for details. + """ # noqa: E501 + + if isinstance(names, dict): + if not names: + raise ValueError("rename_columns received 'names' with no entries.") + + if len(names.values()) != len(set(names.values())): + raise ValueError( + f"rename_columns received duplicate values in the 'names': {names}" + ) + + if not all( + isinstance(k, str) and isinstance(v, str) for k, v in names.items() + ): + raise ValueError( + "rename_columns requires both keys and values in the 'names' " + "to be strings." + ) + + cols_rename = names + elif isinstance(names, list): + if not names: + raise ValueError( + "rename_columns requires 'names' with at least one column name." + ) + + if len(names) != len(set(names)): + raise ValueError( + f"rename_columns received duplicate values in the 'names': {names}" + ) + + if not all(isinstance(col, str) for col in names): + raise ValueError( + "rename_columns requires all elements in the 'names' to be strings." + ) + + current_names = self.schema().names + if len(current_names) != len(names): + raise ValueError( + f"rename_columns requires 'names': {names} length match current " + f"schema names: {current_names}." + ) + + cols_rename = dict(zip(current_names, names)) + else: + raise TypeError( + f"rename_columns expected names to be either List[str] or " + f"Dict[str, str], got {type(names)}." + ) + + if concurrency is not None and not isinstance(concurrency, int): + raise ValueError( + f"Expected `concurrency` to be an integer or `None`, but " + f"got {concurrency}." + ) + + # Construct the plan and project operation + from ray.data._internal.compute import TaskPoolStrategy + + compute = TaskPoolStrategy(size=concurrency) + + plan = self._plan.copy() + select_op = Project( + self._logical_plan.dag, + cols=None, + cols_rename=cols_rename, + compute=compute, + ray_remote_args=ray_remote_args, + ) + logical_plan = LogicalPlan(select_op, self.context) + return Dataset(plan, logical_plan) + + @PublicAPI(api_group=BT_API_GROUP) + def flat_map( + self, + fn: UserDefinedFunction[Dict[str, Any], List[Dict[str, Any]]], + *, + compute: Optional[ComputeStrategy] = None, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + num_cpus: Optional[float] = None, + num_gpus: Optional[float] = None, + memory: Optional[float] = None, + concurrency: Optional[Union[int, Tuple[int, int]]] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + **ray_remote_args, + ) -> "Dataset": + """Apply the given function to each row and then flatten results. + + Use this method if your transformation returns multiple rows for each input + row. + + You can use either a function or a callable class to perform the transformation. + For functions, Ray Data uses stateless Ray tasks. For classes, Ray Data uses + stateful Ray actors. For more information, see + :ref:`Stateful Transforms `. + + .. tip:: + :meth:`~Dataset.map_batches` can also modify the number of rows. If your + transformation is vectorized like most NumPy and pandas operations, + it might be faster. + + .. warning:: + Specifying both ``num_cpus`` and ``num_gpus`` for map tasks is experimental, + and may result in scheduling or stability issues. Please + `report any issues `_ + to the Ray team. + + Examples: + + .. testcode:: + + from typing import Any, Dict, List + import ray + + def duplicate_row(row: Dict[str, Any]) -> List[Dict[str, Any]]: + return [row] * 2 + + print( + ray.data.range(3) + .flat_map(duplicate_row) + .take_all() + ) + + .. testoutput:: + + [{'id': 0}, {'id': 0}, {'id': 1}, {'id': 1}, {'id': 2}, {'id': 2}] + + Time complexity: O(dataset size / parallelism) + + Args: + fn: The function or generator to apply to each record, or a class type + that can be instantiated to create such a callable. + compute: This argument is deprecated. Use ``concurrency`` argument. + fn_args: Positional arguments to pass to ``fn`` after the first argument. + These arguments are top-level arguments to the underlying Ray task. + fn_kwargs: Keyword arguments to pass to ``fn``. These arguments are + top-level arguments to the underlying Ray task. + fn_constructor_args: Positional arguments to pass to ``fn``'s constructor. + You can only provide this if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + fn_constructor_kwargs: Keyword arguments to pass to ``fn``'s constructor. + This can only be provided if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + num_cpus: The number of CPUs to reserve for each parallel map worker. + num_gpus: The number of GPUs to reserve for each parallel map worker. For + example, specify `num_gpus=1` to request 1 GPU for each parallel map + worker. + memory: The heap memory in bytes to reserve for each parallel map worker. + concurrency: The semantics of this argument depend on the type of ``fn``: + + * If ``fn`` is a function and ``concurrency`` isn't set (default), the + actual concurrency is implicitly determined by the available + resources and number of input blocks. + + * If ``fn`` is a function and ``concurrency`` is an int ``n``, Ray Data + launches *at most* ``n`` concurrent tasks. + + * If ``fn`` is a class and ``concurrency`` is an int ``n``, Ray Data + uses an actor pool with *exactly* ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` is a tuple ``(m, n)``, Ray + Data uses an autoscaling actor pool from ``m`` to ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` isn't set (default), this + method raises an error. + + ray_remote_args_fn: A function that returns a dictionary of remote args + passed to each map worker. The purpose of this argument is to generate + dynamic arguments for each actor/task, and will be called each time + prior to initializing the worker. Args returned from this dict will + always override the args in ``ray_remote_args``. Note: this is an + advanced, experimental feature. + ray_remote_args: Additional resource requirements to request from + Ray for each map worker. See :func:`ray.remote` for details. + + .. seealso:: + + :meth:`~Dataset.map_batches` + Call this method to transform batches of data. + + :meth:`~Dataset.map` + Call this method to transform one row at time. + """ + compute = get_compute_strategy( + fn, + fn_constructor_args=fn_constructor_args, + compute=compute, + concurrency=concurrency, + ) + + if num_cpus is not None: + ray_remote_args["num_cpus"] = num_cpus + + if num_gpus is not None: + ray_remote_args["num_gpus"] = num_gpus + + if memory is not None: + ray_remote_args["memory"] = memory + + plan = self._plan.copy() + op = FlatMap( + input_op=self._logical_plan.dag, + fn=fn, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @PublicAPI(api_group=BT_API_GROUP) + def filter( + self, + fn: Optional[UserDefinedFunction[Dict[str, Any], bool]] = None, + expr: Optional[str] = None, + *, + compute: Union[str, ComputeStrategy] = None, + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + concurrency: Optional[Union[int, Tuple[int, int]]] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + **ray_remote_args, + ) -> "Dataset": + """Filter out rows that don't satisfy the given predicate. + + You can use either a function or a callable class or an expression string to + perform the transformation. + For functions, Ray Data uses stateless Ray tasks. For classes, Ray Data uses + stateful Ray actors. For more information, see + :ref:`Stateful Transforms `. + + .. tip:: + If you use the `expr` parameter with a Python expression string, Ray Data + optimizes your filter with native Arrow interfaces. + + Examples: + + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.filter(expr="id <= 4").take_all() + [{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}] + + Time complexity: O(dataset size / parallelism) + + Args: + fn: The predicate to apply to each row, or a class type + that can be instantiated to create such a callable. + expr: An expression string needs to be a valid Python expression that + will be converted to ``pyarrow.dataset.Expression`` type. + fn_args: Positional arguments to pass to ``fn`` after the first argument. + These arguments are top-level arguments to the underlying Ray task. + fn_kwargs: Keyword arguments to pass to ``fn``. These arguments are + top-level arguments to the underlying Ray task. + fn_constructor_args: Positional arguments to pass to ``fn``'s constructor. + You can only provide this if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + fn_constructor_kwargs: Keyword arguments to pass to ``fn``'s constructor. + This can only be provided if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + compute: This argument is deprecated. Use ``concurrency`` argument. + concurrency: The semantics of this argument depend on the type of ``fn``: + + * If ``fn`` is a function and ``concurrency`` isn't set (default), the + actual concurrency is implicitly determined by the available + resources and number of input blocks. + + * If ``fn`` is a function and ``concurrency`` is an int ``n``, Ray Data + launches *at most* ``n`` concurrent tasks. + + * If ``fn`` is a class and ``concurrency`` is an int ``n``, Ray Data + uses an actor pool with *exactly* ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` is a tuple ``(m, n)``, Ray + Data uses an autoscaling actor pool from ``m`` to ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` isn't set (default), this + method raises an error. + + ray_remote_args_fn: A function that returns a dictionary of remote args + passed to each map worker. The purpose of this argument is to generate + dynamic arguments for each actor/task, and will be called each time + prior to initializing the worker. Args returned from this dict will + always override the args in ``ray_remote_args``. Note: this is an + advanced, experimental feature. + ray_remote_args: Additional resource requirements to request from + Ray (e.g., num_gpus=1 to request GPUs for the map tasks). See + :func:`ray.remote` for details. + """ + # Ensure exactly one of fn or expr is provided + resolved_expr = None + if not ((fn is None) ^ (expr is None)): + raise ValueError("Exactly one of 'fn' or 'expr' must be provided.") + elif expr is not None: + if ( + fn_args is not None + or fn_kwargs is not None + or fn_constructor_args is not None + or fn_constructor_kwargs is not None + ): + raise ValueError( + "when 'expr' is used, 'fn_args/fn_kwargs' or 'fn_constructor_args/fn_constructor_kwargs' can not be used." + ) + from ray.data._internal.compute import TaskPoolStrategy + from ray.data._internal.planner.plan_expression.expression_evaluator import ( # noqa: E501 + ExpressionEvaluator, + ) + + # TODO: (srinathk) bind the expression to the actual schema. + # If fn is a string, convert it to a pyarrow.dataset.Expression + # Initialize ExpressionEvaluator with valid columns, if available + resolved_expr = ExpressionEvaluator.get_filters(expression=expr) + + compute = TaskPoolStrategy(size=concurrency) + else: + warnings.warn( + "Use 'expr' instead of 'fn' when possible for performant filters." + ) + + if callable(fn): + compute = get_compute_strategy( + fn=fn, + fn_constructor_args=fn_constructor_args, + compute=compute, + concurrency=concurrency, + ) + else: + raise ValueError( + f"fn must be a UserDefinedFunction, but got " + f"{type(fn).__name__} instead." + ) + + plan = self._plan.copy() + op = Filter( + input_op=self._logical_plan.dag, + fn=fn, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + filter_expr=resolved_expr, + compute=compute, + ray_remote_args_fn=ray_remote_args_fn, + ray_remote_args=ray_remote_args, + ) + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @AllToAllAPI + @PublicAPI(api_group=SSR_API_GROUP) + def repartition( + self, + num_blocks: Optional[int] = None, + target_num_rows_per_block: Optional[int] = None, + *, + shuffle: bool = False, + keys: Optional[List[str]] = None, + sort: bool = False, + ) -> "Dataset": + """Repartition the :class:`Dataset` into exactly this number of + :ref:`blocks `. + + This method can be useful to tune the performance of your pipeline. To learn + more, see :ref:`Advanced: Performance Tips and Tuning `. + + If you're writing data to files, you can also use this method to change the + number of output files. To learn more, see + :ref:`Changing the number of output files `. + + .. note:: + + Repartition has two modes. If ``shuffle=False``, Ray Data performs the + minimal data movement needed to equalize block sizes. Otherwise, Ray Data + performs a full distributed shuffle. + + .. image:: /data/images/dataset-shuffle.svg + :align: center + + .. + https://docs.google.com/drawings/d/132jhE3KXZsf29ho1yUdPrCHB9uheHBWHJhDQMXqIVPA/edit + + Examples: + >>> import ray + >>> ds = ray.data.range(100).repartition(10).materialize() + >>> ds.num_blocks() + 10 + + Time complexity: O(dataset size / parallelism) + + Args: + num_blocks: Number of blocks after repartitioning. + target_num_rows_per_block: [Experimental] The target number of rows per block to + repartition. Note that either `num_blocks` or + `target_num_rows_per_block` must be set, but not both. When + `target_num_rows_per_block` is set, it only repartitions + :class:`Dataset` :ref:`blocks ` that are larger than + `target_num_rows_per_block`. Note that the system will internally + figure out the number of rows per :ref:`blocks ` for + optimal execution, based on the `target_num_rows_per_block`. This is + the current behavior because of the implementation and may change in + the future. + shuffle: Whether to perform a distributed shuffle during the + repartition. When shuffle is enabled, each output block + contains a subset of data rows from each input block, which + requires all-to-all data movement. When shuffle is disabled, + output blocks are created from adjacent input blocks, + minimizing data movement. + keys: List of key columns repartitioning will use to determine which + partition will row belong to after repartitioning (by applying + hash-partitioning algorithm to the whole dataset). Note that, this + config is only relevant when `DataContext.use_hash_based_shuffle` + is set to True. + sort: Whether the blocks should be sorted after repartitioning. Note, + that by default blocks will be sorted in the ascending order. + + Note that you must set either `num_blocks` or `target_num_rows_per_block` + but not both. + Additionally note that this operation materializes the entire dataset in memory + when you set shuffle to True. + + Returns: + The repartitioned :class:`Dataset`. + """ # noqa: E501 + + if target_num_rows_per_block is not None: + if keys is not None: + warnings.warn( + "`keys` is ignored when `target_num_rows_per_block` is set." + ) + if sort is not False: + warnings.warn( + "`sort` is ignored when `target_num_rows_per_block` is set." + ) + if shuffle: + warnings.warn( + "`shuffle` is ignored when `target_num_rows_per_block` is set." + ) + + if (num_blocks is None) and (target_num_rows_per_block is None): + raise ValueError( + "Either `num_blocks` or `target_num_rows_per_block` must be set" + ) + + if (num_blocks is not None) and (target_num_rows_per_block is not None): + raise ValueError( + "Only one of `num_blocks` or `target_num_rows_per_block` must be set, " + "but not both." + ) + + if target_num_rows_per_block is not None and shuffle: + raise ValueError( + "`shuffle` must be False when `target_num_rows_per_block` is set." + ) + + plan = self._plan.copy() + if target_num_rows_per_block is not None: + op = StreamingRepartition( + self._logical_plan.dag, + target_num_rows_per_block=target_num_rows_per_block, + ) + else: + op = Repartition( + self._logical_plan.dag, + num_outputs=num_blocks, + shuffle=shuffle, + keys=keys, + sort=sort, + ) + + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @AllToAllAPI + @PublicAPI(api_group=SSR_API_GROUP) + def random_shuffle( + self, + *, + seed: Optional[int] = None, + num_blocks: Optional[int] = None, + **ray_remote_args, + ) -> "Dataset": + """Randomly shuffle the rows of this :class:`Dataset`. + + .. tip:: + + This method can be slow. For better performance, try + :ref:`Iterating over batches with shuffling `. + Also, see :ref:`Optimizing shuffles `. + + Examples: + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.random_shuffle().take(3) # doctest: +SKIP + {'id': 41}, {'id': 21}, {'id': 92}] + >>> ds.random_shuffle(seed=42).take(3) # doctest: +SKIP + {'id': 77}, {'id': 21}, {'id': 63}] + + Time complexity: O(dataset size / parallelism) + + Args: + seed: Fix the random seed to use, otherwise one is chosen + based on system randomness. + + Returns: + The shuffled :class:`Dataset`. + """ # noqa: E501 + + if num_blocks is not None: + raise DeprecationWarning( + "`num_blocks` parameter is deprecated in Ray 2.9. random_shuffle() " + "does not support to change the number of output blocks. Use " + "repartition() instead.", # noqa: E501 + ) + plan = self._plan.copy() + op = RandomShuffle( + self._logical_plan.dag, + seed=seed, + ray_remote_args=ray_remote_args, + ) + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @AllToAllAPI + @PublicAPI(api_group=SSR_API_GROUP) + def randomize_block_order( + self, + *, + seed: Optional[int] = None, + ) -> "Dataset": + """Randomly shuffle the :ref:`blocks ` of this :class:`Dataset`. + + This method is useful if you :meth:`~Dataset.split` your dataset into shards and + want to randomize the data in each shard without performing a full + :meth:`~Dataset.random_shuffle`. + + Examples: + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.take(5) + [{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}] + >>> ds.randomize_block_order().take(5) # doctest: +SKIP + {'id': 15}, {'id': 16}, {'id': 17}, {'id': 18}, {'id': 19}] + + Args: + seed: Fix the random seed to use, otherwise one is chosen + based on system randomness. + + Returns: + The block-shuffled :class:`Dataset`. + """ # noqa: E501 + + plan = self._plan.copy() + op = RandomizeBlocks( + self._logical_plan.dag, + seed=seed, + ) + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @PublicAPI(api_group=BT_API_GROUP) + def random_sample( + self, fraction: float, *, seed: Optional[int] = None + ) -> "Dataset": + """Returns a new :class:`Dataset` containing a random fraction of the rows. + + .. note:: + + This method returns roughly ``fraction * total_rows`` rows. An exact number + of rows isn't guaranteed. + + Examples: + >>> import ray + >>> ds1 = ray.data.range(100) + >>> ds1.random_sample(0.1).count() # doctest: +SKIP + 10 + >>> ds2 = ray.data.range(1000) + >>> ds2.random_sample(0.123, seed=42).take(2) # doctest: +SKIP + [{'id': 2}, {'id': 9}] + >>> ds2.random_sample(0.123, seed=42).take(2) # doctest: +SKIP + [{'id': 2}, {'id': 9}] + + Args: + fraction: The fraction of elements to sample. + seed: Seeds the python random pRNG generator. + + Returns: + Returns a :class:`Dataset` containing the sampled rows. + """ + import pandas as pd + import pyarrow as pa + + if self._plan.initial_num_blocks() == 0: + raise ValueError("Cannot sample from an empty Dataset.") + + if fraction < 0 or fraction > 1: + raise ValueError("Fraction must be between 0 and 1.") + + from ray.data._internal.execution.interfaces.task_context import TaskContext + + def random_sample(batch: DataBatch, seed: Optional[int]): + ctx = TaskContext.get_current() + + if "rng" in ctx.kwargs: + rng = ctx.kwargs["rng"] + elif seed is None: + rng = np.random.default_rng() + ctx.kwargs["rng"] = rng + else: + rng = np.random.default_rng([ctx.task_idx, seed]) + ctx.kwargs["rng"] = rng + + mask_idx = np.where(rng.random(len(batch)) < fraction)[0] + if isinstance(batch, pa.Table): + return batch.take(mask_idx) + elif isinstance(batch, pd.DataFrame): + return batch.iloc[mask_idx, :] + + raise ValueError(f"Unsupported batch type: {type(batch)}") + + return self.map_batches( + random_sample, + fn_args=[seed], + batch_format=None, + ) + + @ConsumptionAPI + @PublicAPI(api_group=SMJ_API_GROUP) + def streaming_split( + self, + n: int, + *, + equal: bool = False, + locality_hints: Optional[List["NodeIdStr"]] = None, + ) -> List[DataIterator]: + """Returns ``n`` :class:`DataIterators ` that can + be used to read disjoint subsets of the dataset in parallel. + + This method is the recommended way to consume :class:`Datasets ` for + distributed training. + + Streaming split works by delegating the execution of this :class:`Dataset` to a + coordinator actor. The coordinator pulls block references from the executed + stream, and divides those blocks among ``n`` output iterators. Iterators pull + blocks from the coordinator actor to return to their caller on ``next``. + + The returned iterators are also repeatable; each iteration will trigger a + new execution of the Dataset. There is an implicit barrier at the start of + each iteration, which means that `next` must be called on all iterators before + the iteration starts. + + .. warning:: + + Because iterators are pulling blocks from the same :class:`Dataset` + execution, if one iterator falls behind, other iterators may be stalled. + + Examples: + + .. testcode:: + + import ray + + ds = ray.data.range(100) + it1, it2 = ds.streaming_split(2, equal=True) + + Consume data from iterators in parallel. + + .. testcode:: + + @ray.remote + def consume(it): + for batch in it.iter_batches(): + pass + + ray.get([consume.remote(it1), consume.remote(it2)]) + + You can loop over the iterators multiple times (multiple epochs). + + .. testcode:: + + @ray.remote + def train(it): + NUM_EPOCHS = 2 + for _ in range(NUM_EPOCHS): + for batch in it.iter_batches(): + pass + + ray.get([train.remote(it1), train.remote(it2)]) + + The following remote function call blocks waiting for a read on ``it2`` to + start. + + .. testcode:: + :skipif: True + + ray.get(train.remote(it1)) + + Args: + n: Number of output iterators to return. + equal: If ``True``, each output iterator sees an exactly equal number + of rows, dropping data if necessary. If ``False``, some iterators may + see slightly more or less rows than others, but no data is dropped. + locality_hints: Specify the node ids corresponding to each iterator + location. Dataset will try to minimize data movement based on the + iterator output locations. This list must have length ``n``. You can + get the current node id of a task or actor by calling + ``ray.get_runtime_context().get_node_id()``. + + Returns: + The output iterator splits. These iterators are Ray-serializable and can + be freely passed to any Ray task or actor. + + .. seealso:: + + :meth:`Dataset.split` + Unlike :meth:`~Dataset.streaming_split`, :meth:`~Dataset.split` + materializes the dataset in memory. + """ + return StreamSplitDataIterator.create(self, n, equal, locality_hints) + + @ConsumptionAPI + @PublicAPI(api_group=SMJ_API_GROUP) + def split( + self, n: int, *, equal: bool = False, locality_hints: Optional[List[Any]] = None + ) -> List["MaterializedDataset"]: + """Materialize and split the dataset into ``n`` disjoint pieces. + + This method returns a list of ``MaterializedDataset`` that can be passed to Ray + Tasks and Actors and used to read the dataset rows in parallel. + + Examples: + + .. testcode:: + + @ray.remote + class Worker: + + def train(self, data_iterator): + for batch in data_iterator.iter_batches(batch_size=8): + pass + + workers = [Worker.remote() for _ in range(4)] + shards = ray.data.range(100).split(n=4, equal=True) + ray.get([w.train.remote(s) for w, s in zip(workers, shards)]) + + Time complexity: O(1) + + Args: + n: Number of child datasets to return. + equal: Whether to guarantee each split has an equal + number of records. This might drop records if the rows can't be + divided equally among the splits. + locality_hints: [Experimental] A list of Ray actor handles of size ``n``. + The system tries to co-locate the blocks of the i-th dataset + with the i-th actor to maximize data locality. + + Returns: + A list of ``n`` disjoint dataset splits. + + .. seealso:: + + :meth:`Dataset.split_at_indices` + Unlike :meth:`~Dataset.split`, which splits a dataset into approximately + equal splits, :meth:`Dataset.split_proportionately` lets you split a + dataset into different sizes. + + :meth:`Dataset.split_proportionately` + This method is equivalent to :meth:`Dataset.split_at_indices` if + you compute indices manually. + + :meth:`Dataset.streaming_split`. + Unlike :meth:`~Dataset.split`, :meth:`~Dataset.streaming_split` + doesn't materialize the dataset in memory. + """ + if n <= 0: + raise ValueError(f"The number of splits {n} is not positive.") + + # fallback to split_at_indices for equal split without locality hints. + # simple benchmarks shows spilit_at_indices yields more stable performance. + # https://github.com/ray-project/ray/pull/26641 for more context. + if equal and locality_hints is None: + count = self.count() + split_index = count // n + # we are creating n split_indices which will generate + # n + 1 splits; the last split will at most contains (n - 1) + # rows, which could be safely dropped. + split_indices = [split_index * i for i in range(1, n + 1)] + shards = self.split_at_indices(split_indices) + return shards[:n] + + if locality_hints and len(locality_hints) != n: + raise ValueError( + f"The length of locality_hints {len(locality_hints)} " + f"doesn't equal the number of splits {n}." + ) + + bundle: RefBundle = self._plan.execute() + # We should not free blocks since we will materialize the Datasets. + owned_by_consumer = False + stats = self._plan.stats() + block_refs, metadata = zip(*bundle.blocks) + + if locality_hints is None: + block_refs_splits = np.array_split(block_refs, n) + metadata_splits = np.array_split(metadata, n) + + split_datasets = [] + for block_refs_split, metadata_split in zip( + block_refs_splits, metadata_splits + ): + ref_bundles = [ + RefBundle( + [(b, m)], owns_blocks=owned_by_consumer, schema=bundle.schema + ) + for b, m in zip(block_refs_split, metadata_split) + ] + logical_plan = LogicalPlan( + InputData(input_data=ref_bundles), + self.context, + ) + split_datasets.append( + MaterializedDataset( + ExecutionPlan(stats, self.context.copy()), + logical_plan, + ) + ) + return split_datasets + + metadata_mapping = dict(zip(block_refs, metadata)) + + # If the locality_hints is set, we use a two-round greedy algorithm + # to co-locate the blocks with the actors based on block + # and actor's location (node_id). + # + # The split algorithm tries to allocate equally-sized blocks regardless + # of locality. Thus we first calculate the expected number of blocks + # for each split. + # + # In the first round, for each actor, we look for all blocks that + # match the actor's node_id, then allocate those matched blocks to + # this actor until we reach the limit(expected number). + # + # In the second round: fill each actor's allocation with + # remaining unallocated blocks until we reach the limit. + + def build_allocation_size_map( + num_blocks: int, actors: List[Any] + ) -> Dict[Any, int]: + """Given the total number of blocks and a list of actors, calcuate + the expected number of blocks to allocate for each actor. + """ + num_actors = len(actors) + num_blocks_per_actor = num_blocks // num_actors + num_blocks_left = num_blocks - num_blocks_per_actor * n + num_blocks_by_actor = {} + for i, actor in enumerate(actors): + num_blocks_by_actor[actor] = num_blocks_per_actor + if i < num_blocks_left: + num_blocks_by_actor[actor] += 1 + return num_blocks_by_actor + + def build_block_refs_by_node_id( + blocks: List[ObjectRef[Block]], + ) -> Dict[str, List[ObjectRef[Block]]]: + """Build the reverse index from node_id to block_refs. For + simplicity, if the block is stored on multiple nodes we + only pick the first one. + """ + block_ref_locations = ray.experimental.get_object_locations(blocks) + block_refs_by_node_id = collections.defaultdict(list) + for block_ref in blocks: + node_ids = block_ref_locations.get(block_ref, {}).get("node_ids", []) + node_id = node_ids[0] if node_ids else None + block_refs_by_node_id[node_id].append(block_ref) + return block_refs_by_node_id + + def build_node_id_by_actor(actors: List[Any]) -> Dict[Any, str]: + """Build a map from a actor to its node_id.""" + actors_state = ray._private.state.actors() + return { + actor: actors_state.get(actor._actor_id.hex(), {}) + .get("Address", {}) + .get("NodeID") + for actor in actors + } + + # expected number of blocks to be allocated for each actor + expected_block_count_by_actor = build_allocation_size_map( + len(block_refs), locality_hints + ) + # the reverse index from node_id to block_refs + block_refs_by_node_id = build_block_refs_by_node_id(block_refs) + # the map from actor to its node_id + node_id_by_actor = build_node_id_by_actor(locality_hints) + + allocation_per_actor = collections.defaultdict(list) + + # In the first round, for each actor, we look for all blocks that + # match the actor's node_id, then allocate those matched blocks to + # this actor until we reach the limit(expected number) + for actor in locality_hints: + node_id = node_id_by_actor[actor] + matching_blocks = block_refs_by_node_id[node_id] + expected_block_count = expected_block_count_by_actor[actor] + allocation = [] + while matching_blocks and len(allocation) < expected_block_count: + allocation.append(matching_blocks.pop()) + allocation_per_actor[actor] = allocation + + # In the second round: fill each actor's allocation with + # remaining unallocated blocks until we reach the limit + remaining_block_refs = list( + itertools.chain.from_iterable(block_refs_by_node_id.values()) + ) + for actor in locality_hints: + while ( + len(allocation_per_actor[actor]) < expected_block_count_by_actor[actor] + ): + allocation_per_actor[actor].append(remaining_block_refs.pop()) + + assert len(remaining_block_refs) == 0, len(remaining_block_refs) + + per_split_bundles = [] + for actor in locality_hints: + blocks = allocation_per_actor[actor] + metadata = [metadata_mapping[b] for b in blocks] + bundle = RefBundle( + tuple(zip(blocks, metadata)), + owns_blocks=owned_by_consumer, + schema=bundle.schema, + ) + per_split_bundles.append(bundle) + + if equal: + # equalize the splits + per_split_bundles = _equalize(per_split_bundles, owned_by_consumer) + + split_datasets = [] + for bundle in per_split_bundles: + logical_plan = LogicalPlan(InputData(input_data=[bundle]), self.context) + split_datasets.append( + MaterializedDataset( + ExecutionPlan(stats, self.context.copy()), + logical_plan, + ) + ) + return split_datasets + + @ConsumptionAPI + @PublicAPI(api_group=SMJ_API_GROUP) + def split_at_indices(self, indices: List[int]) -> List["MaterializedDataset"]: + """Materialize and split the dataset at the given indices (like ``np.split``). + + Examples: + >>> import ray + >>> ds = ray.data.range(10) + >>> d1, d2, d3 = ds.split_at_indices([2, 5]) + >>> d1.take_batch() + {'id': array([0, 1])} + >>> d2.take_batch() + {'id': array([2, 3, 4])} + >>> d3.take_batch() + {'id': array([5, 6, 7, 8, 9])} + + Time complexity: O(num splits) + + Args: + indices: List of sorted integers which indicate where the dataset + are split. If an index exceeds the length of the dataset, + an empty dataset is returned. + + Returns: + The dataset splits. + + .. seealso:: + + :meth:`Dataset.split` + Unlike :meth:`~Dataset.split_at_indices`, which lets you split a + dataset into different sizes, :meth:`Dataset.split` splits a dataset + into approximately equal splits. + + :meth:`Dataset.split_proportionately` + This method is equivalent to :meth:`Dataset.split_at_indices` if + you compute indices manually. + + :meth:`Dataset.streaming_split`. + Unlike :meth:`~Dataset.split`, :meth:`~Dataset.streaming_split` + doesn't materialize the dataset in memory. + """ + + if len(indices) < 1: + raise ValueError("indices must be at least of length 1") + if sorted(indices) != indices: + raise ValueError("indices must be sorted") + if indices[0] < 0: + raise ValueError("indices must be positive") + start_time = time.perf_counter() + bundle: RefBundle = self._plan.execute() + blocks, metadata = _split_at_indices( + bundle.blocks, + indices, + False, + ) + split_duration = time.perf_counter() - start_time + parent_stats = self._plan.stats() + splits = [] + + for bs, ms in zip(blocks, metadata): + stats = DatasetStats(metadata={"Split": ms}, parent=parent_stats) + stats.time_total_s = split_duration + ref_bundles = [ + RefBundle([(b, m)], owns_blocks=False, schema=bundle.schema) + for b, m in zip(bs, ms) + ] + logical_plan = LogicalPlan( + InputData(input_data=ref_bundles), + self.context, + ) + + splits.append( + MaterializedDataset( + ExecutionPlan(stats, self.context.copy()), + logical_plan, + ) + ) + return splits + + @ConsumptionAPI + @PublicAPI(api_group=SMJ_API_GROUP) + def split_proportionately( + self, proportions: List[float] + ) -> List["MaterializedDataset"]: + """Materialize and split the dataset using proportions. + + A common use case for this is splitting the dataset into train + and test sets (equivalent to eg. scikit-learn's ``train_test_split``). + For a higher level abstraction, see :meth:`Dataset.train_test_split`. + + This method splits datasets so that all splits + always contains at least one row. If that isn't possible, + an exception is raised. + + This is equivalent to caulculating the indices manually and calling + :meth:`Dataset.split_at_indices`. + + Examples: + >>> import ray + >>> ds = ray.data.range(10) + >>> d1, d2, d3 = ds.split_proportionately([0.2, 0.5]) + >>> d1.take_batch() + {'id': array([0, 1])} + >>> d2.take_batch() + {'id': array([2, 3, 4, 5, 6])} + >>> d3.take_batch() + {'id': array([7, 8, 9])} + + Time complexity: O(num splits) + + Args: + proportions: List of proportions to split the dataset according to. + Must sum up to less than 1, and each proportion must be bigger + than 0. + + Returns: + The dataset splits. + + .. seealso:: + + :meth:`Dataset.split` + Unlike :meth:`~Dataset.split_proportionately`, which lets you split a + dataset into different sizes, :meth:`Dataset.split` splits a dataset + into approximately equal splits. + + :meth:`Dataset.split_at_indices` + :meth:`Dataset.split_proportionately` uses this method under the hood. + + :meth:`Dataset.streaming_split`. + Unlike :meth:`~Dataset.split`, :meth:`~Dataset.streaming_split` + doesn't materialize the dataset in memory. + """ + + if len(proportions) < 1: + raise ValueError("proportions must be at least of length 1") + if sum(proportions) >= 1: + raise ValueError("proportions must sum to less than 1") + if any(p <= 0 for p in proportions): + raise ValueError("proportions must be bigger than 0") + + dataset_length = self.count() + cumulative_proportions = np.cumsum(proportions) + split_indices = [ + int(dataset_length * proportion) for proportion in cumulative_proportions + ] + + # Ensure each split has at least one element + subtract = 0 + for i in range(len(split_indices) - 2, -1, -1): + split_indices[i] -= subtract + if split_indices[i] == split_indices[i + 1]: + subtract += 1 + split_indices[i] -= 1 + if any(i <= 0 for i in split_indices): + raise ValueError( + "Couldn't create non-empty splits with the given proportions." + ) + + return self.split_at_indices(split_indices) + + @ConsumptionAPI + @PublicAPI(api_group=SMJ_API_GROUP) + def train_test_split( + self, + test_size: Union[int, float], + *, + shuffle: bool = False, + seed: Optional[int] = None, + ) -> Tuple["MaterializedDataset", "MaterializedDataset"]: + """Materialize and split the dataset into train and test subsets. + + Examples: + + >>> import ray + >>> ds = ray.data.range(8) + >>> train, test = ds.train_test_split(test_size=0.25) + >>> train.take_batch() + {'id': array([0, 1, 2, 3, 4, 5])} + >>> test.take_batch() + {'id': array([6, 7])} + + Args: + test_size: If float, should be between 0.0 and 1.0 and represent the + proportion of the dataset to include in the test split. If int, + represents the absolute number of test samples. The train split + always complements the test split. + shuffle: Whether or not to globally shuffle the dataset before splitting. + Defaults to ``False``. This may be a very expensive operation with a + large dataset. + seed: Fix the random seed to use for shuffle, otherwise one is chosen + based on system randomness. Ignored if ``shuffle=False``. + + Returns: + Train and test subsets as two ``MaterializedDatasets``. + + .. seealso:: + + :meth:`Dataset.split_proportionately` + """ + ds = self + + if shuffle: + ds = ds.random_shuffle(seed=seed) + + if not isinstance(test_size, (int, float)): + raise TypeError(f"`test_size` must be int or float got {type(test_size)}.") + if isinstance(test_size, float): + if test_size <= 0 or test_size >= 1: + raise ValueError( + "If `test_size` is a float, it must be bigger than 0 and smaller " + f"than 1. Got {test_size}." + ) + return ds.split_proportionately([1 - test_size]) + else: + ds_length = ds.count() + if test_size <= 0 or test_size >= ds_length: + raise ValueError( + "If `test_size` is an int, it must be bigger than 0 and smaller " + f"than the size of the dataset ({ds_length}). " + f"Got {test_size}." + ) + return ds.split_at_indices([ds_length - test_size]) + + @PublicAPI(api_group=SMJ_API_GROUP) + def union(self, *other: List["Dataset"]) -> "Dataset": + """Concatenate :class:`Datasets ` across rows. + + The order of the blocks in the datasets is preserved, as is the + relative ordering between the datasets passed in the argument list. + + .. caution:: + Unioned datasets aren't lineage-serializable. As a result, they can't be + used as a tunable hyperparameter in Ray Tune. + + Examples: + + >>> import ray + >>> ds1 = ray.data.range(2) + >>> ds2 = ray.data.range(3) + >>> ds1.union(ds2).take_all() + [{'id': 0}, {'id': 1}, {'id': 0}, {'id': 1}, {'id': 2}] + + Args: + other: List of datasets to combine with this one. The datasets + must have the same schema as this dataset, otherwise the + behavior is undefined. + + Returns: + A new dataset holding the rows of the input datasets. + """ + start_time = time.perf_counter() + + datasets = [self] + list(other) + logical_plans = [union_ds._plan._logical_plan for union_ds in datasets] + op = UnionLogicalOperator( + *[plan.dag for plan in logical_plans], + ) + logical_plan = LogicalPlan(op, self.context) + + stats = DatasetStats( + metadata={"Union": []}, + parent=[d._plan.stats() for d in datasets], + ) + stats.time_total_s = time.perf_counter() - start_time + return Dataset( + ExecutionPlan(stats, self.context.copy()), + logical_plan, + ) + + @AllToAllAPI + @PublicAPI(api_group=SMJ_API_GROUP) + def join( + self, + ds: "Dataset", + join_type: str, + num_partitions: int, + on: Tuple[str] = ("id",), + right_on: Optional[Tuple[str]] = None, + left_suffix: Optional[str] = None, + right_suffix: Optional[str] = None, + *, + partition_size_hint: Optional[int] = None, + aggregator_ray_remote_args: Optional[Dict[str, Any]] = None, + validate_schemas: bool = False, + ) -> "Dataset": + """Join :class:`Datasets ` on join keys. + + Args: + ds: Other dataset to join against + join_type: The kind of join that should be performed, one of ("inner", + "left_outer", "right_outer", "full_outer") + num_partitions: Total number of "partitions" input sequences will be split + into with each partition being joined independently. Increasing number + of partitions allows to reduce individual partition size, hence reducing + memory requirements when individual partitions are being joined. Note + that, consequently, this will also be a total number of blocks that will + be produced as a result of executing join. + on: The columns from the left operand that will be used as + keys for the join operation. + right_on: The columns from the right operand that will be + used as keys for the join operation. When none, `on` will + be assumed to be a list of columns to be used for the right dataset + as well. + left_suffix: (Optional) Suffix to be appended for columns of the left + operand. + right_suffix: (Optional) Suffix to be appended for columns of the right + operand. + partition_size_hint: (Optional) Hint to joining operator about the estimated + avg expected size of the individual partition (in bytes). + This is used in estimating the total dataset size and allow to tune + memory requirement of the individual joining workers to prevent OOMs + when joining very large datasets. + aggregator_ray_remote_args: (Optional) Parameter overriding `ray.remote` + args passed when constructing joining (aggregator) workers. + validate_schemas: (Optional) Controls whether validation of provided + configuration against input schemas will be performed (defaults to + false, since obtaining schemas could be prohibitively expensive). + + Returns: + A :class:`Dataset` that holds rows of input left Dataset joined with the + right Dataset based on join type and keys. + + Examples: + + .. testcode:: + :skipif: True + + doubles_ds = ray.data.range(4).map( + lambda row: {"id": row["id"], "double": int(row["id"]) * 2} + ) + + squares_ds = ray.data.range(4).map( + lambda row: {"id": row["id"], "square": int(row["id"]) ** 2} + ) + + joined_ds = doubles_ds.join( + squares_ds, + join_type="inner", + num_partitions=2, + on=("id",), + ) + + print(sorted(joined_ds.take_all(), key=lambda item: item["id"])) + + .. testoutput:: + :options: +ELLIPSIS, +NORMALIZE_WHITESPACE + + [ + {'id': 0, 'double': 0, 'square': 0}, + {'id': 1, 'double': 2, 'square': 1}, + {'id': 2, 'double': 4, 'square': 4}, + {'id': 3, 'double': 6, 'square': 9} + ] + """ + + if not isinstance(on, (tuple, list)): + raise ValueError( + f"Expected tuple or list as `on` (got {type(on).__name__})" + ) + + if right_on and not isinstance(right_on, (tuple, list)): + raise ValueError( + f"Expected tuple or list as `right_on` (got {type(right_on).__name__})" + ) + + # NOTE: If no separate keys provided for the right side, assume just the left + # side ones + right_on = right_on or on + + # NOTE: By default validating schemas are disabled as it could be arbitrarily + # expensive (potentially executing whole pipeline to completion) to fetch + # one currently + if validate_schemas: + left_op_schema: Optional["Schema"] = self.schema() + right_op_schema: Optional["Schema"] = ds.schema() + + Join._validate_schemas(left_op_schema, right_op_schema, on, right_on) + + plan = self._plan.copy() + op = Join( + left_input_op=self._logical_plan.dag, + right_input_op=ds._logical_plan.dag, + left_key_columns=on, + right_key_columns=right_on, + join_type=join_type, + num_partitions=num_partitions, + left_columns_suffix=left_suffix, + right_columns_suffix=right_suffix, + partition_size_hint=partition_size_hint, + aggregator_ray_remote_args=aggregator_ray_remote_args, + ) + + return Dataset(plan, LogicalPlan(op, self.context)) + + @AllToAllAPI + @PublicAPI(api_group=GGA_API_GROUP) + def groupby( + self, + key: Union[str, List[str], None], + num_partitions: Optional[int] = None, + ) -> "GroupedData": + """Group rows of a :class:`Dataset` according to a column. + + Use this method to transform data based on a + categorical variable. + + Examples: + + .. testcode:: + + import pandas as pd + import ray + + def normalize_variety(group: pd.DataFrame) -> pd.DataFrame: + for feature in group.drop("variety").columns: + group[feature] = group[feature] / group[feature].abs().max() + return group + + ds = ( + ray.data.read_parquet("s3://anonymous@ray-example-data/iris.parquet") + .groupby("variety") + .map_groups(normalize_variety, batch_format="pandas") + ) + + Time complexity: O(dataset size * log(dataset size / parallelism)) + + Args: + key: A column name or list of column names. + If this is ``None``, place all rows in a single group. + + num_partitions: Number of partitions data will be partitioned into (only + relevant if hash-shuffling strategy is used). When not set defaults + to `DataContext.min_parallelism`. + + Returns: + A lazy :class:`~ray.data.grouped_data.GroupedData`. + + .. seealso:: + + :meth:`~ray.data.grouped_data.GroupedData.map_groups` + Call this method to transform groups of data. + """ + from ray.data.grouped_data import GroupedData + + # Always allow None since groupby interprets that as grouping all + # records into a single global group. + if key is not None: + # Fetching the schema can trigger execution, so don't fetch it for + # input validation. + SortKey(key).validate_schema(self.schema(fetch_if_missing=False)) + + if num_partitions is not None and num_partitions <= 0: + raise ValueError("`num_partitions` must be a positive integer") + + return GroupedData(self, key, num_partitions=num_partitions) + + @AllToAllAPI + @ConsumptionAPI + @PublicAPI(api_group=GGA_API_GROUP) + def unique(self, column: str) -> List[Any]: + """List the unique elements in a given column. + + Examples: + + >>> import ray + >>> ds = ray.data.from_items([1, 2, 3, 2, 3]) + >>> ds.unique("item") + [1, 2, 3] + + This function is very useful for computing labels + in a machine learning dataset: + + >>> import ray + >>> ds = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + >>> ds.unique("target") + [0, 1, 2] + + One common use case is to convert the class labels + into integers for training and inference: + + >>> classes = {0: 'Setosa', 1: 'Versicolor', 2: 'Virginica'} + >>> def preprocessor(df, classes): + ... df["variety"] = df["target"].map(classes) + ... return df + >>> train_ds = ds.map_batches( + ... preprocessor, fn_kwargs={"classes": classes}, batch_format="pandas") + >>> train_ds.sort("sepal length (cm)").take(1) # Sort to make it deterministic + [{'sepal length (cm)': 4.3, ..., 'variety': 'Setosa'}] + + Time complexity: O(dataset size / parallelism) + + Args: + column: The column to collect unique elements over. + + Returns: + A list with unique elements in the given column. + """ # noqa: E501 + ret = self._aggregate_on(Unique, column) + return self._aggregate_result(ret) + + @AllToAllAPI + @ConsumptionAPI + @PublicAPI(api_group=GGA_API_GROUP) + def aggregate(self, *aggs: AggregateFn) -> Union[Any, Dict[str, Any]]: + """Aggregate values using one or more functions. + + Use this method to compute metrics like the product of a column. + + Examples: + + .. testcode:: + + import ray + from ray.data.aggregate import AggregateFn + + ds = ray.data.from_items([{"number": i} for i in range(1, 10)]) + aggregation = AggregateFn( + init=lambda column: 1, + # Apply this to each row to produce a partial aggregate result + accumulate_row=lambda a, row: a * row["number"], + # Apply this to merge partial aggregate results into a final result + merge=lambda a1, a2: a1 * a2, + name="prod" + ) + print(ds.aggregate(aggregation)) + + .. testoutput:: + + {'prod': 362880} + + Time complexity: O(dataset size / parallelism) + + Args: + *aggs: :class:`Aggregations ` to perform. + + Returns: + A ``dict`` where each each value is an aggregation for a given column. + """ + ret = self.groupby(None).aggregate(*aggs).take(1) + return ret[0] if len(ret) > 0 else None + + @AllToAllAPI + @ConsumptionAPI + @PublicAPI(api_group=GGA_API_GROUP) + def sum( + self, on: Optional[Union[str, List[str]]] = None, ignore_nulls: bool = True + ) -> Union[Any, Dict[str, Any]]: + """Compute the sum of one or more columns. + + Examples: + >>> import ray + >>> ray.data.range(100).sum("id") + 4950 + >>> ray.data.from_items([ + ... {"A": i, "B": i**2} + ... for i in range(100) + ... ]).sum(["A", "B"]) + {'sum(A)': 4950, 'sum(B)': 328350} + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values are ignored when computing the sum. If ``False``, + when a null value is encountered, the output is ``None``. + Ray Data considers ``np.nan``, ``None``, and ``pd.NaT`` to be null + values. Default is ``True``. + + Returns: + The sum result. + + For different values of ``on``, the return varies: + + - ``on=None``: a dict containing the column-wise sum of all + columns, + - ``on="col"``: a scalar representing the sum of all items in + column ``"col"``, + - ``on=["col_1", ..., "col_n"]``: an n-column ``dict`` + containing the column-wise sum of the provided columns. + + If the dataset is empty, all values are null. If ``ignore_nulls`` is + ``False`` and any value is null, then the output is ``None``. + """ + ret = self._aggregate_on(Sum, on, ignore_nulls=ignore_nulls) + return self._aggregate_result(ret) + + @AllToAllAPI + @ConsumptionAPI + @PublicAPI(api_group=GGA_API_GROUP) + def min( + self, on: Optional[Union[str, List[str]]] = None, ignore_nulls: bool = True + ) -> Union[Any, Dict[str, Any]]: + """Return the minimum of one or more columns. + + Examples: + >>> import ray + >>> ray.data.range(100).min("id") + 0 + >>> ray.data.from_items([ + ... {"A": i, "B": i**2} + ... for i in range(100) + ... ]).min(["A", "B"]) + {'min(A)': 0, 'min(B)': 0} + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values are ignored when computing the min; if ``False``, + when a null value is encountered, the output is ``None``. + This method considers ``np.nan``, ``None``, and ``pd.NaT`` to be null + values. Default is ``True``. + + Returns: + The min result. + + For different values of ``on``, the return varies: + + - ``on=None``: an dict containing the column-wise min of + all columns, + - ``on="col"``: a scalar representing the min of all items in + column ``"col"``, + - ``on=["col_1", ..., "col_n"]``: an n-column dict + containing the column-wise min of the provided columns. + + If the dataset is empty, all values are null. If ``ignore_nulls`` is + ``False`` and any value is null, then the output is ``None``. + """ + ret = self._aggregate_on(Min, on, ignore_nulls=ignore_nulls) + return self._aggregate_result(ret) + + @AllToAllAPI + @ConsumptionAPI + @PublicAPI(api_group=GGA_API_GROUP) + def max( + self, on: Optional[Union[str, List[str]]] = None, ignore_nulls: bool = True + ) -> Union[Any, Dict[str, Any]]: + """Return the maximum of one or more columns. + + Examples: + >>> import ray + >>> ray.data.range(100).max("id") + 99 + >>> ray.data.from_items([ + ... {"A": i, "B": i**2} + ... for i in range(100) + ... ]).max(["A", "B"]) + {'max(A)': 99, 'max(B)': 9801} + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values are ignored when computing the max; if ``False``, + when a null value is encountered, the output is ``None``. + This method considers ``np.nan``, ``None``, and ``pd.NaT`` to be null + values. Default is ``True``. + + Returns: + The max result. + + For different values of ``on``, the return varies: + + - ``on=None``: an dict containing the column-wise max of + all columns, + - ``on="col"``: a scalar representing the max of all items in + column ``"col"``, + - ``on=["col_1", ..., "col_n"]``: an n-column dict + containing the column-wise max of the provided columns. + + If the dataset is empty, all values are null. If ``ignore_nulls`` is + ``False`` and any value is null, then the output is ``None``. + """ + ret = self._aggregate_on(Max, on, ignore_nulls=ignore_nulls) + return self._aggregate_result(ret) + + @AllToAllAPI + @ConsumptionAPI + @PublicAPI(api_group=GGA_API_GROUP) + def mean( + self, on: Optional[Union[str, List[str]]] = None, ignore_nulls: bool = True + ) -> Union[Any, Dict[str, Any]]: + """Compute the mean of one or more columns. + + Examples: + >>> import ray + >>> ray.data.range(100).mean("id") + 49.5 + >>> ray.data.from_items([ + ... {"A": i, "B": i**2} + ... for i in range(100) + ... ]).mean(["A", "B"]) + {'mean(A)': 49.5, 'mean(B)': 3283.5} + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values are ignored when computing the mean; if ``False``, + when a null value is encountered, the output is ``None``. + This method considers ``np.nan``, ``None``, and ``pd.NaT`` to be null + values. Default is ``True``. + + Returns: + The mean result. + + For different values of ``on``, the return varies: + + - ``on=None``: an dict containing the column-wise mean of + all columns, + - ``on="col"``: a scalar representing the mean of all items in + column ``"col"``, + - ``on=["col_1", ..., "col_n"]``: an n-column dict + containing the column-wise mean of the provided columns. + + If the dataset is empty, all values are null. If ``ignore_nulls`` is + ``False`` and any value is null, then the output is ``None``. + """ + ret = self._aggregate_on(Mean, on, ignore_nulls=ignore_nulls) + return self._aggregate_result(ret) + + @AllToAllAPI + @ConsumptionAPI + @PublicAPI(api_group=GGA_API_GROUP) + def std( + self, + on: Optional[Union[str, List[str]]] = None, + ddof: int = 1, + ignore_nulls: bool = True, + ) -> Union[Any, Dict[str, Any]]: + """Compute the standard deviation of one or more columns. + + .. note:: + This method uses Welford's online method for an accumulator-style + computation of the standard deviation. This method has + numerical stability, and is computable in a single pass. This may give + different (but more accurate) results than NumPy, Pandas, and sklearn, which + use a less numerically stable two-pass algorithm. + To learn more, see + `the Wikapedia article `_. + + Examples: + >>> import ray + >>> round(ray.data.range(100).std("id", ddof=0), 5) + 28.86607 + >>> ray.data.from_items([ + ... {"A": i, "B": i**2} + ... for i in range(100) + ... ]).std(["A", "B"]) + {'std(A)': 29.011491975882016, 'std(B)': 2968.1748039269296} + + Args: + on: a column name or a list of column names to aggregate. + ddof: Delta Degrees of Freedom. The divisor used in calculations + is ``N - ddof``, where ``N`` represents the number of elements. + ignore_nulls: Whether to ignore null values. If ``True``, null + values are ignored when computing the std; if ``False``, + when a null value is encountered, the output is ``None``. + This method considers ``np.nan``, ``None``, and ``pd.NaT`` to be null + values. Default is ``True``. + + Returns: + The standard deviation result. + + For different values of ``on``, the return varies: + + - ``on=None``: an dict containing the column-wise std of + all columns, + - ``on="col"``: a scalar representing the std of all items in + column ``"col"``, + - ``on=["col_1", ..., "col_n"]``: an n-column dict + containing the column-wise std of the provided columns. + + If the dataset is empty, all values are null. If ``ignore_nulls`` is + ``False`` and any value is null, then the output is ``None``. + """ # noqa: E501 + ret = self._aggregate_on(Std, on, ignore_nulls=ignore_nulls, ddof=ddof) + return self._aggregate_result(ret) + + @AllToAllAPI + @PublicAPI(api_group=SSR_API_GROUP) + def sort( + self, + key: Union[str, List[str]], + descending: Union[bool, List[bool]] = False, + boundaries: List[Union[int, float]] = None, + ) -> "Dataset": + """Sort the dataset by the specified key column or key function. + The `key` parameter must be specified (i.e., it cannot be `None`). + + .. note:: + If provided, the `boundaries` parameter can only be used to partition + the first sort key. + + Examples: + >>> import ray + >>> ds = ray.data.range(15) + >>> ds = ds.sort("id", descending=False, boundaries=[5, 10]) + >>> for df in ray.get(ds.to_pandas_refs()): + ... print(df) + id + 0 0 + 1 1 + 2 2 + 3 3 + 4 4 + id + 0 5 + 1 6 + 2 7 + 3 8 + 4 9 + id + 0 10 + 1 11 + 2 12 + 3 13 + 4 14 + + Time complexity: O(dataset size * log(dataset size / parallelism)) + + Args: + key: The column or a list of columns to sort by. + descending: Whether to sort in descending order. Must be a boolean or a list + of booleans matching the number of the columns. + boundaries: The list of values based on which to repartition the dataset. + For example, if the input boundary is [10,20], rows with values less + than 10 will be divided into the first block, rows with values greater + than or equal to 10 and less than 20 will be divided into the + second block, and rows with values greater than or equal to 20 + will be divided into the third block. If not provided, the + boundaries will be sampled from the input blocks. This feature + only supports numeric columns right now. + + Returns: + A new, sorted :class:`Dataset`. + + Raises: + ``ValueError``: if the sort key is None. + """ + if key is None: + raise ValueError("The 'key' parameter cannot be None for sorting.") + sort_key = SortKey(key, descending, boundaries) + plan = self._plan.copy() + op = Sort( + self._logical_plan.dag, + sort_key=sort_key, + ) + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @PublicAPI(api_group=SMJ_API_GROUP) + def zip(self, other: "Dataset") -> "Dataset": + """Zip the columns of this dataset with the columns of another. + + The datasets must have the same number of rows. Their column sets are + merged, and any duplicate column names are disambiguated with suffixes like + ``"_1"``. + + .. note:: + The smaller of the two datasets is repartitioned to align the number + of rows per block with the larger dataset. + + .. note:: + Zipped datasets aren't lineage-serializable. As a result, they can't be used + as a tunable hyperparameter in Ray Tune. + + Examples: + >>> import ray + >>> ds1 = ray.data.range(5) + >>> ds2 = ray.data.range(5) + >>> ds1.zip(ds2).take_batch() + {'id': array([0, 1, 2, 3, 4]), 'id_1': array([0, 1, 2, 3, 4])} + + Args: + other: The dataset to zip with on the right hand side. + + Returns: + A :class:`Dataset` containing the columns of the second dataset + concatenated horizontally with the columns of the first dataset, + with duplicate column names disambiguated with suffixes like ``"_1"``. + """ + plan = self._plan.copy() + op = Zip(self._logical_plan.dag, other._logical_plan.dag) + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @PublicAPI(api_group=BT_API_GROUP) + def limit(self, limit: int) -> "Dataset": + """Truncate the dataset to the first ``limit`` rows. + + Unlike :meth:`~Dataset.take`, this method doesn't move data to the caller's + machine. Instead, it returns a new :class:`Dataset` pointing to the truncated + distributed data. + + Examples: + >>> import ray + >>> ds = ray.data.range(1000) + >>> ds.limit(5).count() + 5 + + Time complexity: O(limit specified) + + Args: + limit: The size of the dataset to truncate to. + + Returns: + The truncated dataset. + """ + plan = self._plan.copy() + op = Limit(self._logical_plan.dag, limit=limit) + logical_plan = LogicalPlan(op, self.context) + return Dataset(plan, logical_plan) + + @ConsumptionAPI + @PublicAPI(api_group=CD_API_GROUP) + def take_batch( + self, batch_size: int = 20, *, batch_format: Optional[str] = "default" + ) -> DataBatch: + """Return up to ``batch_size`` rows from the :class:`Dataset` in a batch. + + Ray Data represents batches as NumPy arrays or pandas DataFrames. You can + configure the batch type by specifying ``batch_format``. + + This method is useful for inspecting inputs to :meth:`~Dataset.map_batches`. + + .. warning:: + + :meth:`~Dataset.take_batch` moves up to ``batch_size`` rows to the caller's + machine. If ``batch_size`` is large, this method can cause an ` + ``OutOfMemory`` error on the caller. + + Examples: + + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.take_batch(5) + {'id': array([0, 1, 2, 3, 4])} + + Time complexity: O(batch_size specified) + + Args: + batch_size: The maximum number of rows to return. + batch_format: If ``"default"`` or ``"numpy"``, batches are + ``Dict[str, numpy.ndarray]``. If ``"pandas"``, batches are + ``pandas.DataFrame``. + + Returns: + A batch of up to ``batch_size`` rows from the dataset. + + Raises: + ``ValueError``: if the dataset is empty. + """ + batch_format = _apply_batch_format(batch_format) + limited_ds = self.limit(batch_size) + + try: + res = next( + iter( + limited_ds.iter_batches( + batch_size=batch_size, + prefetch_batches=0, + batch_format=batch_format, + ) + ) + ) + except StopIteration: + raise ValueError("The dataset is empty.") + self._synchronize_progress_bar() + + # Save the computed stats to the original dataset. + self._plan._snapshot_stats = limited_ds._plan.stats() + return res + + @ConsumptionAPI + @PublicAPI(api_group=CD_API_GROUP) + def take(self, limit: int = 20) -> List[Dict[str, Any]]: + """Return up to ``limit`` rows from the :class:`Dataset`. + + This method is useful for inspecting data. + + .. warning:: + + :meth:`~Dataset.take` moves up to ``limit`` rows to the caller's machine. If + ``limit`` is large, this method can cause an ``OutOfMemory`` error on the + caller. + + Examples: + + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.take(3) + [{'id': 0}, {'id': 1}, {'id': 2}] + + Time complexity: O(limit specified) + + Args: + limit: The maximum number of rows to return. + + Returns: + A list of up to ``limit`` rows from the dataset. + + .. seealso:: + + :meth:`~Dataset.take_all` + Call this method to return all rows. + """ + if ray.util.log_once("dataset_take"): + logger.info( + "Tip: Use `take_batch()` instead of `take() / show()` to return " + "records in pandas or numpy batch format." + ) + output = [] + + limited_ds = self.limit(limit) + for row in limited_ds.iter_rows(): + output.append(row) + if len(output) >= limit: + break + self._synchronize_progress_bar() + + # Save the computed stats to the original dataset. + self._plan._snapshot_stats = limited_ds._plan.stats() + return output + + @ConsumptionAPI + @PublicAPI(api_group=CD_API_GROUP) + def take_all(self, limit: Optional[int] = None) -> List[Dict[str, Any]]: + """Return all of the rows in this :class:`Dataset`. + + This method is useful for inspecting small datasets. + + .. warning:: + + :meth:`~Dataset.take_all` moves the entire dataset to the caller's + machine. If the dataset is large, this method can cause an + ``OutOfMemory`` error on the caller. + + Examples: + >>> import ray + >>> ds = ray.data.range(5) + >>> ds.take_all() + [{'id': 0}, {'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}] + + Time complexity: O(dataset size) + + Args: + limit: Raise an error if the size exceeds the specified limit. + + Returns: + A list of all the rows in the dataset. + + .. seealso:: + + :meth:`~Dataset.take` + Call this method to return a specific number of rows. + """ + output = [] + for row in self.iter_rows(): + output.append(row) + if limit is not None and len(output) > limit: + raise ValueError( + f"The dataset has more than the given limit of {limit} records." + ) + self._synchronize_progress_bar() + return output + + @ConsumptionAPI + @PublicAPI(api_group=CD_API_GROUP) + def show(self, limit: int = 20) -> None: + """Print up to the given number of rows from the :class:`Dataset`. + + This method is useful for inspecting data. + + Examples: + + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.show(3) + {'id': 0} + {'id': 1} + {'id': 2} + + Time complexity: O(limit specified) + + Args: + limit: The maximum number of row to print. + + .. seealso:: + + :meth:`~Dataset.take` + Call this method to get (not print) a given number of rows. + """ + for row in self.take(limit): + print(row) + + @ConsumptionAPI( + if_more_than_read=True, + datasource_metadata="row count", + pattern="Examples:", + ) + @PublicAPI(api_group=IM_API_GROUP) + def count(self) -> int: + """Count the number of rows in the dataset. + + For Datasets which only read Parquet files (created with + :meth:`~ray.data.read_parquet`), this method reads the file metadata to + efficiently count the number of rows without reading in the entire data. + + Examples: + >>> import ray + >>> ds = ray.data.range(10) + >>> ds.count() + 10 + + Returns: + The number of records in the dataset. + """ + # Handle empty dataset. + if self._plan.initial_num_blocks() == 0: + return 0 + + # For parquet, we can return the count directly from metadata. + meta_count = self._meta_count() + if meta_count is not None: + return meta_count + + plan = self._plan.copy() + count_op = Count([self._logical_plan.dag]) + logical_plan = LogicalPlan(count_op, self.context) + count_ds = Dataset(plan, logical_plan) + + count = 0 + for batch in count_ds.iter_batches(batch_size=None): + assert Count.COLUMN_NAME in batch, ( + "Outputs from the 'Count' logical operator should contain a column " + f"named '{Count.COLUMN_NAME}'" + ) + count += batch[Count.COLUMN_NAME].sum() + # Explicitly cast to int to avoid returning `np.int64`, which is the result + # from calculating `sum()` from numpy batches. + return int(count) + + @ConsumptionAPI( + if_more_than_read=True, + datasource_metadata="schema", + extra_condition="or if ``fetch_if_missing=True`` (the default)", + pattern="Time complexity:", + ) + @PublicAPI(api_group=IM_API_GROUP) + def schema(self, fetch_if_missing: bool = True) -> Optional["Schema"]: + """Return the schema of the dataset. + + Examples: + >>> import ray + >>> ds = ray.data.range(10) + >>> ds.schema() + Column Type + ------ ---- + id int64 + + Time complexity: O(1) + + Args: + fetch_if_missing: If True, synchronously fetch the schema if it's + not known. If False, None is returned if the schema is not known. + Default is True. + + Returns: + The :class:`ray.data.Schema` class of the records, or None if the + schema is not known and fetch_if_missing is False. + """ + + context = self._plan._context + + # First check if the schema is already known from materialized blocks. + base_schema = self._plan.schema(fetch_if_missing=False) + if base_schema is not None: + return Schema(base_schema, data_context=context) + + # Lazily execute only the first block to minimize computation. We achieve this + # by appending a Limit[1] operation to a copy of this Dataset, which we then + # execute to get its schema. + base_schema = self.limit(1)._plan.schema(fetch_if_missing=fetch_if_missing) + if base_schema is not None: + self._plan.cache_schema(base_schema) + return Schema(base_schema, data_context=context) + else: + return None + + @ConsumptionAPI( + if_more_than_read=True, + datasource_metadata="schema", + extra_condition="or if ``fetch_if_missing=True`` (the default)", + pattern="Time complexity:", + ) + @PublicAPI(api_group=IM_API_GROUP) + def columns(self, fetch_if_missing: bool = True) -> Optional[List[str]]: + """Returns the columns of this Dataset. + + Time complexity: O(1) + + Example: + >>> import ray + >>> # Create dataset from synthetic data. + >>> ds = ray.data.range(1000) + >>> ds.columns() + ['id'] + + Args: + fetch_if_missing: If True, synchronously fetch the column names from the + schema if it's not known. If False, None is returned if the schema is + not known. Default is True. + + Returns: + A list of the column names for this Dataset or None if schema is not known + and `fetch_if_missing` is False. + + """ + schema = self.schema(fetch_if_missing=fetch_if_missing) + if schema is not None: + return schema.names + return None + + @PublicAPI(api_group=IM_API_GROUP) + def num_blocks(self) -> int: + """Return the number of blocks of this :class:`Dataset`. + + This method is only implemented for :class:`~ray.data.MaterializedDataset`, + since the number of blocks may dynamically change during execution. + For instance, during read and transform operations, Ray Data may dynamically + adjust the number of blocks to respect memory limits, increasing the + number of blocks at runtime. + + Returns: + The number of blocks of this :class:`Dataset`. + """ + raise NotImplementedError( + "Number of blocks is only available for `MaterializedDataset`," + "because the number of blocks may dynamically change during execution." + "Call `ds.materialize()` to get a `MaterializedDataset`." + ) + + @ConsumptionAPI + @PublicAPI(api_group=IM_API_GROUP) + def size_bytes(self) -> int: + """Return the in-memory size of the dataset. + + Examples: + >>> import ray + >>> ds = ray.data.range(10) + >>> ds.size_bytes() + 80 + + Returns: + The in-memory size of the dataset in bytes, or None if the + in-memory size is not known. + """ + # If the size is known from metadata, return it. + if self._logical_plan.dag.infer_metadata().size_bytes is not None: + return self._logical_plan.dag.infer_metadata().size_bytes + + metadata = self._plan.execute().metadata + if not metadata or metadata[0].size_bytes is None: + return None + return sum(m.size_bytes for m in metadata) + + @ConsumptionAPI + @PublicAPI(api_group=IM_API_GROUP) + def input_files(self) -> List[str]: + """Return the list of input files for the dataset. + + Examples: + >>> import ray + >>> ds = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + >>> ds.input_files() + ['ray-example-data/iris.csv'] + + Returns: + The list of input files used to create the dataset, or an empty + list if the input files is not known. + """ + return list(set(self._plan.input_files())) + + @ConsumptionAPI + @PublicAPI(api_group=IOC_API_GROUP) + def write_parquet( + self, + path: str, + *, + partition_cols: Optional[List[str]] = None, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + try_create_dir: bool = True, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + filename_provider: Optional[FilenameProvider] = None, + arrow_parquet_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + min_rows_per_file: Optional[int] = None, + max_rows_per_file: Optional[int] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + num_rows_per_file: Optional[int] = None, + mode: SaveMode = SaveMode.APPEND, + **arrow_parquet_args, + ) -> None: + """Writes the :class:`~ray.data.Dataset` to parquet files under the provided ``path``. + + The number of files is determined by the number of blocks in the dataset. + To control the number of number of blocks, call + :meth:`~ray.data.Dataset.repartition`. + + If pyarrow can't represent your data, this method errors. + + By default, the format of the output files is ``{uuid}_{block_idx}.parquet``, + where ``uuid`` is a unique id for the dataset. To modify this behavior, + implement a custom :class:`~ray.data.datasource.FilenameProvider` and pass it in + as the ``filename_provider`` argument. + + Examples: + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.write_parquet("local:///tmp/data/") + + Time complexity: O(dataset size / parallelism) + + Args: + path: The path to the destination root directory, where + parquet files are written to. + partition_cols: Column names by which to partition the dataset. + Files are writted in Hive partition style. + filesystem: The pyarrow filesystem implementation to write to. + These filesystems are specified in the + `pyarrow docs `_. + Specify this if you need to provide specific configurations to the + filesystem. By default, the filesystem is automatically selected based + on the scheme of the paths. For example, if the path begins with + ``s3://``, the ``S3FileSystem`` is used. + try_create_dir: If ``True``, attempts to create all directories in the + destination path. Does nothing if all directories already + exist. Defaults to ``True``. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_output_stream `_, which is used when + opening the file to write to. + filename_provider: A :class:`~ray.data.datasource.FilenameProvider` + implementation. Use this parameter to customize what your filenames + look like. The filename is expected to be templatized with `{i}` + to ensure unique filenames when writing multiple files. If it's not + templatized, Ray Data will add `{i}` to the filename to ensure + compatibility with the pyarrow `write_dataset `_. + arrow_parquet_args_fn: Callable that returns a dictionary of write + arguments that are provided to `pyarrow.parquet.ParquetWriter() `_ + when writing each block to a file. Overrides + any duplicate keys from ``arrow_parquet_args``. If `row_group_size` is + provided, it will be passed to + `pyarrow.parquet.ParquetWriter.write_table() `_. Use this argument + instead of ``arrow_parquet_args`` if any of your write arguments + can't pickled, or if you'd like to lazily resolve the write + arguments for each dataset block. + min_rows_per_file: [Experimental] The target minimum number of rows to write + to each file. If ``None``, Ray Data writes a system-chosen number of + rows to each file. If the number of rows per block is larger than the + specified value, Ray Data writes the number of rows per block to each file. + The specified value is a hint, not a strict limit. Ray Data + might write more or fewer rows to each file. + max_rows_per_file: [Experimental] The target maximum number of rows to write + to each file. If ``None``, Ray Data writes a system-chosen number of + rows to each file. If the number of rows per block is smaller than the + specified value, Ray Data writes the number of rows per block to each file. + The specified value is a hint, not a strict limit. Ray Data + might write more or fewer rows to each file. If both ``min_rows_per_file`` + and ``max_rows_per_file`` are specified, ``max_rows_per_file`` takes + precedence when they cannot both be satisfied. + ray_remote_args: Kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + num_rows_per_file: [Deprecated] Use min_rows_per_file instead. + arrow_parquet_args: Options to pass to + `pyarrow.parquet.ParquetWriter() `_, which is used to write + out each block to a file. See `arrow_parquet_args_fn` for more detail. + mode: Determines how to handle existing files. Valid modes are "overwrite", "error", + "ignore", "append". Defaults to "append". + NOTE: This method isn't atomic. "Overwrite" first deletes all the data + before writing to `path`. + """ # noqa: E501 + if arrow_parquet_args_fn is None: + arrow_parquet_args_fn = lambda: {} # noqa: E731 + + effective_min_rows, effective_max_rows = _validate_rows_per_file_args( + num_rows_per_file=num_rows_per_file, + min_rows_per_file=min_rows_per_file, + max_rows_per_file=max_rows_per_file, + ) + + datasink = ParquetDatasink( + path, + partition_cols=partition_cols, + arrow_parquet_args_fn=arrow_parquet_args_fn, + arrow_parquet_args=arrow_parquet_args, + min_rows_per_file=effective_min_rows, + max_rows_per_file=effective_max_rows, + filesystem=filesystem, + try_create_dir=try_create_dir, + open_stream_args=arrow_open_stream_args, + filename_provider=filename_provider, + dataset_uuid=self._uuid, + mode=mode, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + @PublicAPI(api_group=IOC_API_GROUP) + def write_json( + self, + path: str, + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + try_create_dir: bool = True, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + filename_provider: Optional[FilenameProvider] = None, + pandas_json_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + min_rows_per_file: Optional[int] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + num_rows_per_file: Optional[int] = None, + mode: SaveMode = SaveMode.APPEND, + **pandas_json_args, + ) -> None: + """Writes the :class:`~ray.data.Dataset` to JSON and JSONL files. + + The number of files is determined by the number of blocks in the dataset. + To control the number of number of blocks, call + :meth:`~ray.data.Dataset.repartition`. + + This method is only supported for datasets with records that are convertible to + pandas dataframes. + + By default, the format of the output files is ``{uuid}_{block_idx}.json``, + where ``uuid`` is a unique id for the dataset. To modify this behavior, + implement a custom :class:`~ray.data.datasource.FilenameProvider` and pass it in + as the ``filename_provider`` argument. + + Examples: + Write the dataset as JSON file to a local directory. + + >>> import ray + >>> import pandas as pd + >>> ds = ray.data.from_pandas([pd.DataFrame({"one": [1], "two": ["a"]})]) + >>> ds.write_json("local:///tmp/data") + + Write the dataset as JSONL files to a local directory. + + >>> ds = ray.data.read_json("s3://anonymous@ray-example-data/train.jsonl") + >>> ds.write_json("local:///tmp/data") + + Time complexity: O(dataset size / parallelism) + + Args: + path: The path to the destination root directory, where + the JSON files are written to. + filesystem: The pyarrow filesystem implementation to write to. + These filesystems are specified in the + `pyarrow docs `_. + Specify this if you need to provide specific configurations to the + filesystem. By default, the filesystem is automatically selected based + on the scheme of the paths. For example, if the path begins with + ``s3://``, the ``S3FileSystem`` is used. + try_create_dir: If ``True``, attempts to create all directories in the + destination path. Does nothing if all directories already + exist. Defaults to ``True``. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_output_stream `_, which is used when + opening the file to write to. + filename_provider: A :class:`~ray.data.datasource.FilenameProvider` + implementation. Use this parameter to customize what your filenames + look like. + pandas_json_args_fn: Callable that returns a dictionary of write + arguments that are provided to + `pandas.DataFrame.to_json() `_ + when writing each block to a file. Overrides + any duplicate keys from ``pandas_json_args``. Use this parameter + instead of ``pandas_json_args`` if any of your write arguments + can't be pickled, or if you'd like to lazily resolve the write + arguments for each dataset block. + min_rows_per_file: [Experimental] The target minimum number of rows to write + to each file. If ``None``, Ray Data writes a system-chosen number of + rows to each file. If the number of rows per block is larger than the + specified value, Ray Data writes the number of rows per block to each file. + The specified value is a hint, not a strict limit. Ray Data + might write more or fewer rows to each file. + ray_remote_args: kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + num_rows_per_file: Deprecated. Use ``min_rows_per_file`` instead. + pandas_json_args: These args are passed to + `pandas.DataFrame.to_json() `_, + which is used under the hood to write out each + :class:`~ray.data.Dataset` block. These + are dict(orient="records", lines=True) by default. + mode: Determines how to handle existing files. Valid modes are "overwrite", "error", + "ignore", "append". Defaults to "append". + NOTE: This method isn't atomic. "Overwrite" first deletes all the data + before writing to `path`. + """ + if pandas_json_args_fn is None: + pandas_json_args_fn = lambda: {} # noqa: E731 + + effective_min_rows, _ = _validate_rows_per_file_args( + num_rows_per_file=num_rows_per_file, min_rows_per_file=min_rows_per_file + ) + + datasink = JSONDatasink( + path, + pandas_json_args_fn=pandas_json_args_fn, + pandas_json_args=pandas_json_args, + min_rows_per_file=effective_min_rows, + filesystem=filesystem, + try_create_dir=try_create_dir, + open_stream_args=arrow_open_stream_args, + filename_provider=filename_provider, + dataset_uuid=self._uuid, + mode=mode, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + @PublicAPI(stability="alpha", api_group=IOC_API_GROUP) + def write_iceberg( + self, + table_identifier: str, + catalog_kwargs: Optional[Dict[str, Any]] = None, + snapshot_properties: Optional[Dict[str, str]] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + ) -> None: + """Writes the :class:`~ray.data.Dataset` to an Iceberg table. + + .. tip:: + For more details on PyIceberg, see + - URI: https://py.iceberg.apache.org/ + + Examples: + .. testcode:: + :skipif: True + + import ray + import pandas as pd + docs = [{"title": "Iceberg data sink test"} for key in range(4)] + ds = ray.data.from_pandas(pd.DataFrame(docs)) + ds.write_iceberg( + table_identifier="db_name.table_name", + catalog_kwargs={"name": "default", "type": "sql"} + ) + + Args: + table_identifier: Fully qualified table identifier (``db_name.table_name``) + catalog_kwargs: Optional arguments to pass to PyIceberg's catalog.load_catalog() + function (e.g., name, type, etc.). For the function definition, see + `pyiceberg catalog + `_. + snapshot_properties: custom properties write to snapshot when committing + to an iceberg table. + ray_remote_args: kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + """ + + datasink = IcebergDatasink( + table_identifier, catalog_kwargs, snapshot_properties + ) + + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @PublicAPI(stability="alpha", api_group=IOC_API_GROUP) + @ConsumptionAPI + def write_images( + self, + path: str, + column: str, + file_format: str = "png", + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + try_create_dir: bool = True, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + filename_provider: Optional[FilenameProvider] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + mode: SaveMode = SaveMode.APPEND, + ) -> None: + """Writes the :class:`~ray.data.Dataset` to images. + + Examples: + >>> import ray + >>> ds = ray.data.read_images("s3://anonymous@ray-example-data/image-datasets/simple") + >>> ds.write_images("local:///tmp/images", column="image") + + Time complexity: O(dataset size / parallelism) + + Args: + path: The path to the destination root directory, where + the images are written to. + column: The column containing the data you want to write to images. + file_format: The image file format to write with. For available options, + see `Image file formats `_. + filesystem: The pyarrow filesystem implementation to write to. + These filesystems are specified in the + `pyarrow docs `_. + Specify this if you need to provide specific configurations to the + filesystem. By default, the filesystem is automatically selected based + on the scheme of the paths. For example, if the path begins with + ``s3://``, the ``S3FileSystem`` is used. + try_create_dir: If ``True``, attempts to create all directories in the + destination path. Does nothing if all directories already + exist. Defaults to ``True``. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_output_stream `_, which is used when + opening the file to write to. + filename_provider: A :class:`~ray.data.datasource.FilenameProvider` + implementation. Use this parameter to customize what your filenames + look like. + ray_remote_args: kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + mode: Determines how to handle existing files. Valid modes are "overwrite", "error", + "ignore", "append". Defaults to "append". + NOTE: This method isn't atomic. "Overwrite" first deletes all the data + before writing to `path`. + """ # noqa: E501 + datasink = ImageDatasink( + path, + column, + file_format, + filesystem=filesystem, + try_create_dir=try_create_dir, + open_stream_args=arrow_open_stream_args, + filename_provider=filename_provider, + dataset_uuid=self._uuid, + mode=mode, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + @PublicAPI(api_group=IOC_API_GROUP) + def write_csv( + self, + path: str, + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + try_create_dir: bool = True, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + filename_provider: Optional[FilenameProvider] = None, + arrow_csv_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + min_rows_per_file: Optional[int] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + num_rows_per_file: Optional[int] = None, + mode: SaveMode = SaveMode.APPEND, + **arrow_csv_args, + ) -> None: + """Writes the :class:`~ray.data.Dataset` to CSV files. + + The number of files is determined by the number of blocks in the dataset. + To control the number of number of blocks, call + :meth:`~ray.data.Dataset.repartition`. + + This method is only supported for datasets with records that are convertible to + pyarrow tables. + + By default, the format of the output files is ``{uuid}_{block_idx}.csv``, + where ``uuid`` is a unique id for the dataset. To modify this behavior, + implement a custom :class:`~ray.data.datasource.FilenameProvider` + and pass it in as the ``filename_provider`` argument. + + + Examples: + Write the dataset as CSV files to a local directory. + + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.write_csv("local:///tmp/data") + + Write the dataset as CSV files to S3. + + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.write_csv("s3://bucket/folder/) # doctest: +SKIP + + Time complexity: O(dataset size / parallelism) + + Args: + path: The path to the destination root directory, where + the CSV files are written to. + filesystem: The pyarrow filesystem implementation to write to. + These filesystems are specified in the + `pyarrow docs `_. + Specify this if you need to provide specific configurations to the + filesystem. By default, the filesystem is automatically selected based + on the scheme of the paths. For example, if the path begins with + ``s3://``, the ``S3FileSystem`` is used. + try_create_dir: If ``True``, attempts to create all directories in the + destination path if ``True``. Does nothing if all directories already + exist. Defaults to ``True``. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_output_stream `_, which is used when + opening the file to write to. + filename_provider: A :class:`~ray.data.datasource.FilenameProvider` + implementation. Use this parameter to customize what your filenames + look like. + arrow_csv_args_fn: Callable that returns a dictionary of write + arguments that are provided to `pyarrow.write.write_csv `_ when writing each + block to a file. Overrides any duplicate keys from ``arrow_csv_args``. + Use this argument instead of ``arrow_csv_args`` if any of your write + arguments cannot be pickled, or if you'd like to lazily resolve the + write arguments for each dataset block. + min_rows_per_file: [Experimental] The target minimum number of rows to write + to each file. If ``None``, Ray Data writes a system-chosen number of + rows to each file. If the number of rows per block is larger than the + specified value, Ray Data writes the number of rows per block to each file. + The specified value is a hint, not a strict limit. Ray Data + might write more or fewer rows to each file. + ray_remote_args: kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + num_rows_per_file: [Deprecated] Use min_rows_per_file instead. + arrow_csv_args: Options to pass to `pyarrow.write.write_csv `_ + when writing each block to a file. + mode: Determines how to handle existing files. Valid modes are "overwrite", "error", + "ignore", "append". Defaults to "append". + NOTE: This method isn't atomic. "Overwrite" first deletes all the data + before writing to `path`. + """ + if arrow_csv_args_fn is None: + arrow_csv_args_fn = lambda: {} # noqa: E731 + + effective_min_rows, _ = _validate_rows_per_file_args( + num_rows_per_file=num_rows_per_file, min_rows_per_file=min_rows_per_file + ) + + datasink = CSVDatasink( + path, + arrow_csv_args_fn=arrow_csv_args_fn, + arrow_csv_args=arrow_csv_args, + min_rows_per_file=effective_min_rows, + filesystem=filesystem, + try_create_dir=try_create_dir, + open_stream_args=arrow_open_stream_args, + filename_provider=filename_provider, + dataset_uuid=self._uuid, + mode=mode, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + @PublicAPI(api_group=IOC_API_GROUP) + def write_tfrecords( + self, + path: str, + *, + tf_schema: Optional["schema_pb2.Schema"] = None, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + try_create_dir: bool = True, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + filename_provider: Optional[FilenameProvider] = None, + min_rows_per_file: Optional[int] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + num_rows_per_file: Optional[int] = None, + mode: SaveMode = SaveMode.APPEND, + ) -> None: + """Write the :class:`~ray.data.Dataset` to TFRecord files. + + The `TFRecord `_ + files contain + `tf.train.Example `_ + records, with one Example record for each row in the dataset. + + .. warning:: + tf.train.Feature only natively stores ints, floats, and bytes, + so this function only supports datasets with these data types, + and will error if the dataset contains unsupported types. + + The number of files is determined by the number of blocks in the dataset. + To control the number of number of blocks, call + :meth:`~ray.data.Dataset.repartition`. + + This method is only supported for datasets with records that are convertible to + pyarrow tables. + + By default, the format of the output files is ``{uuid}_{block_idx}.tfrecords``, + where ``uuid`` is a unique id for the dataset. To modify this behavior, + implement a custom :class:`~ray.data.datasource.FilenameProvider` + and pass it in as the ``filename_provider`` argument. + + Examples: + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.write_tfrecords("local:///tmp/data/") + + Time complexity: O(dataset size / parallelism) + + Args: + path: The path to the destination root directory, where tfrecords + files are written to. + filesystem: The pyarrow filesystem implementation to write to. + These filesystems are specified in the + `pyarrow docs `_. + Specify this if you need to provide specific configurations to the + filesystem. By default, the filesystem is automatically selected based + on the scheme of the paths. For example, if the path begins with + ``s3://``, the ``S3FileSystem`` is used. + try_create_dir: If ``True``, attempts to create all directories in the + destination path. Does nothing if all directories already + exist. Defaults to ``True``. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_output_stream `_, which is used when + opening the file to write to. + filename_provider: A :class:`~ray.data.datasource.FilenameProvider` + implementation. Use this parameter to customize what your filenames + look like. + min_rows_per_file: [Experimental] The target minimum number of rows to write + to each file. If ``None``, Ray Data writes a system-chosen number of + rows to each file. If the number of rows per block is larger than the + specified value, Ray Data writes the number of rows per block to each file. + The specified value is a hint, not a strict limit. Ray Data + might write more or fewer rows to each file. + ray_remote_args: kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + num_rows_per_file: [Deprecated] Use min_rows_per_file instead. + mode: Determines how to handle existing files. Valid modes are "overwrite", "error", + "ignore", "append". Defaults to "append". + NOTE: This method isn't atomic. "Overwrite" first deletes all the data + before writing to `path`. + """ + effective_min_rows, _ = _validate_rows_per_file_args( + num_rows_per_file=num_rows_per_file, min_rows_per_file=min_rows_per_file + ) + + datasink = TFRecordDatasink( + path=path, + tf_schema=tf_schema, + min_rows_per_file=effective_min_rows, + filesystem=filesystem, + try_create_dir=try_create_dir, + open_stream_args=arrow_open_stream_args, + filename_provider=filename_provider, + dataset_uuid=self._uuid, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + @PublicAPI(stability="alpha", api_group=IOC_API_GROUP) + def write_webdataset( + self, + path: str, + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + try_create_dir: bool = True, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + filename_provider: Optional[FilenameProvider] = None, + min_rows_per_file: Optional[int] = None, + ray_remote_args: Dict[str, Any] = None, + encoder: Optional[Union[bool, str, callable, list]] = True, + concurrency: Optional[int] = None, + num_rows_per_file: Optional[int] = None, + mode: SaveMode = SaveMode.APPEND, + ) -> None: + """Writes the dataset to `WebDataset `_ files. + + The `TFRecord `_ + files will contain + `tf.train.Example `_ # noqa: E501 + records, with one Example record for each row in the dataset. + + .. warning:: + tf.train.Feature only natively stores ints, floats, and bytes, + so this function only supports datasets with these data types, + and will error if the dataset contains unsupported types. + + This is only supported for datasets convertible to Arrow records. + To control the number of files, use :meth:`Dataset.repartition`. + + Unless a custom filename provider is given, the format of the output + files is ``{uuid}_{block_idx}.tfrecords``, where ``uuid`` is a unique id + for the dataset. + + Examples: + + .. testcode:: + :skipif: True + + import ray + + ds = ray.data.range(100) + ds.write_webdataset("s3://bucket/folder/") + + Time complexity: O(dataset size / parallelism) + + Args: + path: The path to the destination root directory, where tfrecords + files are written to. + filesystem: The filesystem implementation to write to. + try_create_dir: If ``True``, attempts to create all + directories in the destination path. Does nothing if all directories + already exist. Defaults to ``True``. + arrow_open_stream_args: kwargs passed to + ``pyarrow.fs.FileSystem.open_output_stream`` + filename_provider: A :class:`~ray.data.datasource.FilenameProvider` + implementation. Use this parameter to customize what your filenames + look like. + min_rows_per_file: [Experimental] The target minimum number of rows to write + to each file. If ``None``, Ray Data writes a system-chosen number of + rows to each file. If the number of rows per block is larger than the + specified value, Ray Data writes the number of rows per block to each file. + The specified value is a hint, not a strict limit. Ray Data + might write more or fewer rows to each file. + ray_remote_args: Kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + num_rows_per_file: [Deprecated] Use min_rows_per_file instead. + mode: Determines how to handle existing files. Valid modes are "overwrite", "error", + "ignore", "append". Defaults to "append". + NOTE: This method isn't atomic. "Overwrite" first deletes all the data + before writing to `path`. + """ + effective_min_rows, _ = _validate_rows_per_file_args( + num_rows_per_file=num_rows_per_file, min_rows_per_file=min_rows_per_file + ) + + datasink = WebDatasetDatasink( + path, + encoder=encoder, + min_rows_per_file=effective_min_rows, + filesystem=filesystem, + try_create_dir=try_create_dir, + open_stream_args=arrow_open_stream_args, + filename_provider=filename_provider, + dataset_uuid=self._uuid, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + @PublicAPI(api_group=IOC_API_GROUP) + def write_numpy( + self, + path: str, + *, + column: str, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + try_create_dir: bool = True, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + filename_provider: Optional[FilenameProvider] = None, + min_rows_per_file: Optional[int] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + num_rows_per_file: Optional[int] = None, + mode: SaveMode = SaveMode.APPEND, + ) -> None: + """Writes a column of the :class:`~ray.data.Dataset` to .npy files. + + This is only supported for columns in the datasets that can be converted to + NumPy arrays. + + The number of files is determined by the number of blocks in the dataset. + To control the number of number of blocks, call + :meth:`~ray.data.Dataset.repartition`. + + + By default, the format of the output files is ``{uuid}_{block_idx}.npy``, + where ``uuid`` is a unique id for the dataset. To modify this behavior, + implement a custom :class:`~ray.data.datasource.FilenameProvider` + and pass it in as the ``filename_provider`` argument. + + Examples: + >>> import ray + >>> ds = ray.data.range(100) + >>> ds.write_numpy("local:///tmp/data/", column="id") + + Time complexity: O(dataset size / parallelism) + + Args: + path: The path to the destination root directory, where + the npy files are written to. + column: The name of the column that contains the data to + be written. + filesystem: The pyarrow filesystem implementation to write to. + These filesystems are specified in the + `pyarrow docs `_. + Specify this if you need to provide specific configurations to the + filesystem. By default, the filesystem is automatically selected based + on the scheme of the paths. For example, if the path begins with + ``s3://``, the ``S3FileSystem`` is used. + try_create_dir: If ``True``, attempts to create all directories in + destination path. Does nothing if all directories already + exist. Defaults to ``True``. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_output_stream `_, which is used when + opening the file to write to. + filename_provider: A :class:`~ray.data.datasource.FilenameProvider` + implementation. Use this parameter to customize what your filenames + look like. + min_rows_per_file: [Experimental] The target minimum number of rows to write + to each file. If ``None``, Ray Data writes a system-chosen number of + rows to each file. If the number of rows per block is larger than the + specified value, Ray Data writes the number of rows per block to each file. + The specified value is a hint, not a strict limit. Ray Data + might write more or fewer rows to each file. + ray_remote_args: kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + num_rows_per_file: [Deprecated] Use min_rows_per_file instead. + mode: Determines how to handle existing files. Valid modes are "overwrite", "error", + "ignore", "append". Defaults to "append". + NOTE: This method isn't atomic. "Overwrite" first deletes all the data + before writing to `path`. + """ + effective_min_rows, _ = _validate_rows_per_file_args( + num_rows_per_file=num_rows_per_file, min_rows_per_file=min_rows_per_file + ) + + datasink = NumpyDatasink( + path, + column, + min_rows_per_file=effective_min_rows, + filesystem=filesystem, + try_create_dir=try_create_dir, + open_stream_args=arrow_open_stream_args, + filename_provider=filename_provider, + dataset_uuid=self._uuid, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + def write_sql( + self, + sql: str, + connection_factory: Callable[[], Connection], + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + ) -> None: + """Write to a database that provides a + `Python DB API2-compliant `_ connector. + + .. note:: + + This method writes data in parallel using the DB API2 ``executemany`` + method. To learn more about this method, see + `PEP 249 `_. + + Examples: + + .. testcode:: + + import sqlite3 + import ray + + connection = sqlite3.connect("example.db") + connection.cursor().execute("CREATE TABLE movie(title, year, score)") + dataset = ray.data.from_items([ + {"title": "Monty Python and the Holy Grail", "year": 1975, "score": 8.2}, + {"title": "And Now for Something Completely Different", "year": 1971, "score": 7.5} + ]) + + dataset.write_sql( + "INSERT INTO movie VALUES(?, ?, ?)", lambda: sqlite3.connect("example.db") + ) + + result = connection.cursor().execute("SELECT * FROM movie ORDER BY year") + print(result.fetchall()) + + .. testoutput:: + + [('And Now for Something Completely Different', 1971, 7.5), ('Monty Python and the Holy Grail', 1975, 8.2)] + + .. testcode:: + :hide: + + import os + os.remove("example.db") + + Arguments: + sql: An ``INSERT INTO`` statement that specifies the table to write to. The + number of parameters must match the number of columns in the table. + connection_factory: A function that takes no arguments and returns a + Python DB API2 + `Connection object `_. + ray_remote_args: Keyword arguments passed to :func:`ray.remote` in the + write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + """ # noqa: E501 + datasink = SQLDatasink(sql=sql, connection_factory=connection_factory) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @PublicAPI(stability="alpha", api_group=IOC_API_GROUP) + @ConsumptionAPI + def write_mongo( + self, + uri: str, + database: str, + collection: str, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + ) -> None: + """Writes the :class:`~ray.data.Dataset` to a MongoDB database. + + This method is only supported for datasets convertible to pyarrow tables. + + The number of parallel writes is determined by the number of blocks in the + dataset. To control the number of number of blocks, call + :meth:`~ray.data.Dataset.repartition`. + + .. warning:: + This method supports only a subset of the PyArrow's types, due to the + limitation of pymongoarrow which is used underneath. Writing unsupported + types fails on type checking. See all the supported types at: + https://mongo-arrow.readthedocs.io/en/stable/api/types.html. + + .. note:: + The records are inserted into MongoDB as new documents. If a record has + the _id field, this _id must be non-existent in MongoDB, otherwise the write + is rejected and fail (hence preexisting documents are protected from + being mutated). It's fine to not have _id field in record and MongoDB will + auto generate one at insertion. + + Examples: + + .. testcode:: + :skipif: True + + import ray + + ds = ray.data.range(100) + ds.write_mongo( + uri="mongodb://username:password@mongodb0.example.com:27017/?authSource=admin", + database="my_db", + collection="my_collection" + ) + + Args: + uri: The URI to the destination MongoDB where the dataset is + written to. For the URI format, see details in the + `MongoDB docs `_. + database: The name of the database. This database must exist otherwise + a ValueError is raised. + collection: The name of the collection in the database. This collection + must exist otherwise a ValueError is raised. + ray_remote_args: kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + + Raises: + ValueError: if ``database`` doesn't exist. + ValueError: if ``collection`` doesn't exist. + """ + datasink = MongoDatasink( + uri=uri, + database=database, + collection=collection, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + def write_bigquery( + self, + project_id: str, + dataset: str, + max_retry_cnt: int = 10, + overwrite_table: Optional[bool] = True, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + ) -> None: + """Write the dataset to a BigQuery dataset table. + + To control the number of parallel write tasks, use ``.repartition()`` + before calling this method. + + Examples: + .. testcode:: + :skipif: True + + import ray + import pandas as pd + + docs = [{"title": "BigQuery Datasource test"} for key in range(4)] + ds = ray.data.from_pandas(pd.DataFrame(docs)) + ds.write_bigquery( + project_id="my_project_id", + dataset="my_dataset_table", + overwrite_table=True + ) + + Args: + project_id: The name of the associated Google Cloud Project that hosts + the dataset to read. For more information, see details in + `Creating and managing projects `_. + dataset: The name of the dataset in the format of ``dataset_id.table_id``. + The dataset is created if it doesn't already exist. + max_retry_cnt: The maximum number of retries that an individual block write + is retried due to BigQuery rate limiting errors. This isn't + related to Ray fault tolerance retries. The default number of retries + is 10. + overwrite_table: Whether the write will overwrite the table if it already + exists. The default behavior is to overwrite the table. + ``overwrite_table=False`` will append to the table if it exists. + ray_remote_args: Kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + """ # noqa: E501 + if ray_remote_args is None: + ray_remote_args = {} + + # Each write task will launch individual remote tasks to write each block + # To avoid duplicate block writes, the write task should not be retried + if ray_remote_args.get("max_retries", 0) != 0: + warnings.warn( + "The max_retries of a BigQuery Write Task should be set to 0" + " to avoid duplicate writes." + ) + else: + ray_remote_args["max_retries"] = 0 + + datasink = BigQueryDatasink( + project_id=project_id, + dataset=dataset, + max_retry_cnt=max_retry_cnt, + overwrite_table=overwrite_table, + ) + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + def write_clickhouse( + self, + table: str, + dsn: str, + *, + mode: SinkMode = SinkMode.CREATE, + schema: Optional["pyarrow.Schema"] = None, + client_settings: Optional[Dict[str, Any]] = None, + client_kwargs: Optional[Dict[str, Any]] = None, + table_settings: Optional[ClickHouseTableSettings] = None, + max_insert_block_rows: Optional[int] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + ) -> None: + """Write the dataset to a ClickHouse dataset table. + + To control the number of parallel write tasks, use ``.repartition()`` + before calling this method. + + Examples: + .. testcode:: + :skipif: True + + import ray + import pyarrow as pa + import pandas as pd + + docs = [{"title": "ClickHouse Datasink test"} for key in range(4)] + ds = ray.data.from_pandas(pd.DataFrame(docs)) + user_schema = pa.schema( + [ + ("id", pa.int64()), + ("title", pa.string()), + ] + ) + ds.write_clickhouse( + table="default.my_table", + dsn="clickhouse+http://user:pass@localhost:8123/default", + mode=ray.data.SinkMode.OVERWRITE, + schema=user_schema, + table_settings=ray.data.ClickHouseTableSettings( + engine="ReplacingMergeTree()", + order_by="id", + ), + ) + + Args: + table: Fully qualified table identifier (e.g., "default.my_table"). + The table is created if it doesn't already exist. + dsn: A string in DSN (Data Source Name) HTTP format + (e.g., "clickhouse+http://username:password@host:8123/default"). + For more information, see `ClickHouse Connection String doc + `_. + mode: One of SinkMode.CREATE, SinkMode.APPEND, or + SinkMode.OVERWRITE: + + * SinkMode.CREATE: Create a new table; fail if it already exists. If the table + does not exist, you must provide a schema (either via the `schema` + argument or as part of the dataset's first block). + + * SinkMode.APPEND: If the table exists, append data to it; if not, create + the table using the provided or inferred schema. If the table does + not exist, you must supply a schema. + + * SinkMode.OVERWRITE: Drop any existing table of this name, then create + a new table and write data to it. You **must** provide a schema in + this case, as the table is being re-created. + + schema: Optional :class:`pyarrow.Schema` specifying column definitions. + This is mandatory if you are creating a new table (i.e., table doesn't + exist in CREATE or APPEND mode) or overwriting an existing table (OVERWRITE). + When appending to an existing table, a schema is optional, though you can + provide one to enforce column types or cast data as needed. If omitted + (and the table already exists), the existing table definition will be used. + If omitted and the table must be created, the schema is inferred from + the first block in the dataset. + client_settings: Optional ClickHouse server settings to be used with the + session/every request. For more information, see + `ClickHouse Client Settings doc + `_. + client_kwargs: Optional keyword arguments to pass to the + ClickHouse client. For more information, see + `ClickHouse Core Settings doc + `_. + table_settings: An optional :class:`ClickHouseTableSettings` dataclass + that specifies additional table creation instructions, including: + + * engine (default: `"MergeTree()"`): + Specifies the engine for the `CREATE TABLE` statement. + + * order_by: + Sets the `ORDER BY` clause in the `CREATE TABLE` statement, iff not provided. + When overwriting an existing table, its previous `ORDER BY` (if any) is reused. + Otherwise, a "best" column is selected automatically (favoring a timestamp column, + then a non-string column, and lastly the first column). + + * partition_by: + If present, adds a `PARTITION BY ` clause to the `CREATE TABLE` statement. + + * primary_key: + If present, adds a `PRIMARY KEY ()` clause. + + * settings: + Appends a `SETTINGS ` clause to the `CREATE TABLE` statement, allowing + custom ClickHouse settings. + + max_insert_block_rows: If you have extremely large blocks, specifying + a limit here will chunk the insert into multiple smaller insert calls. + Defaults to None (no chunking). + ray_remote_args: Kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + """ # noqa: E501 + datasink = ClickHouseDatasink( + table=table, + dsn=dsn, + mode=mode, + schema=schema, + client_settings=client_settings, + client_kwargs=client_kwargs, + table_settings=table_settings, + max_insert_block_rows=max_insert_block_rows, + ) + + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI + def write_lance( + self, + path: str, + *, + schema: Optional["pyarrow.Schema"] = None, + mode: Literal["create", "append", "overwrite"] = "create", + min_rows_per_file: int = 1024 * 1024, + max_rows_per_file: int = 64 * 1024 * 1024, + data_storage_version: Optional[str] = None, + storage_options: Optional[Dict[str, Any]] = None, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + ) -> None: + """Write the dataset to a Lance dataset. + + Examples: + .. testcode:: + import ray + import pandas as pd + + docs = [{"title": "Lance data sink test"} for key in range(4)] + ds = ray.data.from_pandas(pd.DataFrame(docs)) + ds.write_lance("/tmp/data/") + + Args: + path: The path to the destination Lance dataset. + schema: The schema of the dataset. If not provided, it is inferred from the data. + mode: The write mode. Can be "create", "append", or "overwrite". + min_rows_per_file: The minimum number of rows per file. + max_rows_per_file: The maximum number of rows per file. + data_storage_version: The version of the data storage format to use. Newer versions are more + efficient but require newer versions of lance to read. The default is + "legacy" which will use the legacy v1 version. See the user guide + for more details. + storage_options: The storage options for the writer. Default is None. + """ + datasink = LanceDatasink( + path, + schema=schema, + mode=mode, + min_rows_per_file=min_rows_per_file, + max_rows_per_file=max_rows_per_file, + data_storage_version=data_storage_version, + storage_options=storage_options, + ) + + self.write_datasink( + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + + @ConsumptionAPI(pattern="Time complexity:") + def write_datasink( + self, + datasink: Datasink, + *, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + ) -> None: + """Writes the dataset to a custom :class:`~ray.data.Datasink`. + + Time complexity: O(dataset size / parallelism) + + Args: + datasink: The :class:`~ray.data.Datasink` to write to. + ray_remote_args: Kwargs passed to :func:`ray.remote` in the write tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run. By default, concurrency is dynamically + decided based on the available resources. + """ # noqa: E501 + if ray_remote_args is None: + ray_remote_args = {} + + if not datasink.supports_distributed_writes: + if ray.util.client.ray.is_connected(): + raise ValueError( + "If you're using Ray Client, Ray Data won't schedule write tasks " + "on the driver's node." + ) + ray_remote_args["scheduling_strategy"] = NodeAffinitySchedulingStrategy( + ray.get_runtime_context().get_node_id(), + soft=False, + ) + + plan = self._plan.copy() + write_op = Write( + self._logical_plan.dag, + datasink, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + ) + logical_plan = LogicalPlan(write_op, self.context) + + try: + datasink.on_write_start() + if isinstance(datasink, _FileDatasink): + if not datasink.has_created_dir and datasink.mode == SaveMode.IGNORE: + logger.info( + f"Ignoring write because {datasink.path} already exists" + ) + return + + self._write_ds = Dataset(plan, logical_plan).materialize() + # TODO: Get and handle the blocks with an iterator instead of getting + # everything in a blocking way, so some blocks can be freed earlier. + raw_write_results = ray.get(self._write_ds._plan.execute().block_refs) + write_result = gen_datasink_write_result(raw_write_results) + logger.info( + "Data sink %s finished. %d rows and %s data written.", + datasink.get_name(), + write_result.num_rows, + memory_string(write_result.size_bytes), + ) + datasink.on_write_complete(write_result) + + except Exception as e: + datasink.on_write_failed(e) + raise + + @ConsumptionAPI( + delegate=( + "Calling any of the consumption methods on the returned ``DataIterator``" + ), + pattern="Returns:", + ) + @PublicAPI(api_group=CD_API_GROUP) + def iterator(self) -> DataIterator: + """Return a :class:`~ray.data.DataIterator` over this dataset. + + Don't call this method directly. Use it internally. + + Returns: + A :class:`~ray.data.DataIterator` over this dataset. + """ + return DataIteratorImpl(self) + + @ConsumptionAPI + @PublicAPI(api_group=CD_API_GROUP) + def iter_rows(self) -> Iterable[Dict[str, Any]]: + """Return an iterable over the rows in this dataset. + + Examples: + >>> import ray + >>> for row in ray.data.range(3).iter_rows(): + ... print(row) + {'id': 0} + {'id': 1} + {'id': 2} + + Time complexity: O(1) + + Returns: + An iterable over the rows in this dataset. + """ + return self.iterator().iter_rows() + + @ConsumptionAPI + @PublicAPI(api_group=CD_API_GROUP) + def iter_batches( + self, + *, + prefetch_batches: int = 1, + batch_size: Optional[int] = 256, + batch_format: Optional[str] = "default", + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + _collate_fn: Optional[Callable[[DataBatch], CollatedData]] = None, + ) -> Iterable[DataBatch]: + """Return an iterable over batches of data. + + This method is useful for model training. + + Examples: + + .. testcode:: + + import ray + + ds = ray.data.read_images("example://image-datasets/simple") + + for batch in ds.iter_batches(batch_size=2, batch_format="numpy"): + print(batch) + + .. testoutput:: + :options: +MOCK + + {'image': array([[[[...]]]], dtype=uint8)} + ... + {'image': array([[[[...]]]], dtype=uint8)} + + Time complexity: O(1) + + Args: + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool is used + to fetch the objects to the local node and format the batches. Defaults + to 1. + batch_size: The number of rows in each batch, or ``None`` to use entire + blocks as batches (blocks may contain different numbers of rows). + The final batch may include fewer than ``batch_size`` rows if + ``drop_last`` is ``False``. Defaults to 256. + batch_format: If ``"default"`` or ``"numpy"``, batches are + ``Dict[str, numpy.ndarray]``. If ``"pandas"``, batches are + ``pandas.DataFrame``. + drop_last: Whether to drop the last batch if it's incomplete. + local_shuffle_buffer_size: If not ``None``, the data is randomly shuffled + using a local in-memory shuffle buffer, and this value serves as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer are drained. + local_shuffle_seed: The seed to use for the local random shuffle. + + Returns: + An iterable over batches of data. + """ + batch_format = _apply_batch_format(batch_format) + return self.iterator()._iter_batches( + prefetch_batches=prefetch_batches, + batch_size=batch_size, + batch_format=batch_format, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + _collate_fn=_collate_fn, + ) + + @ConsumptionAPI + @PublicAPI(api_group=CD_API_GROUP) + def iter_torch_batches( + self, + *, + prefetch_batches: int = 1, + batch_size: Optional[int] = 256, + dtypes: Optional[Union["torch.dtype", Dict[str, "torch.dtype"]]] = None, + device: str = "auto", + collate_fn: Optional[Callable[[Dict[str, np.ndarray]], CollatedData]] = None, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + ) -> Iterable[TorchBatchType]: + """Return an iterable over batches of data represented as Torch tensors. + + This iterable yields batches of type ``Dict[str, torch.Tensor]``. + For more flexibility, call :meth:`~Dataset.iter_batches` and manually convert + your data to Torch tensors. + + Examples: + >>> import ray + >>> for batch in ray.data.range( + ... 12, + ... ).iter_torch_batches(batch_size=4): + ... print(batch) + {'id': tensor([0, 1, 2, 3])} + {'id': tensor([4, 5, 6, 7])} + {'id': tensor([ 8, 9, 10, 11])} + + Use the ``collate_fn`` to customize how the tensor batch is created. + + >>> from typing import Any, Dict + >>> import torch + >>> import numpy as np + >>> import ray + >>> def collate_fn(batch: Dict[str, np.ndarray]) -> Any: + ... return torch.stack( + ... [torch.as_tensor(array) for array in batch.values()], + ... axis=1 + ... ) + >>> dataset = ray.data.from_items([ + ... {"col_1": 1, "col_2": 2}, + ... {"col_1": 3, "col_2": 4}]) + >>> for batch in dataset.iter_torch_batches(collate_fn=collate_fn): + ... print(batch) + tensor([[1, 2], + [3, 4]]) + + + Time complexity: O(1) + + Args: + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool is used + to fetch the objects to the local node, format the batches, and apply + the ``collate_fn``. Defaults to 1. + batch_size: The number of rows in each batch, or ``None`` to use entire + blocks as batches (blocks may contain different number of rows). + The final batch may include fewer than ``batch_size`` rows if + ``drop_last`` is ``False``. Defaults to 256. + dtypes: The Torch dtype(s) for the created tensor(s); if ``None``, the dtype + is inferred from the tensor data. You can't use this parameter with + ``collate_fn``. + device: The device on which the tensor should be placed. Defaults to + "auto" which moves the tensors to the appropriate device when the + Dataset is passed to Ray Train and ``collate_fn`` is not provided. + Otherwise, defaults to CPU. You can't use this parameter with + ``collate_fn``. + collate_fn: A function to convert a Numpy batch to a PyTorch tensor batch. + When this parameter is specified, the user should manually handle the + host to device data transfer outside of collate_fn. + This is useful for further processing the data after it has been + batched. Potential use cases include collating along a dimension other + than the first, padding sequences of various lengths, or generally + handling batches of different length tensors. If not provided, the + default collate function is used which simply converts the batch of + numpy arrays to a batch of PyTorch tensors. This API is still + experimental and is subject to change. You can't use this parameter in + conjunction with ``dtypes`` or ``device``. + drop_last: Whether to drop the last batch if it's incomplete. + local_shuffle_buffer_size: If not ``None``, the data is randomly shuffled + using a local in-memory shuffle buffer, and this value serves as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer are drained. + ``batch_size`` must also be specified when using local shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + + Returns: + An iterable over Torch Tensor batches. + + .. seealso:: + :meth:`Dataset.iter_batches` + Call this method to manually convert your data to Torch tensors. + """ # noqa: E501 + return self.iterator().iter_torch_batches( + prefetch_batches=prefetch_batches, + batch_size=batch_size, + dtypes=dtypes, + device=device, + collate_fn=collate_fn, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + ) + + @ConsumptionAPI + @Deprecated + def iter_tf_batches( + self, + *, + prefetch_batches: int = 1, + batch_size: Optional[int] = 256, + dtypes: Optional[Union["tf.dtypes.DType", Dict[str, "tf.dtypes.DType"]]] = None, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + ) -> Iterable[TensorFlowTensorBatchType]: + """Return an iterable over batches of data represented as TensorFlow tensors. + + This iterable yields batches of type ``Dict[str, tf.Tensor]``. + For more flexibility, call :meth:`~Dataset.iter_batches` and manually convert + your data to TensorFlow tensors. + + .. tip:: + If you don't need the additional flexibility provided by this method, + consider using :meth:`~ray.data.Dataset.to_tf` instead. It's easier + to use. + + Examples: + + .. testcode:: + + import ray + + ds = ray.data.read_csv("s3://anonymous@air-example-data/iris.csv") + + tf_dataset = ds.to_tf( + feature_columns="sepal length (cm)", + label_columns="target", + batch_size=2 + ) + for features, labels in tf_dataset: + print(features, labels) + + .. testoutput:: + + tf.Tensor([5.1 4.9], shape=(2,), dtype=float64) tf.Tensor([0 0], shape=(2,), dtype=int64) + ... + tf.Tensor([6.2 5.9], shape=(2,), dtype=float64) tf.Tensor([2 2], shape=(2,), dtype=int64) + + Time complexity: O(1) + + Args: + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool is used + to fetch the objects to the local node, format the batches, and apply + the ``collate_fn``. Defaults to 1. + batch_size: The number of rows in each batch, or ``None`` to use entire + blocks as batches (blocks may contain different numbers of rows). + The final batch may include fewer than ``batch_size`` rows if + ``drop_last`` is ``False``. Defaults to 256. + dtypes: The TensorFlow dtype(s) for the created tensor(s); if ``None``, the + dtype is inferred from the tensor data. + drop_last: Whether to drop the last batch if it's incomplete. + local_shuffle_buffer_size: If not ``None``, the data is randomly shuffled + using a local in-memory shuffle buffer, and this value serves as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer are drained. + ``batch_size`` must also be specified when using local shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + + Returns: + An iterable over TensorFlow Tensor batches. + + .. seealso:: + :meth:`Dataset.iter_batches` + Call this method to manually convert your data to TensorFlow tensors. + """ # noqa: E501 + warnings.warn( + "`iter_tf_batches` is deprecated and will be removed after May 2025. Use " + "`to_tf` instead.", + DeprecationWarning, + ) + return self.iterator().iter_tf_batches( + prefetch_batches=prefetch_batches, + batch_size=batch_size, + dtypes=dtypes, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + ) + + @ConsumptionAPI(pattern="Time complexity:") + @Deprecated + def to_torch( + self, + *, + label_column: Optional[str] = None, + feature_columns: Optional[ + Union[List[str], List[List[str]], Dict[str, List[str]]] + ] = None, + label_column_dtype: Optional["torch.dtype"] = None, + feature_column_dtypes: Optional[ + Union["torch.dtype", List["torch.dtype"], Dict[str, "torch.dtype"]] + ] = None, + batch_size: int = 1, + prefetch_batches: int = 1, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + unsqueeze_label_tensor: bool = True, + unsqueeze_feature_tensors: bool = True, + ) -> "torch.utils.data.IterableDataset": + """Return a + `Torch IterableDataset `_ + over this :class:`~ray.data.Dataset`. + + This is only supported for datasets convertible to Arrow records. + + It is recommended to use the returned ``IterableDataset`` directly + instead of passing it into a torch ``DataLoader``. + + Each element in ``IterableDataset`` is a tuple consisting of 2 + elements. The first item contains the feature tensor(s), and the + second item is the label tensor. Those can take on different + forms, depending on the specified arguments. + + For the features tensor (N is the ``batch_size`` and n, m, k + are the number of features per tensor): + + * If ``feature_columns`` is a ``List[str]``, the features is + a tensor of shape (N, n), with columns corresponding to + ``feature_columns`` + + * If ``feature_columns`` is a ``List[List[str]]``, the features is + a list of tensors of shape [(N, m),...,(N, k)], with columns of each + tensor corresponding to the elements of ``feature_columns`` + + * If ``feature_columns`` is a ``Dict[str, List[str]]``, the features + is a dict of key-tensor pairs of shape + {key1: (N, m),..., keyN: (N, k)}, with columns of each + tensor corresponding to the value of ``feature_columns`` under the + key. + + If ``unsqueeze_label_tensor=True`` (default), the label tensor is + of shape (N, 1). Otherwise, it is of shape (N,). + If ``label_column`` is specified as ``None``, then no column from the + ``Dataset`` is treated as the label, and the output label tensor + is ``None``. + + Note that you probably want to call :meth:`Dataset.split` on this dataset if + there are to be multiple Torch workers consuming the data. + + Time complexity: O(1) + + Args: + label_column: The name of the column used as the + label (second element of the output list). Can be None for + prediction, in which case the second element of returned + tuple will also be None. + feature_columns: The names of the columns + to use as the features. Can be a list of lists or + a dict of string-list pairs for multi-tensor output. + If ``None``, then use all columns except the label column as + the features. + label_column_dtype: The torch dtype to + use for the label column. If ``None``, then automatically infer + the dtype. + feature_column_dtypes: The dtypes to use for the feature + tensors. This should match the format of ``feature_columns``, + or be a single dtype, in which case it is applied to + all tensors. If ``None``, then automatically infer the dtype. + batch_size: How many samples per batch to yield at a time. + Defaults to 1. + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool is used + to fetch the objects to the local node, format the batches, and apply + the collate_fn. Defaults to 1. + drop_last: Set to True to drop the last incomplete batch, + if the dataset size is not divisible by the batch size. If + False and the size of the stream is not divisible by the batch + size, then the last batch is smaller. Defaults to False. + local_shuffle_buffer_size: If non-None, the data is randomly shuffled + using a local in-memory shuffle buffer, and this value will serve as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer is drained. This + buffer size must be greater than or equal to ``batch_size``, and + therefore ``batch_size`` must also be specified when using local + shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + unsqueeze_label_tensor: If set to True, the label tensor + is unsqueezed (reshaped to (N, 1)). Otherwise, it will + be left as is, that is (N, ). In general, regression loss + functions expect an unsqueezed tensor, while classification + loss functions expect a squeezed one. Defaults to True. + unsqueeze_feature_tensors: If set to True, the features tensors + are unsqueezed (reshaped to (N, 1)) before being concatenated into + the final features tensor. Otherwise, they are left as is, that is + (N, ). Defaults to True. + + Returns: + A `Torch IterableDataset`_. + """ # noqa: E501 + warnings.warn( + "`to_torch` is deprecated and will be removed after May 2025. Use " + "`iter_torch_batches` instead.", + DeprecationWarning, + ) + return self.iterator().to_torch( + label_column=label_column, + feature_columns=feature_columns, + label_column_dtype=label_column_dtype, + feature_column_dtypes=feature_column_dtypes, + batch_size=batch_size, + prefetch_batches=prefetch_batches, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + unsqueeze_label_tensor=unsqueeze_label_tensor, + unsqueeze_feature_tensors=unsqueeze_feature_tensors, + ) + + @ConsumptionAPI + @PublicAPI(api_group=IOC_API_GROUP) + def to_tf( + self, + feature_columns: Union[str, List[str]], + label_columns: Union[str, List[str]], + *, + additional_columns: Union[str, List[str]] = None, + prefetch_batches: int = 1, + batch_size: int = 1, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + feature_type_spec: Union["tf.TypeSpec", Dict[str, "tf.TypeSpec"]] = None, + label_type_spec: Union["tf.TypeSpec", Dict[str, "tf.TypeSpec"]] = None, + additional_type_spec: Union["tf.TypeSpec", Dict[str, "tf.TypeSpec"]] = None, + ) -> "tf.data.Dataset": + """Return a `TensorFlow Dataset `_ + over this :class:`~ray.data.Dataset`. + + .. warning:: + If your :class:`~ray.data.Dataset` contains ragged tensors, this method errors. + To prevent errors, :ref:`resize your tensors `. + + Examples: + >>> import ray + >>> ds = ray.data.read_csv("s3://anonymous@air-example-data/iris.csv") + >>> ds + Dataset(num_rows=?, schema=...) + + If your model accepts a single tensor as input, specify a single feature column. + + >>> ds.to_tf(feature_columns="sepal length (cm)", label_columns="target") + <_OptionsDataset element_spec=(TensorSpec(shape=(None,), dtype=tf.float64, name='sepal length (cm)'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'))> + + If your model accepts a dictionary as input, specify a list of feature columns. + + >>> ds.to_tf(["sepal length (cm)", "sepal width (cm)"], "target") + <_OptionsDataset element_spec=({'sepal length (cm)': TensorSpec(shape=(None,), dtype=tf.float64, name='sepal length (cm)'), 'sepal width (cm)': TensorSpec(shape=(None,), dtype=tf.float64, name='sepal width (cm)')}, TensorSpec(shape=(None,), dtype=tf.int64, name='target'))> + + If your dataset contains multiple features but your model accepts a single + tensor as input, combine features with + :class:`~ray.data.preprocessors.Concatenator`. + + >>> from ray.data.preprocessors import Concatenator + >>> columns_to_concat = ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"] + >>> preprocessor = Concatenator(columns=columns_to_concat, output_column_name="features") + >>> ds = preprocessor.transform(ds) + >>> ds + Concatenator + +- Dataset(num_rows=?, schema=...) + >>> ds.to_tf("features", "target") + <_OptionsDataset element_spec=(TensorSpec(shape=(None, 4), dtype=tf.float64, name='features'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'))> + + If your model accepts different types, shapes, or names of tensors as input, specify the type spec. + If type specs are not specified, they are automatically inferred from the schema of the dataset. + + >>> import tensorflow as tf + >>> ds.to_tf( + ... feature_columns="features", + ... label_columns="target", + ... feature_type_spec=tf.TensorSpec(shape=(None, 4), dtype=tf.float32, name="features"), + ... label_type_spec=tf.TensorSpec(shape=(None,), dtype=tf.float32, name="label") + ... ) + <_OptionsDataset element_spec=(TensorSpec(shape=(None, 4), dtype=tf.float32, name='features'), TensorSpec(shape=(None,), dtype=tf.float32, name='label'))> + + If your model accepts additional metadata aside from features and label, specify a single additional column or a list of additional columns. + A common use case is to include sample weights in the data samples and train a ``tf.keras.Model`` with ``tf.keras.Model.fit``. + + >>> import pandas as pd + >>> ds = ds.add_column("sample weights", lambda df: pd.Series([1] * len(df))) + >>> ds.to_tf(feature_columns="features", label_columns="target", additional_columns="sample weights") + <_OptionsDataset element_spec=(TensorSpec(shape=(None, 4), dtype=tf.float64, name='features'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'), TensorSpec(shape=(None,), dtype=tf.int64, name='sample weights'))> + + If your model accepts different types, shapes, or names for the additional metadata, specify the type spec of the additional column. + + >>> ds.to_tf( + ... feature_columns="features", + ... label_columns="target", + ... additional_columns="sample weights", + ... additional_type_spec=tf.TensorSpec(shape=(None,), dtype=tf.float32, name="weight") + ... ) + <_OptionsDataset element_spec=(TensorSpec(shape=(None, 4), dtype=tf.float64, name='features'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'), TensorSpec(shape=(None,), dtype=tf.float32, name='weight'))> + + Args: + feature_columns: Columns that correspond to model inputs. If this is a + string, the input data is a tensor. If this is a list, the input data + is a ``dict`` that maps column names to their tensor representation. + label_columns: Columns that correspond to model targets. If this is a + string, the target data is a tensor. If this is a list, the target data + is a ``dict`` that maps column names to their tensor representation. + additional_columns: Columns that correspond to sample weights or other metadata. + If this is a string, the weight data is a tensor. If this is a list, the + weight data is a ``dict`` that maps column names to their tensor representation. + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool is used + to fetch the objects to the local node, format the batches, and apply + the collate_fn. Defaults to 1. + batch_size: Record batch size. Defaults to 1. + drop_last: Set to True to drop the last incomplete batch, + if the dataset size is not divisible by the batch size. If + False and the size of the stream is not divisible by the batch + size, then the last batch is smaller. Defaults to False. + local_shuffle_buffer_size: If non-None, the data is randomly shuffled + using a local in-memory shuffle buffer, and this value will serve as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer is drained. This + buffer size must be greater than or equal to ``batch_size``, and + therefore ``batch_size`` must also be specified when using local + shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + feature_type_spec: The `tf.TypeSpec` of `feature_columns`. If there is + only one column, specify a `tf.TypeSpec`. If there are multiple columns, + specify a ``dict`` that maps column names to their `tf.TypeSpec`. + Default is `None` to automatically infer the type of each column. + label_type_spec: The `tf.TypeSpec` of `label_columns`. If there is + only one column, specify a `tf.TypeSpec`. If there are multiple columns, + specify a ``dict`` that maps column names to their `tf.TypeSpec`. + Default is `None` to automatically infer the type of each column. + additional_type_spec: The `tf.TypeSpec` of `additional_columns`. If there + is only one column, specify a `tf.TypeSpec`. If there are multiple + columns, specify a ``dict`` that maps column names to their `tf.TypeSpec`. + Default is `None` to automatically infer the type of each column. + + Returns: + A `TensorFlow Dataset`_ that yields inputs and targets. + + .. seealso:: + + :meth:`~ray.data.Dataset.iter_tf_batches` + Call this method if you need more flexibility. + """ # noqa: E501 + + return self.iterator().to_tf( + feature_columns=feature_columns, + label_columns=label_columns, + additional_columns=additional_columns, + prefetch_batches=prefetch_batches, + drop_last=drop_last, + batch_size=batch_size, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + feature_type_spec=feature_type_spec, + label_type_spec=label_type_spec, + additional_type_spec=additional_type_spec, + ) + + @ConsumptionAPI(pattern="Time complexity:") + @PublicAPI(api_group=IOC_API_GROUP) + def to_daft(self) -> "daft.DataFrame": + """Convert this :class:`~ray.data.Dataset` into a + `Daft DataFrame `_. + + This will convert all the data inside the Ray Dataset into a Daft DataFrame in a zero-copy way + (using Arrow as the intermediate data format). + + Time complexity: O(dataset size / parallelism) + + Returns: + A `Daft DataFrame`_ created from this dataset. + """ + import daft + + return daft.from_ray_dataset(self) + + @ConsumptionAPI(pattern="Time complexity:") + @PublicAPI(api_group=IOC_API_GROUP) + def to_dask( + self, + meta: Union[ + "pandas.DataFrame", + "pandas.Series", + Dict[str, Any], + Iterable[Any], + Tuple[Any], + None, + ] = None, + verify_meta: bool = True, + ) -> "dask.dataframe.DataFrame": + """Convert this :class:`~ray.data.Dataset` into a + `Dask DataFrame `_. + + This is only supported for datasets convertible to Arrow records. + + Note that this function will set the Dask scheduler to Dask-on-Ray + globally, via the config. + + Time complexity: O(dataset size / parallelism) + + Args: + meta: An empty `pandas DataFrame`_ or `Series`_ that matches the dtypes and column + names of the stream. This metadata is necessary for many algorithms in + dask dataframe to work. For ease of use, some alternative inputs are + also available. Instead of a DataFrame, a dict of ``{name: dtype}`` or + iterable of ``(name, dtype)`` can be provided (note that the order of + the names should match the order of the columns). Instead of a series, a + tuple of ``(name, dtype)`` can be used. + By default, this is inferred from the underlying Dataset schema, + with this argument supplying an optional override. + verify_meta: If True, Dask will check that the partitions have consistent + metadata. Defaults to True. + + Returns: + A `Dask DataFrame`_ created from this dataset. + + .. _pandas DataFrame: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html + .. _Series: https://pandas.pydata.org/docs/reference/api/pandas.Series.html + """ # noqa: E501 + import dask + import dask.dataframe as dd + import pandas as pd + + try: + import pyarrow as pa + except Exception: + pa = None + + from ray.data._internal.pandas_block import PandasBlockSchema + from ray.util.client.common import ClientObjectRef + from ray.util.dask import ray_dask_get + + dask.config.set(scheduler=ray_dask_get) + + @dask.delayed + def block_to_df(block_ref: ObjectRef[Block]) -> pd.DataFrame: + if isinstance(block_ref, (ray.ObjectRef, ClientObjectRef)): + raise ValueError( + "Dataset.to_dask() must be used with Dask-on-Ray, please " + "set the Dask scheduler to ray_dask_get (located in " + "ray.util.dask)." + ) + return _block_to_df(block_ref) + + if meta is None: + from ray.data.extensions import TensorDtype + + # Infer Dask metadata from Dataset schema. + schema = self.schema(fetch_if_missing=True) + if isinstance(schema, PandasBlockSchema): + meta = pd.DataFrame( + { + col: pd.Series( + dtype=( + dtype + if not isinstance(dtype, TensorDtype) + else np.object_ + ) + ) + for col, dtype in zip(schema.names, schema.types) + } + ) + elif pa is not None and isinstance(schema, pa.Schema): + arrow_tensor_ext_types = get_arrow_extension_fixed_shape_tensor_types() + + if any( + isinstance(type_, arrow_tensor_ext_types) for type_ in schema.types + ): + meta = pd.DataFrame( + { + col: pd.Series( + dtype=( + dtype.to_pandas_dtype() + if not isinstance(dtype, arrow_tensor_ext_types) + else np.object_ + ) + ) + for col, dtype in zip(schema.names, schema.types) + } + ) + else: + meta = schema.empty_table().to_pandas() + + dfs = [] + for ref_bundle in self.iter_internal_ref_bundles(): + for block_ref in ref_bundle.block_refs: + dfs.append(block_to_df(block_ref)) + + ddf = dd.from_delayed( + dfs, + meta=meta, + verify_meta=verify_meta, + ) + return ddf + + @ConsumptionAPI(pattern="Time complexity:") + @PublicAPI(api_group=IOC_API_GROUP) + def to_mars(self) -> "mars.dataframe.DataFrame": + """Convert this :class:`~ray.data.Dataset` into a + `Mars DataFrame `_. + + Time complexity: O(dataset size / parallelism) + + Returns: + A `Mars DataFrame`_ created from this dataset. + """ # noqa: E501 + import pandas as pd + import pyarrow as pa + from mars.dataframe.datasource.read_raydataset import DataFrameReadRayDataset + from mars.dataframe.utils import parse_index + + from ray.data._internal.pandas_block import PandasBlockSchema + + refs = self.to_pandas_refs() + # remove this when https://github.com/mars-project/mars/issues/2945 got fixed + schema = self.schema() + if isinstance(schema, Schema): + schema = schema.base_schema + if isinstance(schema, PandasBlockSchema): + dtypes = pd.Series(schema.types, index=schema.names) + elif isinstance(schema, pa.Schema): + dtypes = schema.empty_table().to_pandas().dtypes + else: + raise NotImplementedError(f"Unsupported format of schema {schema}") + index_value = parse_index(pd.RangeIndex(-1)) + columns_value = parse_index(dtypes.index, store_data=True) + op = DataFrameReadRayDataset(refs=refs) + return op(index_value=index_value, columns_value=columns_value, dtypes=dtypes) + + @ConsumptionAPI(pattern="Time complexity:") + @PublicAPI(api_group=IOC_API_GROUP) + def to_modin(self) -> "modin.pandas.dataframe.DataFrame": + """Convert this :class:`~ray.data.Dataset` into a + `Modin DataFrame `_. + + This works by first converting this dataset into a distributed set of + Pandas DataFrames (using :meth:`Dataset.to_pandas_refs`). + See caveats there. Then the individual DataFrames are used to + create the Modin DataFrame using + ``modin.distributed.dataframe.pandas.partitions.from_partitions()``. + + This is only supported for datasets convertible to Arrow records. + This function induces a copy of the data. For zero-copy access to the + underlying data, consider using :meth:`.to_arrow_refs` or + :meth:`.iter_internal_ref_bundles`. + + Time complexity: O(dataset size / parallelism) + + Returns: + A `Modin DataFrame`_ created from this dataset. + """ # noqa: E501 + + from modin.distributed.dataframe.pandas.partitions import from_partitions + + pd_objs = self.to_pandas_refs() + return from_partitions(pd_objs, axis=0) + + @ConsumptionAPI(pattern="Time complexity:") + @PublicAPI(api_group=IOC_API_GROUP) + def to_spark(self, spark: "pyspark.sql.SparkSession") -> "pyspark.sql.DataFrame": + """Convert this :class:`~ray.data.Dataset` into a + `Spark DataFrame `_. + + Time complexity: O(dataset size / parallelism) + + Args: + spark: A `SparkSession`_, which must be created by RayDP (Spark-on-Ray). + + Returns: + A `Spark DataFrame`_ created from this dataset. + + .. _SparkSession: https://spark.apache.org/docs/latest/api/python/reference/pyspark.sql/api/pyspark.sql.SparkSession.html + """ # noqa: E501 + import raydp + + schema = self.schema() + if isinstance(schema, Schema): + schema = schema.base_schema + + ref_bundles = self.iter_internal_ref_bundles() + block_refs = _ref_bundles_iterator_to_block_refs_list(ref_bundles) + return raydp.spark.ray_dataset_to_spark_dataframe(spark, schema, block_refs) + + @ConsumptionAPI(pattern="Time complexity:") + @PublicAPI(api_group=IOC_API_GROUP) + def to_pandas(self, limit: int = None) -> "pandas.DataFrame": + """Convert this :class:`~ray.data.Dataset` to a single pandas DataFrame. + + This method errors if the number of rows exceeds the provided ``limit``. + To truncate the dataset beforehand, call :meth:`.limit`. + + Examples: + >>> import ray + >>> ds = ray.data.from_items([{"a": i} for i in range(3)]) + >>> ds.to_pandas() + a + 0 0 + 1 1 + 2 2 + + Time complexity: O(dataset size) + + Args: + limit: The maximum number of rows to return. An error is + raised if the dataset has more rows than this limit. Defaults to + ``None``, which means no limit. + + Returns: + A pandas DataFrame created from this dataset, containing a limited + number of rows. + + Raises: + ValueError: if the number of rows in the :class:`~ray.data.Dataset` exceeds + ``limit``. + """ + if limit is not None: + count = self.count() + if count > limit: + raise ValueError( + f"the dataset has more than the given limit of {limit} " + f"rows: {count}. If you are sure that a DataFrame with " + f"{count} rows will fit in local memory, set " + "ds.to_pandas(limit=None) to disable limits." + ) + + builder = PandasBlockBuilder() + for batch in self.iter_batches(batch_format="pandas", batch_size=None): + builder.add_block(batch) + block = builder.build() + + # `PandasBlockBuilder` creates a dataframe with internal extension types like + # 'TensorDtype'. We use the `to_pandas` method to convert these extension + # types to regular types. + return BlockAccessor.for_block(block).to_pandas() + + @ConsumptionAPI(pattern="Time complexity:") + @DeveloperAPI + def to_pandas_refs(self) -> List[ObjectRef["pandas.DataFrame"]]: + """Converts this :class:`~ray.data.Dataset` into a distributed set of Pandas + dataframes. + + One DataFrame is created for each block in this Dataset. + + This function induces a copy of the data. For zero-copy access to the + underlying data, consider using :meth:`Dataset.to_arrow_refs` or + :meth:`Dataset.iter_internal_ref_bundles`. + + Examples: + >>> import ray + >>> ds = ray.data.range(10, override_num_blocks=2) + >>> refs = ds.to_pandas_refs() + >>> len(refs) + 2 + + Time complexity: O(dataset size / parallelism) + + Returns: + A list of remote pandas DataFrames created from this dataset. + """ + + block_to_df = cached_remote_fn(_block_to_df) + pandas_refs = [] + for bundle in self.iter_internal_ref_bundles(): + for block_ref in bundle.block_refs: + pandas_refs.append(block_to_df.remote(block_ref)) + return pandas_refs + + @DeveloperAPI + def to_numpy_refs( + self, *, column: Optional[str] = None + ) -> List[ObjectRef[np.ndarray]]: + """Converts this :class:`~ray.data.Dataset` into a distributed set of NumPy + ndarrays or dictionary of NumPy ndarrays. + + This is only supported for datasets convertible to NumPy ndarrays. + This function induces a copy of the data. For zero-copy access to the + underlying data, consider using :meth:`Dataset.to_arrow_refs` or + :meth:`Dataset.iter_internal_ref_bundles`. + + Examples: + >>> import ray + >>> ds = ray.data.range(10, override_num_blocks=2) + >>> refs = ds.to_numpy_refs() + >>> len(refs) + 2 + + Time complexity: O(dataset size / parallelism) + + Args: + column: The name of the column to convert to numpy. If ``None``, all columns + are used. If multiple columns are specified, each returned + future represents a dict of ndarrays. Defaults to None. + + Returns: + A list of remote NumPy ndarrays created from this dataset. + """ + block_to_ndarray = cached_remote_fn(_block_to_ndarray) + numpy_refs = [] + for bundle in self.iter_internal_ref_bundles(): + for block_ref in bundle.block_refs: + numpy_refs.append(block_to_ndarray.remote(block_ref, column=column)) + return numpy_refs + + @ConsumptionAPI(pattern="Time complexity:") + @DeveloperAPI + def to_arrow_refs(self) -> List[ObjectRef["pyarrow.Table"]]: + """Convert this :class:`~ray.data.Dataset` into a distributed set of PyArrow + tables. + + One PyArrow table is created for each block in this Dataset. + + This method is only supported for datasets convertible to PyArrow tables. + This function is zero-copy if the existing data is already in PyArrow + format. Otherwise, the data is converted to PyArrow format. + + Examples: + >>> import ray + >>> ds = ray.data.range(10, override_num_blocks=2) + >>> refs = ds.to_arrow_refs() + >>> len(refs) + 2 + + Time complexity: O(1) unless conversion is required. + + Returns: + A list of remote PyArrow tables created from this dataset. + """ + import pyarrow as pa + + ref_bundles: Iterator[RefBundle] = self.iter_internal_ref_bundles() + block_refs: List[ + ObjectRef["pyarrow.Table"] + ] = _ref_bundles_iterator_to_block_refs_list(ref_bundles) + # Schema is safe to call since we have already triggered execution with + # iter_internal_ref_bundles. + schema = self.schema(fetch_if_missing=True) + if isinstance(schema, Schema): + schema = schema.base_schema + if isinstance(schema, pa.Schema): + # Zero-copy path. + return block_refs + + block_to_arrow = cached_remote_fn(_block_to_arrow) + return [block_to_arrow.remote(block) for block in block_refs] + + @ConsumptionAPI(pattern="Args:") + def to_random_access_dataset( + self, + key: str, + num_workers: Optional[int] = None, + ) -> RandomAccessDataset: + """Convert this dataset into a distributed RandomAccessDataset (EXPERIMENTAL). + + RandomAccessDataset partitions the dataset across the cluster by the given + sort key, providing efficient random access to records via binary search. A + number of worker actors are created, each of which has zero-copy access to the + underlying sorted data blocks of the dataset. + + Note that the key must be unique in the dataset. If there are duplicate keys, + an arbitrary value is returned. + + This is only supported for Arrow-format datasets. + + Args: + key: The key column over which records can be queried. + num_workers: The number of actors to use to serve random access queries. + By default, this is determined by multiplying the number of Ray nodes + in the cluster by four. As a rule of thumb, you can expect each worker + to provide ~3000 records / second via ``get_async()``, and + ~10000 records / second via ``multiget()``. + """ + if num_workers is None: + num_workers = 4 * len(ray.nodes()) + return RandomAccessDataset(self, key, num_workers=num_workers) + + @ConsumptionAPI(pattern="store memory.", insert_after=True) + @PublicAPI(api_group=E_API_GROUP) + def materialize(self) -> "MaterializedDataset": + """Execute and materialize this dataset into object store memory. + + This can be used to read all blocks into memory. By default, Dataset + doesn't read blocks from the datasource until the first transform. + + Note that this does not mutate the original Dataset. Only the blocks of the + returned MaterializedDataset class are pinned in memory. + + Examples: + >>> import ray + >>> ds = ray.data.range(10) + >>> materialized_ds = ds.materialize() + >>> materialized_ds + MaterializedDataset(num_blocks=..., num_rows=10, schema={id: int64}) + + Returns: + A MaterializedDataset holding the materialized data blocks. + """ + copy = Dataset.copy(self, _deep_copy=True, _as=MaterializedDataset) + + bundle: RefBundle = copy._plan.execute() + blocks_with_metadata = bundle.blocks + + # TODO(hchen): Here we generate the same number of blocks as + # the original Dataset. Because the old code path does this, and + # some unit tests implicily depend on this behavior. + # After we remove the old code path, we should consider merging + # some blocks for better perf. + ref_bundles = [ + RefBundle( + blocks=[block_with_metadata], + owns_blocks=False, + schema=bundle.schema, + ) + for block_with_metadata in blocks_with_metadata + ] + logical_plan = LogicalPlan(InputData(input_data=ref_bundles), self.context) + output = MaterializedDataset( + ExecutionPlan(copy._plan.stats(), data_context=copy.context), + logical_plan, + ) + # Metrics are tagged with `copy`s uuid, update the output uuid with + # this so the user can access the metrics label. + output.set_name(copy.name) + output._set_uuid(copy._get_uuid()) + output._plan.execute() # No-op that marks the plan as fully executed. + return output + + @PublicAPI(api_group=IM_API_GROUP) + def stats(self) -> str: + """Returns a string containing execution timing information. + + Note that this does not trigger execution, so if the dataset has not yet + executed, an empty string is returned. + + Examples: + + .. testcode:: + + import ray + + ds = ray.data.range(10) + assert ds.stats() == "" + + ds = ds.materialize() + print(ds.stats()) + + .. testoutput:: + :options: +MOCK + + Operator 0 Read: 1 tasks executed, 5 blocks produced in 0s + * Remote wall time: 16.29us min, 7.29ms max, 1.21ms mean, 24.17ms total + * Remote cpu time: 16.0us min, 2.54ms max, 810.45us mean, 16.21ms total + * Peak heap memory usage (MiB): 137968.75 min, 142734.38 max, 139846 mean + * Output num rows: 0 min, 1 max, 0 mean, 10 total + * Output size bytes: 0 min, 8 max, 4 mean, 80 total + * Tasks per node: 20 min, 20 max, 20 mean; 1 nodes used + + """ + if self._current_executor: + return self._current_executor.get_stats().to_summary().to_string() + elif self._write_ds is not None and self._write_ds._plan.has_computed_output(): + return self._write_ds.stats() + return self._get_stats_summary().to_string() + + def _get_stats_summary(self) -> DatasetStatsSummary: + return self._plan.stats().to_summary() + + @ConsumptionAPI(pattern="Examples:") + @DeveloperAPI + def iter_internal_ref_bundles(self) -> Iterator[RefBundle]: + """Get an iterator over ``RefBundles`` + belonging to this Dataset. Calling this function doesn't keep + the data materialized in-memory. + + Examples: + >>> import ray + >>> ds = ray.data.range(1) + >>> for ref_bundle in ds.iter_internal_ref_bundles(): + ... for block_ref, block_md in ref_bundle.blocks: + ... block = ray.get(block_ref) + + Returns: + An iterator over this Dataset's ``RefBundles``. + """ + iter_ref_bundles, _, _ = self._plan.execute_to_iterator() + self._synchronize_progress_bar() + + return iter_ref_bundles + + @Deprecated + @ConsumptionAPI(pattern="Examples:") + def get_internal_block_refs(self) -> List[ObjectRef[Block]]: + """Get a list of references to the underlying blocks of this dataset. + + This function can be used for zero-copy access to the data. It blocks + until the underlying blocks are computed. + + Examples: + >>> import ray + >>> ds = ray.data.range(1) + >>> ds.get_internal_block_refs() + [ObjectRef(...)] + + Returns: + A list of references to this dataset's blocks. + """ + logger.warning( + "`Dataset.get_internal_block_refs()` is deprecated. Use " + "`Dataset.iter_internal_ref_bundles()` instead.", + ) + block_refs = self._plan.execute().block_refs + self._synchronize_progress_bar() + return block_refs + + @DeveloperAPI + def has_serializable_lineage(self) -> bool: + """Whether this dataset's lineage is able to be serialized for storage and + later deserialized, possibly on a different cluster. + + Only datasets that are created from data that we know will still exist at + deserialization time, e.g. data external to this Ray cluster such as persistent + cloud object stores, support lineage-based serialization. All of the + ray.data.read_*() APIs support lineage-based serialization. + + Examples: + + >>> import ray + >>> ray.data.from_items(list(range(10))).has_serializable_lineage() + False + >>> ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv").has_serializable_lineage() + True + """ # noqa: E501 + return all( + op.is_lineage_serializable() + for op in self._logical_plan.dag.post_order_iter() + ) + + @DeveloperAPI + def serialize_lineage(self) -> bytes: + """ + Serialize this dataset's lineage, not the actual data or the existing data + futures, to bytes that can be stored and later deserialized, possibly on a + different cluster. + + Note that this uses pickle and will drop all computed data, and that everything + is recomputed from scratch after deserialization. + + Use :py:meth:`Dataset.deserialize_lineage` to deserialize the serialized + bytes returned from this method into a Dataset. + + .. note:: + Unioned and zipped datasets, produced by :py:meth`Dataset.union` and + :py:meth:`Dataset.zip`, are not lineage-serializable. + + Examples: + + .. testcode:: + + import ray + + ds = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + serialized_ds = ds.serialize_lineage() + ds = ray.data.Dataset.deserialize_lineage(serialized_ds) + print(ds) + + .. testoutput:: + + Dataset(num_rows=?, schema=...) + + + Returns: + Serialized bytes containing the lineage of this dataset. + """ + if not self.has_serializable_lineage(): + raise ValueError( + "Lineage-based serialization is not supported for this stream, which " + "means that it cannot be used as a tunable hyperparameter. " + "Lineage-based serialization is explicitly NOT supported for unioned " + "or zipped datasets (see docstrings for those methods), and is only " + "supported for datasets created from data that we know will still " + "exist at deserialization time, e.g. external data in persistent cloud " + "object stores or in-memory data from long-lived clusters. Concretely, " + "all ray.data.read_*() APIs should support lineage-based " + "serialization, while all of the ray.data.from_*() APIs do not. To " + "allow this stream to be serialized to storage, write the data to an " + "external store (such as AWS S3, GCS, or Azure Blob Storage) using the " + "Dataset.write_*() APIs, and serialize a new dataset reading " + "from the external store using the ray.data.read_*() APIs." + ) + # Copy Dataset and clear the blocks from the execution plan so only the + # Dataset's lineage is serialized. + plan_copy = self._plan.deep_copy() + logical_plan_copy = copy.copy(self._plan._logical_plan) + ds = Dataset(plan_copy, logical_plan_copy) + ds._plan.clear_snapshot() + ds._set_uuid(self._get_uuid()) + + def _reduce_remote_fn(rf: ray.remote_function.RemoteFunction): + # Custom reducer for Ray remote function handles that allows for + # cross-cluster serialization. + # This manually unsets the last export session and job to force re-exporting + # of the function when the handle is deserialized on a new cluster. + # TODO(Clark): Fix this in core Ray, see issue: + # https://github.com/ray-project/ray/issues/24152. + reconstructor, args, state = rf.__reduce__() + state["_last_export_session_and_job"] = None + return reconstructor, args, state + + context = ray._private.worker.global_worker.get_serialization_context() + try: + context._register_cloudpickle_reducer( + ray.remote_function.RemoteFunction, _reduce_remote_fn + ) + serialized = pickle.dumps(ds) + finally: + context._unregister_cloudpickle_reducer(ray.remote_function.RemoteFunction) + return serialized + + @staticmethod + @DeveloperAPI + def deserialize_lineage(serialized_ds: bytes) -> "Dataset": + """ + Deserialize the provided lineage-serialized Dataset. + + This uses pickle, and assumes that the provided serialized bytes were + serialized using :py:meth:`Dataset.serialize_lineage`. + + Examples: + + .. testcode:: + + import ray + + ds = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + serialized_ds = ds.serialize_lineage() + ds = ray.data.Dataset.deserialize_lineage(serialized_ds) + print(ds) + + .. testoutput:: + + Dataset(num_rows=?, schema=...) + + Args: + serialized_ds: The serialized Dataset that we wish to deserialize. + + Returns: + A deserialized ``Dataset`` instance. + """ + return pickle.loads(serialized_ds) + + @property + @DeveloperAPI + def context(self) -> DataContext: + """Return the DataContext used to create this Dataset.""" + return self._plan._context + + def _aggregate_on( + self, agg_cls: type, on: Optional[Union[str, List[str]]], *args, **kwargs + ): + """Helper for aggregating on a particular subset of the dataset. + + This validates the `on` argument, and converts a list of column names + or lambdas to a multi-aggregation. A null `on` results in a + multi-aggregation on all columns for an Arrow Dataset, and a single + aggregation on the entire row for a simple Dataset. + """ + aggs = self._build_multicolumn_aggs(agg_cls, on, *args, **kwargs) + return self.aggregate(*aggs) + + def _build_multicolumn_aggs( + self, + agg_cls: type, + on: Optional[Union[str, List[str]]], + *args, + skip_cols: Optional[List[str]] = None, + **kwargs, + ): + """Build set of aggregations for applying a single aggregation to + multiple columns. + """ + # Expand None into an aggregation for each column. + if on is None: + schema = self.schema(fetch_if_missing=True) + if schema is not None and not isinstance(schema, type): + if not skip_cols: + skip_cols = [] + if len(schema.names) > 0: + on = [col for col in schema.names if col not in skip_cols] + + if not isinstance(on, list): + on = [on] + + if len(on) == 0: + raise ValueError("At least 1 column to aggregate on has to be provided") + + return [agg_cls(on_, *args, **kwargs) for on_ in on] + + def _aggregate_result(self, result: Union[Tuple, Mapping]) -> U: + if result is not None and len(result) == 1: + if isinstance(result, tuple): + return result[0] + else: + # NOTE (kfstorm): We cannot call `result[0]` directly on + # `PandasRow` because indexing a column with position is not + # supported by pandas. + return list(result.values())[0] + else: + return result + + @repr_with_fallback(["ipywidgets", "8"]) + def _repr_mimebundle_(self, **kwargs): + """Return a mimebundle with an ipywidget repr and a simple text repr. + + Depending on the frontend where the data is being displayed, + different mimetypes are used from this bundle. + See https://ipython.readthedocs.io/en/stable/config/integrating.html + for information about this method, and + https://ipywidgets.readthedocs.io/en/latest/embedding.html + for more information about the jupyter widget mimetype. + + Returns: + A mimebundle containing an ipywidget repr and a simple text repr. + """ + import ipywidgets + + title = ipywidgets.HTML(f"

    {self.__class__.__name__}

    ") + tab = self._tab_repr_() + widget = ipywidgets.VBox([title, tab], layout=ipywidgets.Layout(width="100%")) + + # Get the widget mime bundle, but replace the plaintext + # with the Datastream repr + bundle = widget._repr_mimebundle_(**kwargs) + bundle.update( + { + "text/plain": repr(self), + } + ) + return bundle + + def _tab_repr_(self): + from ipywidgets import HTML, Tab + + metadata = { + "num_blocks": self._plan.initial_num_blocks(), + "num_rows": self._meta_count(), + } + # Show metadata if available, but don't trigger execution. + schema = self.schema(fetch_if_missing=False) + if schema is None: + schema_repr = Template("rendered_html_common.html.j2").render( + content="
    Unknown schema
    " + ) + elif isinstance(schema, type): + schema_repr = Template("rendered_html_common.html.j2").render( + content=f"
    Data type: {html.escape(str(schema))}
    " + ) + else: + schema_data = {} + for sname, stype in zip(schema.names, schema.types): + schema_data[sname] = getattr(stype, "__name__", str(stype)) + + schema_repr = Template("scrollableTable.html.j2").render( + table=tabulate( + tabular_data=schema_data.items(), + tablefmt="html", + showindex=False, + headers=["Name", "Type"], + ), + max_height="300px", + ) + + children = [] + children.append( + HTML( + Template("scrollableTable.html.j2").render( + table=tabulate( + tabular_data=metadata.items(), + tablefmt="html", + showindex=False, + headers=["Field", "Value"], + ), + max_height="300px", + ) + ) + ) + children.append(HTML(schema_repr)) + return Tab(children, titles=["Metadata", "Schema"]) + + def __repr__(self) -> str: + return self._plan.get_plan_as_string(self.__class__) + + def __str__(self) -> str: + return repr(self) + + def __bool__(self) -> bool: + # Prevents `__len__` from being called to check if it is None + # see: issue #25152 + return True + + def __len__(self) -> int: + raise AttributeError( + "Use `ds.count()` to compute the length of a distributed Dataset. " + "This may be an expensive operation." + ) + + def __iter__(self): + raise TypeError( + "`Dataset` objects aren't iterable. To iterate records, call " + "`ds.iter_rows()` or `ds.iter_batches()`. For more information, read " + "https://docs.ray.io/en/latest/data/iterating-over-data.html." + ) + + def _block_num_rows(self) -> List[int]: + get_num_rows = cached_remote_fn(_get_num_rows) + num_rows = [] + for ref_bundle in self.iter_internal_ref_bundles(): + for block_ref in ref_bundle.block_refs: + num_rows.append(get_num_rows.remote(block_ref)) + return ray.get(num_rows) + + def _meta_count(self) -> Optional[int]: + return self._plan.meta_count() + + def _get_uuid(self) -> str: + return self._uuid + + def _set_uuid(self, uuid: str) -> None: + self._uuid = uuid + self._plan._dataset_uuid = uuid + self._plan._in_stats.dataset_uuid = uuid + + def _synchronize_progress_bar(self): + """Flush progress bar output by shutting down the current executor. + + This should be called at the end of all blocking APIs (e.g., `take`), but not + async APIs (e.g., `iter_batches`). + + The streaming executor runs in a separate generator / thread, so it is + possible the shutdown logic runs even after a call to retrieve rows from the + stream has finished. Explicit shutdown avoids this, which can clobber console + output (https://github.com/ray-project/ray/issues/32414). + """ + if self._current_executor: + # NOTE: This method expected to have executor fully shutdown upon returning + # from this method + self._current_executor.shutdown(force=True) + self._current_executor = None + + def _execute_to_iterator(self) -> Tuple[Iterator[RefBundle], DatasetStats]: + bundle_iter, stats, executor = self._plan.execute_to_iterator() + # Capture current executor to be able to clean it up properly, once + # dataset is garbage-collected + self._current_executor = executor + + return bundle_iter, stats + + def __getstate__(self): + # Note: excludes _current_executor which is not serializable. + return { + "plan": self._plan, + "uuid": self._uuid, + "logical_plan": self._logical_plan, + } + + def __setstate__(self, state): + self._plan = state["plan"] + self._uuid = state["uuid"] + self._logical_plan = state["logical_plan"] + self._current_executor = None + + def __del__(self): + if not self._current_executor: + return + + # When Python shuts down, `ray` might evaluate to ``. + # This value is truthy and not `None`, so we use a try-catch in addition to + # `if ray is not None`. For more information, see #42382. + try: + if ray is not None and ray.is_initialized(): + # NOTE: Upon garbage-collection we're allowing running tasks + # to be terminated asynchronously (ie avoid unnecessary + # synchronization on their completion) + self._current_executor.shutdown(force=False) + except TypeError: + pass + + +@PublicAPI +class MaterializedDataset(Dataset, Generic[T]): + """A Dataset materialized in Ray memory, e.g., via `.materialize()`. + + The blocks of a MaterializedDataset object are materialized into Ray object store + memory, which means that this class can be shared or iterated over by multiple Ray + tasks without re-executing the underlying computations for producing the stream. + """ + + def num_blocks(self) -> int: + """Return the number of blocks of this :class:`MaterializedDataset`. + + Examples: + >>> import ray + >>> ds = ray.data.range(100).repartition(10).materialize() + >>> ds.num_blocks() + 10 + + Time complexity: O(1) + + Returns: + The number of blocks of this :class:`Dataset`. + """ + return self._plan.initial_num_blocks() + + +@PublicAPI(stability="beta") +class Schema: + """Dataset schema. + + Attributes: + base_schema: The underlying Arrow or Pandas schema. + """ + + def __init__( + self, + base_schema: Union["pyarrow.lib.Schema", "PandasBlockSchema"], + *, + data_context: Optional[DataContext] = None, + ): + self.base_schema = base_schema + + # Snapshot the current context, so that the config of Datasets is always + # determined by the config at the time it was created. + self._context = data_context or copy.deepcopy(DataContext.get_current()) + + @property + def names(self) -> List[str]: + """Lists the columns of this Dataset.""" + return self.base_schema.names + + @property + def types(self) -> List[Union[type[object], "pyarrow.lib.DataType"]]: + """Lists the types of this Dataset in Arrow format + + For non-Arrow compatible types, we return "object". + """ + import pyarrow as pa + + from ray.data.extensions import ArrowTensorType, TensorDtype + + if isinstance(self.base_schema, pa.lib.Schema): + return list(self.base_schema.types) + + arrow_types = [] + for dtype in self.base_schema.types: + if isinstance(dtype, TensorDtype): + if self._context.use_arrow_tensor_v2: + pa_tensor_type_class = ArrowTensorTypeV2 + else: + pa_tensor_type_class = ArrowTensorType + + # Manually convert our Pandas tensor extension type to Arrow. + arrow_types.append( + pa_tensor_type_class( + shape=dtype._shape, dtype=pa.from_numpy_dtype(dtype._dtype) + ) + ) + + else: + try: + arrow_types.append(pa.from_numpy_dtype(dtype)) + except pa.ArrowNotImplementedError: + arrow_types.append(object) + except Exception: + logger.exception(f"Error converting dtype {dtype} to Arrow.") + arrow_types.append(None) + return arrow_types + + def __eq__(self, other): + return ( + isinstance(other, Schema) + and other.types == self.types + and other.names == self.names + ) + + def __repr__(self): + column_width = max([len(name) for name in self.names] + [len("Column")]) + padding = 2 + + output = "Column" + output += " " * ((column_width + padding) - len("Column")) + output += "Type\n" + + output += "-" * len("Column") + output += " " * ((column_width + padding) - len("Column")) + output += "-" * len("Type") + "\n" + + for name, type in zip(self.names, self.types): + output += name + output += " " * ((column_width + padding) - len(name)) + output += f"{type}\n" + + output = output.rstrip() + return output + + +def _block_to_df(block: Block) -> "pandas.DataFrame": + block = BlockAccessor.for_block(block) + return block.to_pandas() + + +def _block_to_ndarray(block: Block, column: Optional[str]): + block = BlockAccessor.for_block(block) + return block.to_numpy(column) + + +def _block_to_arrow(block: Block): + block = BlockAccessor.for_block(block) + return block.to_arrow() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/exceptions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..f3f79b83f9cf07afedf00bfc208adde5421450d4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/exceptions.py @@ -0,0 +1,91 @@ +import logging +from typing import Callable + +from ray.data._internal.logging import get_log_directory +from ray.data.context import DataContext +from ray.exceptions import UserCodeException +from ray.util import log_once +from ray.util.annotations import DeveloperAPI +from ray.util.rpdb import _is_ray_debugger_post_mortem_enabled + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class RayDataUserCodeException(UserCodeException): + """Represents an Exception originating from user code, e.g. + user-specified UDF used in a Ray Data transformation. + + By default, the frames corresponding to Ray Data internal files are + omitted from the stack trace logged to stdout, but will still be + emitted to the Ray Data specific log file. To emit all stack frames to stdout, + set `DataContext.log_internal_stack_trace_to_stdout` to True.""" + + pass + + +@DeveloperAPI +class SystemException(Exception): + """Represents an Exception originating from Ray Data internal code + or Ray Core private code paths, as opposed to user code. When + Exceptions of this form are raised, it likely indicates a bug + in Ray Data or Ray Core.""" + + pass + + +@DeveloperAPI +def omit_traceback_stdout(fn: Callable) -> Callable: + """Decorator which runs the function, and if there is an exception raised, + drops the stack trace before re-raising the exception. The original exception, + including the full unmodified stack trace, is always written to the Ray Data + log file at `data_exception_logger._log_path`. + + This is useful for stripping long stack traces of internal Ray Data code, + which can otherwise obfuscate user code errors.""" + + def handle_trace(*args, **kwargs): + try: + return fn(*args, **kwargs) + except Exception as e: + # Only log the full internal stack trace to stdout when configured + # via DataContext, or when the Ray Debugger is enabled. + # The full stack trace will always be emitted to the Ray Data log file. + log_to_stdout = DataContext.get_current().log_internal_stack_trace_to_stdout + if _is_ray_debugger_post_mortem_enabled(): + logger.exception("Full stack trace:") + raise e + + is_user_code_exception = isinstance(e, UserCodeException) + if is_user_code_exception: + # Exception has occurred in user code. + if not log_to_stdout and log_once("ray_data_exception_internal_hidden"): + logger.error( + "Exception occurred in user code, with the abbreviated stack " + "trace below. By default, the Ray Data internal stack trace " + "is omitted from stdout, and only written to the Ray Data log " + f"files at `{get_log_directory()}`. To " + "output the full stack trace to stdout, set " + "`DataContext.log_internal_stack_trace_to_stdout` to True." + ) + else: + # Exception has occurred in internal Ray Data / Ray Core code. + logger.error( + "Exception occurred in Ray Data or Ray Core internal code. " + "If you continue to see this error, please open an issue on " + "the Ray project GitHub page with the full stack trace below: " + "https://github.com/ray-project/ray/issues/new/choose" + ) + + should_hide_traceback = is_user_code_exception and not log_to_stdout + logger.exception( + "Full stack trace:", + exc_info=True, + extra={"hide": should_hide_traceback}, + ) + if is_user_code_exception: + raise e.with_traceback(None) + else: + raise e.with_traceback(None) from SystemException() + + return handle_trace diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/grouped_data.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/grouped_data.py new file mode 100644 index 0000000000000000000000000000000000000000..0771c6bac3f69e4cf26b5ae45947192acfb30602 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/grouped_data.py @@ -0,0 +1,570 @@ +from functools import partial +from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, Tuple, Union + +from ray.data._internal.compute import ComputeStrategy +from ray.data._internal.logical.interfaces import LogicalPlan +from ray.data._internal.logical.operators.all_to_all_operator import Aggregate +from ray.data.aggregate import AggregateFn, Count, Max, Mean, Min, Std, Sum +from ray.data.block import ( + Block, + BlockAccessor, + CallableClass, + DataBatch, + UserDefinedFunction, +) +from ray.data.context import ShuffleStrategy +from ray.data.dataset import Dataset +from ray.util.annotations import PublicAPI + +CDS_API_GROUP = "Computations or Descriptive Stats" +FA_API_GROUP = "Function Application" + + +class GroupedData: + """Represents a grouped dataset created by calling ``Dataset.groupby()``. + + The actual groupby is deferred until an aggregation is applied. + """ + + def __init__( + self, + dataset: Dataset, + key: Optional[Union[str, List[str]]], + *, + num_partitions: Optional[int], + ): + """Construct a dataset grouped by key (internal API). + + The constructor is not part of the GroupedData API. + Use the ``Dataset.groupby()`` method to construct one. + """ + self._dataset: Dataset = dataset + self._key: Optional[Union[str, List[str]]] = key + self._num_partitions: Optional[int] = num_partitions + + def __repr__(self) -> str: + return ( + f"{self.__class__.__name__}(dataset={self._dataset}, " f"key={self._key!r})" + ) + + @PublicAPI(api_group=FA_API_GROUP) + def aggregate(self, *aggs: AggregateFn) -> Dataset: + """Implements an accumulator-based aggregation. + + Args: + aggs: Aggregations to do. + + Returns: + The output is an dataset of ``n + 1`` columns where the first column + is the groupby key and the second through ``n + 1`` columns are the + results of the aggregations. + If groupby key is ``None`` then the key part of return is omitted. + """ + + plan = self._dataset._plan.copy() + op = Aggregate( + self._dataset._logical_plan.dag, + key=self._key, + aggs=aggs, + num_partitions=self._num_partitions, + ) + logical_plan = LogicalPlan(op, self._dataset.context) + return Dataset( + plan, + logical_plan, + ) + + def _aggregate_on( + self, + agg_cls: type, + on: Union[str, List[str]], + *args, + **kwargs, + ): + """Helper for aggregating on a particular subset of the dataset. + + This validates the `on` argument, and converts a list of column names + to a multi-aggregation. A null `on` results in a + multi-aggregation on all columns for an Arrow Dataset, and a single + aggregation on the entire row for a simple Dataset. + """ + aggs = self._dataset._build_multicolumn_aggs( + agg_cls, on, *args, skip_cols=self._key, **kwargs + ) + return self.aggregate(*aggs) + + @PublicAPI(api_group=FA_API_GROUP) + def map_groups( + self, + fn: UserDefinedFunction[DataBatch, DataBatch], + *, + zero_copy_batch: bool = False, + compute: Union[str, ComputeStrategy] = None, + batch_format: Optional[str] = "default", + fn_args: Optional[Iterable[Any]] = None, + fn_kwargs: Optional[Dict[str, Any]] = None, + fn_constructor_args: Optional[Iterable[Any]] = None, + fn_constructor_kwargs: Optional[Dict[str, Any]] = None, + num_cpus: Optional[float] = None, + num_gpus: Optional[float] = None, + memory: Optional[float] = None, + concurrency: Optional[Union[int, Tuple[int, int]]] = None, + ray_remote_args_fn: Optional[Callable[[], Dict[str, Any]]] = None, + **ray_remote_args, + ) -> "Dataset": + """Apply the given function to each group of records of this dataset. + + While map_groups() is very flexible, note that it comes with downsides: + + * It may be slower than using more specific methods such as min(), max(). + * It requires that each group fits in memory on a single node. + + In general, prefer to use `aggregate()` instead of `map_groups()`. + + .. warning:: + Specifying both ``num_cpus`` and ``num_gpus`` for map tasks is experimental, + and may result in scheduling or stability issues. Please + `report any issues `_ + to the Ray team. + + Examples: + >>> # Return a single record per group (list of multiple records in, + >>> # list of a single record out). + >>> import ray + >>> import pandas as pd + >>> import numpy as np + >>> # Get first value per group. + >>> ds = ray.data.from_items([ # doctest: +SKIP + ... {"group": 1, "value": 1}, + ... {"group": 1, "value": 2}, + ... {"group": 2, "value": 3}, + ... {"group": 2, "value": 4}]) + >>> ds.groupby("group").map_groups( # doctest: +SKIP + ... lambda g: {"result": np.array([g["value"][0]])}) + + >>> # Return multiple records per group (dataframe in, dataframe out). + >>> df = pd.DataFrame( + ... {"A": ["a", "a", "b"], "B": [1, 1, 3], "C": [4, 6, 5]} + ... ) + >>> ds = ray.data.from_pandas(df) # doctest: +SKIP + >>> grouped = ds.groupby("A") # doctest: +SKIP + >>> grouped.map_groups( # doctest: +SKIP + ... lambda g: g.apply( + ... lambda c: c / g[c.name].sum() if c.name in ["B", "C"] else c + ... ) + ... ) # doctest: +SKIP + + Args: + fn: The function to apply to each group of records, or a class type + that can be instantiated to create such a callable. It takes as + input a batch of all records from a single group, and returns a + batch of zero or more records, similar to map_batches(). + zero_copy_batch: If True, each group of rows (batch) will be provided w/o + making an additional copy. + compute: This argument is deprecated. Use ``concurrency`` argument. + batch_format: Specify ``"default"`` to use the default block format + (NumPy), ``"pandas"`` to select ``pandas.DataFrame``, "pyarrow" to + select ``pyarrow.Table``, or ``"numpy"`` to select + ``Dict[str, numpy.ndarray]``, or None to return the underlying block + exactly as is with no additional formatting. + fn_args: Arguments to `fn`. + fn_kwargs: Keyword arguments to `fn`. + fn_constructor_args: Positional arguments to pass to ``fn``'s constructor. + You can only provide this if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + fn_constructor_kwargs: Keyword arguments to pass to ``fn``'s constructor. + This can only be provided if ``fn`` is a callable class. These arguments + are top-level arguments in the underlying Ray actor construction task. + num_cpus: The number of CPUs to reserve for each parallel map worker. + num_gpus: The number of GPUs to reserve for each parallel map worker. For + example, specify `num_gpus=1` to request 1 GPU for each parallel map + worker. + memory: The heap memory in bytes to reserve for each parallel map worker. + ray_remote_args_fn: A function that returns a dictionary of remote args + passed to each map worker. The purpose of this argument is to generate + dynamic arguments for each actor or task, and will be called each time prior + to initializing the worker. Args returned from this dict will always + override the args in ``ray_remote_args``. Note: this is an advanced, + experimental feature. + concurrency: The semantics of this argument depend on the type of ``fn``: + + * If ``fn`` is a function and ``concurrency`` isn't set (default), the + actual concurrency is implicitly determined by the available + resources and number of input blocks. + + * If ``fn`` is a function and ``concurrency`` is an int ``n``, Ray Data + launches *at most* ``n`` concurrent tasks. + + * If ``fn`` is a class and ``concurrency`` is an int ``n``, Ray Data + uses an actor pool with *exactly* ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` is a tuple ``(m, n)``, Ray + Data uses an autoscaling actor pool from ``m`` to ``n`` workers. + + * If ``fn`` is a class and ``concurrency`` isn't set (default), this + method raises an error. + + ray_remote_args: Additional resource requirements to request from + Ray (e.g., num_gpus=1 to request GPUs for the map tasks). See + :func:`ray.remote` for details. + + Returns: + The return type is determined by the return type of ``fn``, and the return + value is combined from results of all groups. + + .. seealso:: + + :meth:`GroupedData.aggregate` + Use this method for common aggregation use cases. + """ + + # Prior to applying map operation we have to shuffle the data based on provided + # key and (optionally) number of partitions + # + # - In case key is none, we repartition into a single block + # - In case when hash-shuffle strategy is employed -- perform `repartition_and_sort` + # - Otherwise we perform "global" sort of the dataset (to co-locate rows with the + # same key values) + if self._key is None: + shuffled_ds = self._dataset.repartition(1) + elif self._dataset.context.shuffle_strategy == ShuffleStrategy.HASH_SHUFFLE: + num_partitions = ( + self._num_partitions + or self._dataset.context.default_hash_shuffle_parallelism + ) + shuffled_ds = self._dataset.repartition( + num_partitions, + keys=self._key, + # Blocks must be sorted after repartitioning, such that group + # of rows sharing the same key values are co-located + sort=True, + ) + else: + shuffled_ds = self._dataset.sort(self._key) + + # The batch is the entire block, because we have batch_size=None for + # map_batches() below. + + if self._key is None: + keys = [] + elif isinstance(self._key, str): + keys = [self._key] + elif isinstance(self._key, List): + keys = self._key + else: + raise ValueError( + f"Group-by keys are expected to either be a single column (str) " + f"or a list of columns (got '{self._key}')" + ) + + # NOTE: It's crucial to make sure that UDF isn't capturing `GroupedData` + # object in its closure to ensure its serializability + # + # See https://github.com/ray-project/ray/issues/54280 for more details + if isinstance(fn, CallableClass): + + class wrapped_fn: + def __init__(self, *args, **kwargs): + self.fn = fn(*args, **kwargs) + + def __call__(self, batch, *args, **kwargs): + yield from _apply_udf_to_groups( + self.fn, batch, keys, batch_format, *args, **kwargs + ) + + else: + + def wrapped_fn(batch, *args, **kwargs): + yield from _apply_udf_to_groups( + fn, batch, keys, batch_format, *args, **kwargs + ) + + # Change the name of the wrapped function so that users see the name of their + # function rather than `wrapped_fn` in the progress bar. + if isinstance(fn, partial): + wrapped_fn.__name__ = fn.func.__name__ + else: + wrapped_fn.__name__ = fn.__name__ + + # NOTE: We set batch_size=None here, so that every batch contains the entire block, + # guaranteeing that groups are contained in full (ie not being split) + return shuffled_ds._map_batches_without_batch_size_validation( + wrapped_fn, + batch_size=None, + compute=compute, + # NOTE: We specify `batch_format` as none to avoid converting + # back-n-forth between batch and block formats (instead we convert + # once per group inside the method applying the UDF itself) + batch_format=None, + zero_copy_batch=zero_copy_batch, + fn_args=fn_args, + fn_kwargs=fn_kwargs, + fn_constructor_args=fn_constructor_args, + fn_constructor_kwargs=fn_constructor_kwargs, + num_cpus=num_cpus, + num_gpus=num_gpus, + memory=memory, + concurrency=concurrency, + ray_remote_args_fn=ray_remote_args_fn, + **ray_remote_args, + ) + + @PublicAPI(api_group=CDS_API_GROUP) + def count(self) -> Dataset: + """Compute count aggregation. + + Examples: + >>> import ray + >>> ray.data.from_items([ # doctest: +SKIP + ... {"A": x % 3, "B": x} for x in range(100)]).groupby( # doctest: +SKIP + ... "A").count() # doctest: +SKIP + + Returns: + A dataset of ``[k, v]`` columns where ``k`` is the groupby key and + ``v`` is the number of rows with that key. + If groupby key is ``None`` then the key part of return is omitted. + """ + return self.aggregate(Count()) + + @PublicAPI(api_group=CDS_API_GROUP) + def sum( + self, on: Union[str, List[str]] = None, ignore_nulls: bool = True + ) -> Dataset: + r"""Compute grouped sum aggregation. + + Examples: + >>> import ray + >>> ray.data.from_items([ # doctest: +SKIP + ... (i % 3, i, i**2) # doctest: +SKIP + ... for i in range(100)]) # doctest: +SKIP + ... .groupby(lambda x: x[0] % 3) # doctest: +SKIP + ... .sum(lambda x: x[2]) # doctest: +SKIP + >>> ray.data.range(100).groupby("id").sum() # doctest: +SKIP + >>> ray.data.from_items([ # doctest: +SKIP + ... {"A": i % 3, "B": i, "C": i**2} # doctest: +SKIP + ... for i in range(100)]) # doctest: +SKIP + ... .groupby("A") # doctest: +SKIP + ... .sum(["B", "C"]) # doctest: +SKIP + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values will be ignored when computing the sum; if ``False``, + if a null value is encountered, the output will be null. + We consider np.nan, None, and pd.NaT to be null values. + Default is ``True``. + + Returns: + The sum result. + + For different values of ``on``, the return varies: + + - ``on=None``: a dataset containing a groupby key column, + ``"k"``, and a column-wise sum column for each original column + in the dataset. + - ``on=["col_1", ..., "col_n"]``: a dataset of ``n + 1`` + columns where the first column is the groupby key and the second + through ``n + 1`` columns are the results of the aggregations. + + If groupby key is ``None`` then the key part of return is omitted. + """ + return self._aggregate_on(Sum, on, ignore_nulls=ignore_nulls) + + @PublicAPI(api_group=CDS_API_GROUP) + def min( + self, on: Union[str, List[str]] = None, ignore_nulls: bool = True + ) -> Dataset: + r"""Compute grouped min aggregation. + + Examples: + >>> import ray + >>> ray.data.le(100).groupby("value").min() # doctest: +SKIP + >>> ray.data.from_items([ # doctest: +SKIP + ... {"A": i % 3, "B": i, "C": i**2} # doctest: +SKIP + ... for i in range(100)]) # doctest: +SKIP + ... .groupby("A") # doctest: +SKIP + ... .min(["B", "C"]) # doctest: +SKIP + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values will be ignored when computing the min; if ``False``, + if a null value is encountered, the output will be null. + We consider np.nan, None, and pd.NaT to be null values. + Default is ``True``. + + Returns: + The min result. + + For different values of ``on``, the return varies: + + - ``on=None``: a dataset containing a groupby key column, + ``"k"``, and a column-wise min column for each original column in + the dataset. + - ``on=["col_1", ..., "col_n"]``: a dataset of ``n + 1`` + columns where the first column is the groupby key and the second + through ``n + 1`` columns are the results of the aggregations. + + If groupby key is ``None`` then the key part of return is omitted. + """ + return self._aggregate_on(Min, on, ignore_nulls=ignore_nulls) + + @PublicAPI(api_group=CDS_API_GROUP) + def max( + self, on: Union[str, List[str]] = None, ignore_nulls: bool = True + ) -> Dataset: + r"""Compute grouped max aggregation. + + Examples: + >>> import ray + >>> ray.data.le(100).groupby("value").max() # doctest: +SKIP + >>> ray.data.from_items([ # doctest: +SKIP + ... {"A": i % 3, "B": i, "C": i**2} # doctest: +SKIP + ... for i in range(100)]) # doctest: +SKIP + ... .groupby("A") # doctest: +SKIP + ... .max(["B", "C"]) # doctest: +SKIP + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values will be ignored when computing the max; if ``False``, + if a null value is encountered, the output will be null. + We consider np.nan, None, and pd.NaT to be null values. + Default is ``True``. + + Returns: + The max result. + + For different values of ``on``, the return varies: + + - ``on=None``: a dataset containing a groupby key column, + ``"k"``, and a column-wise max column for each original column in + the dataset. + - ``on=["col_1", ..., "col_n"]``: a dataset of ``n + 1`` + columns where the first column is the groupby key and the second + through ``n + 1`` columns are the results of the aggregations. + + If groupby key is ``None`` then the key part of return is omitted. + """ + return self._aggregate_on(Max, on, ignore_nulls=ignore_nulls) + + @PublicAPI(api_group=CDS_API_GROUP) + def mean( + self, on: Union[str, List[str]] = None, ignore_nulls: bool = True + ) -> Dataset: + r"""Compute grouped mean aggregation. + + Examples: + >>> import ray + >>> ray.data.le(100).groupby("value").mean() # doctest: +SKIP + >>> ray.data.from_items([ # doctest: +SKIP + ... {"A": i % 3, "B": i, "C": i**2} # doctest: +SKIP + ... for i in range(100)]) # doctest: +SKIP + ... .groupby("A") # doctest: +SKIP + ... .mean(["B", "C"]) # doctest: +SKIP + + Args: + on: a column name or a list of column names to aggregate. + ignore_nulls: Whether to ignore null values. If ``True``, null + values will be ignored when computing the mean; if ``False``, + if a null value is encountered, the output will be null. + We consider np.nan, None, and pd.NaT to be null values. + Default is ``True``. + + Returns: + The mean result. + + For different values of ``on``, the return varies: + + - ``on=None``: a dataset containing a groupby key column, + ``"k"``, and a column-wise mean column for each original column + in the dataset. + - ``on=["col_1", ..., "col_n"]``: a dataset of ``n + 1`` + columns where the first column is the groupby key and the second + through ``n + 1`` columns are the results of the aggregations. + + If groupby key is ``None`` then the key part of return is omitted. + """ + return self._aggregate_on(Mean, on, ignore_nulls=ignore_nulls) + + @PublicAPI(api_group=CDS_API_GROUP) + def std( + self, + on: Union[str, List[str]] = None, + ddof: int = 1, + ignore_nulls: bool = True, + ) -> Dataset: + r"""Compute grouped standard deviation aggregation. + + Examples: + >>> import ray + >>> ray.data.range(100).groupby("id").std(ddof=0) # doctest: +SKIP + >>> ray.data.from_items([ # doctest: +SKIP + ... {"A": i % 3, "B": i, "C": i**2} # doctest: +SKIP + ... for i in range(100)]) # doctest: +SKIP + ... .groupby("A") # doctest: +SKIP + ... .std(["B", "C"]) # doctest: +SKIP + + NOTE: This uses Welford's online method for an accumulator-style + computation of the standard deviation. This method was chosen due to + it's numerical stability, and it being computable in a single pass. + This may give different (but more accurate) results than NumPy, Pandas, + and sklearn, which use a less numerically stable two-pass algorithm. + See + https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_online_algorithm + + Args: + on: a column name or a list of column names to aggregate. + ddof: Delta Degrees of Freedom. The divisor used in calculations + is ``N - ddof``, where ``N`` represents the number of elements. + ignore_nulls: Whether to ignore null values. If ``True``, null + values will be ignored when computing the std; if ``False``, + if a null value is encountered, the output will be null. + We consider np.nan, None, and pd.NaT to be null values. + Default is ``True``. + + Returns: + The standard deviation result. + + For different values of ``on``, the return varies: + + - ``on=None``: a dataset containing a groupby key column, + ``"k"``, and a column-wise std column for each original column in + the dataset. + - ``on=["col_1", ..., "col_n"]``: a dataset of ``n + 1`` + columns where the first column is the groupby key and the second + through ``n + 1`` columns are the results of the aggregations. + + If groupby key is ``None`` then the key part of return is omitted. + """ + return self._aggregate_on(Std, on, ignore_nulls=ignore_nulls, ddof=ddof) + + +def _apply_udf_to_groups( + udf: Callable[[DataBatch, ...], DataBatch], + block: Block, + keys: List[str], + batch_format: Optional[str], + *args: Any, + **kwargs: Any, +) -> Iterator[DataBatch]: + """Apply UDF to groups of rows having the same set of values of the specified + columns (keys). + + NOTE: This function is defined at module level to avoid capturing closures and make it serializable.""" + block_accessor = BlockAccessor.for_block(block) + + boundaries = block_accessor._get_group_boundaries_sorted(keys) + + for start, end in zip(boundaries[:-1], boundaries[1:]): + group_block = block_accessor.slice(start, end, copy=False) + group_block_accessor = BlockAccessor.for_block(group_block) + + # Convert corresponding block of each group to batch format here, + # because the block format here can be different from batch format + # (e.g. block is Arrow format, and batch is NumPy format). + yield udf(group_block_accessor.to_batch_format(batch_format), *args, **kwargs) + + +# Backwards compatibility alias. +GroupedDataset = GroupedData diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/iterator.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/iterator.py new file mode 100644 index 0000000000000000000000000000000000000000..8602baf10f0aa23fa84b6084be81dba75e9723ad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/iterator.py @@ -0,0 +1,1000 @@ +import abc +import time +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Iterable, + Iterator, + List, + Optional, + Tuple, + TypeVar, + Union, +) + +import numpy as np + +from ray.data._internal.block_batching.iter_batches import iter_batches +from ray.data._internal.execution.interfaces import RefBundle +from ray.data._internal.logical.interfaces import LogicalPlan +from ray.data._internal.logical.operators.input_data_operator import InputData +from ray.data._internal.plan import ExecutionPlan +from ray.data._internal.stats import DatasetStats, StatsManager +from ray.data.block import BlockAccessor, DataBatch, _apply_batch_format +from ray.data.collate_fn import ( + ArrowBatchCollateFn, + CollateFn, + DefaultCollateFn, + NumpyBatchCollateFn, + PandasBatchCollateFn, + TensorBatchReturnType, + TensorBatchType, + is_tensor_batch_type, +) +from ray.data.context import DataContext +from ray.util.annotations import PublicAPI, RayDeprecationWarning + +if TYPE_CHECKING: + import tensorflow as tf + import torch + + from ray.data.dataset import ( + CollatedData, + MaterializedDataset, + Schema, + TensorFlowTensorBatchType, + TorchBatchType, + ) + + +T = TypeVar("T") + + +class _IterableFromIterator(Iterable[T]): + def __init__(self, iterator_gen: Callable[[], Iterator[T]]): + """Constructs an Iterable from an iterator generator. + + Args: + iterator_gen: A function that returns an iterator each time it + is called. For example, this can be a generator function. + """ + self.iterator_gen = iterator_gen + + def __iter__(self): + return self.iterator_gen() + + +@PublicAPI +class DataIterator(abc.ABC): + """An iterator for reading records from a :class:`~Dataset`. + + For Datasets, each iteration call represents a complete read of all items in the + Dataset. + + If using Ray Train, each trainer actor should get its own iterator by calling + :meth:`ray.train.get_dataset_shard("train") + `. + + Examples: + >>> import ray + >>> ds = ray.data.range(5) + >>> ds + Dataset(num_rows=5, schema={id: int64}) + >>> ds.iterator() + DataIterator(Dataset(num_rows=5, schema={id: int64})) + """ + + @abc.abstractmethod + def _to_ref_bundle_iterator( + self, + ) -> Tuple[Iterator[RefBundle], Optional[DatasetStats], bool]: + """Returns the iterator to use for `iter_batches`. + + Returns: + A tuple. The first item of the tuple is an iterator over RefBundles. + The second item of the tuple is a DatasetStats object used for recording + stats during iteration. + The third item is a boolean indicating if the blocks can be safely cleared + after use. + """ + ... + + @PublicAPI + def iter_batches( + self, + *, + prefetch_batches: int = 1, + batch_size: int = 256, + batch_format: Optional[str] = "default", + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + ) -> Iterable[DataBatch]: + """Return a batched iterable over the dataset. + + Examples: + >>> import ray + >>> for batch in ray.data.range( + ... 1000000 + ... ).iterator().iter_batches(): # doctest: +SKIP + ... print(batch) # doctest: +SKIP + + Time complexity: O(1) + + Args: + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool will be used + to fetch the objects to the local node, format the batches, and apply + the collate_fn. Defaults to 1. + batch_size: The number of rows in each batch, or None to use entire blocks + as batches (blocks may contain different number of rows). + The final batch may include fewer than ``batch_size`` rows if + ``drop_last`` is ``False``. Defaults to 256. + batch_format: Specify ``"default"`` to use the default block format + (NumPy), ``"pandas"`` to select ``pandas.DataFrame``, "pyarrow" to + select ``pyarrow.Table``, or ``"numpy"`` to select + ``Dict[str, numpy.ndarray]``, or None to return the underlying block + exactly as is with no additional formatting. + drop_last: Whether to drop the last batch if it's incomplete. + local_shuffle_buffer_size: If non-None, the data will be randomly shuffled + using a local in-memory shuffle buffer, and this value will serve as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer will be drained. + local_shuffle_seed: The seed to use for the local random shuffle. + + Returns: + An iterable over record batches. + """ + return self._iter_batches( + prefetch_batches=prefetch_batches, + batch_size=batch_size, + batch_format=batch_format, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + ) + + def _iter_batches( + self, + *, + prefetch_batches: int = 1, + batch_size: int = 256, + batch_format: Optional[str] = "default", + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + _collate_fn: Optional[Callable[[DataBatch], "CollatedData"]] = None, + _finalize_fn: Optional[Callable[[Any], Any]] = None, + ) -> Iterable[DataBatch]: + batch_format = _apply_batch_format(batch_format) + + def _create_iterator() -> Iterator[DataBatch]: + time_start = time.perf_counter() + # Iterate through the dataset from the start each time + # _iterator_gen is called. + # This allows multiple iterations of the dataset without + # needing to explicitly call `iter_batches()` multiple times. + ( + ref_bundles_iterator, + stats, + blocks_owned_by_consumer, + ) = self._to_ref_bundle_iterator() + + iterator = iter( + iter_batches( + ref_bundles_iterator, + stats=stats, + clear_block_after_read=blocks_owned_by_consumer, + batch_size=batch_size, + batch_format=batch_format, + drop_last=drop_last, + collate_fn=_collate_fn, + finalize_fn=_finalize_fn, + shuffle_buffer_min_size=local_shuffle_buffer_size, + shuffle_seed=local_shuffle_seed, + prefetch_batches=prefetch_batches, + ) + ) + + dataset_tag = self._get_dataset_tag() + + if stats: + stats.iter_initialize_s.add(time.perf_counter() - time_start) + + for batch in iterator: + yield batch + StatsManager.update_iteration_metrics(stats, dataset_tag) + StatsManager.clear_iteration_metrics(dataset_tag) + + if stats: + stats.iter_total_s.add(time.perf_counter() - time_start) + + return _IterableFromIterator(_create_iterator) + + def _get_dataset_tag(self) -> str: + return "unknown_dataset" + + @PublicAPI + def iter_rows(self) -> Iterable[Dict[str, Any]]: + """Return a local row iterable over the dataset. + + If the dataset is a tabular dataset (Arrow/Pandas blocks), dicts + are yielded for each row by the iterator. If the dataset is not tabular, + the raw row is yielded. + + Examples: + >>> import ray + >>> dataset = ray.data.range(10) + >>> next(iter(dataset.iterator().iter_rows())) + {'id': 0} + + Time complexity: O(1) + + Returns: + An iterable over rows of the dataset. + """ + batch_iterable = self._iter_batches( + batch_size=None, batch_format=None, prefetch_batches=1 + ) + + def _wrapped_iterator(): + for batch in batch_iterable: + batch = BlockAccessor.for_block(BlockAccessor.batch_to_block(batch)) + for row in batch.iter_rows(public_row_format=True): + yield row + + return _IterableFromIterator(_wrapped_iterator) + + @abc.abstractmethod + @PublicAPI + def stats(self) -> str: + """Returns a string containing execution timing information.""" + ... + + @abc.abstractmethod + def schema(self) -> "Schema": + """Return the schema of the dataset iterated over.""" + ... + + @abc.abstractmethod + def get_context(self) -> DataContext: + ... + + @PublicAPI + def iter_torch_batches( + self, + *, + prefetch_batches: int = 1, + batch_size: Optional[int] = 256, + dtypes: Optional[Union["torch.dtype", Dict[str, "torch.dtype"]]] = None, + device: str = "auto", + collate_fn: Optional[ + Union[Callable[[Dict[str, np.ndarray]], "CollatedData"], CollateFn] + ] = None, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + pin_memory: bool = False, + ) -> Iterable["TorchBatchType"]: + """Return a batched iterable of Torch Tensors over the dataset. + + This iterable yields a dictionary of column-tensors. If you are looking for + more flexibility in the tensor conversion (e.g. casting dtypes) or the batch + format, try using :meth:`~ray.data.DataIterator.iter_batches` directly. + + Examples: + >>> import ray + >>> for batch in ray.data.range( + ... 12, + ... ).iterator().iter_torch_batches(batch_size=4): + ... print(batch) + {'id': tensor([0, 1, 2, 3])} + {'id': tensor([4, 5, 6, 7])} + {'id': tensor([ 8, 9, 10, 11])} + + Use the ``collate_fn`` to customize how the tensor batch is created. + + >>> from typing import Any, Dict + >>> import torch + >>> import numpy as np + >>> import ray + >>> def collate_fn(batch: Dict[str, np.ndarray]) -> Any: + ... return torch.stack( + ... [torch.as_tensor(array) for array in batch.values()], + ... axis=1 + ... ) + >>> iterator = ray.data.from_items([ + ... {"col_1": 1, "col_2": 2}, + ... {"col_1": 3, "col_2": 4}]).iterator() + >>> for batch in iterator.iter_torch_batches(collate_fn=collate_fn): + ... print(batch) + tensor([[1, 2], + [3, 4]]) + + Time complexity: O(1) + + Args: + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool will be used + to fetch the objects to the local node, format the batches, and apply + the collate_fn. Defaults to 1. + batch_size: The number of rows in each batch, or None to use entire blocks + as batches (blocks may contain different number of rows). + The final batch may include fewer than ``batch_size`` rows if + ``drop_last`` is ``False``. Defaults to 256. + dtypes: The Torch dtype(s) for the created tensor(s); if None, the dtype + will be inferred from the tensor data. You can't use this parameter + with ``collate_fn``. + device: The device on which the tensor should be placed. Defaults to + "auto" which moves the tensors to the appropriate device when the + Dataset is passed to Ray Train and ``collate_fn`` is not provided. + Otherwise, defaults to CPU. You can't use this parameter with + ``collate_fn``. + collate_fn: [Alpha] A function to customize how data batches are collated + before being passed to the model. This is useful for last-mile data + formatting such as padding, masking, or packaging tensors into custom + data structures. If not provided, `iter_torch_batches` automatically + converts batches to `torch.Tensor`s and moves them to the device + assigned to the current worker. The input to `collate_fn` may be: + + 1. pyarrow.Table, where you should provide a callable class that + subclasses `ArrowBatchCollateFn` (recommended for best performance). + Note that you should use util function `arrow_batch_to_tensors` to + convert the pyarrow.Table to a dictionary of non-contiguous tensor + batches. + 2. Dict[str, np.ndarray], where you should provide a callable class that + subclasses `NumpyBatchCollateFn` + 3. pd.DataFrame, where you should provide a callable class that + subclasses `PandasBatchCollateFn` + + The output can be any type. If the output is a `TensorBatchType`, it will be + automatically moved to the current worker's device. For other types, + you must handle device transfer manually in your training loop. + Note: This function is called in a multi-threaded context; avoid using + thread-unsafe code. + drop_last: Whether to drop the last batch if it's incomplete. + local_shuffle_buffer_size: If non-None, the data will be randomly shuffled + using a local in-memory shuffle buffer, and this value will serve as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer will be drained. This + buffer size must be greater than or equal to ``batch_size``, and + therefore ``batch_size`` must also be specified when using local + shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + pin_memory: [Alpha] If True, copies the tensor to pinned memory. Note that + `pin_memory` is only supported when using `DefaultCollateFn`. + + Returns: + An iterable over Torch Tensor batches. + """ + + from ray.train.torch import get_device + + if collate_fn is not None and (dtypes is not None or device != "auto"): + raise ValueError( + "collate_fn cannot be used with dtypes and device." + "You should manually move the output Torch tensors to the" + "desired dtype and device outside of collate_fn." + ) + + if pin_memory and collate_fn is not None: + raise ValueError( + "pin_memory is only supported when using `DefaultCollateFn`." + ) + + if device == "auto": + # Use the appropriate device for Ray Train, or falls back to CPU if + # Ray Train is not being used. + device = get_device() + + from ray.air._internal.torch_utils import ( + move_tensors_to_device, + ) + + # The default finalize_fn handles the host to device data transfer. + # This is executed in a 1-thread pool separately from collate_fn + # to allow independent parallelism of these steps. + def default_finalize_fn( + batch: TensorBatchType, + ) -> Union[TensorBatchReturnType, Any]: + """Default finalize function for moving PyTorch tensors to device. If + batch is of type `TensorBatchType`, it will be automatically moved to the + current worker's device. For other types, you must handle device transfer + manually in your training loop. + + Args: + batch: Input batch to move to device. + + Returns: + Batch with tensors moved to the target device. + - If input is TensorBatchType, returns tensors moved to device + - Otherwise returns the same type as input without moving tensors + to device. + """ + if is_tensor_batch_type(batch): + return move_tensors_to_device(batch, device=device) + else: + return batch + + if collate_fn is None: + # The default collate_fn handles formatting and Tensor creation. + # Here, we defer host to device data transfer to the subsequent + # finalize_fn. + collate_fn = DefaultCollateFn( + dtypes=dtypes, + device=device, + pin_memory=pin_memory, + ) + batch_format = "pyarrow" + elif isinstance(collate_fn, ArrowBatchCollateFn): + # The ArrowBatchCollateFn handles formatting and Tensor creation. + # Here, we defer host to device data transfer to the subsequent + # finalize_fn. + batch_format = "pyarrow" + elif isinstance(collate_fn, NumpyBatchCollateFn): + batch_format = "numpy" + elif isinstance(collate_fn, PandasBatchCollateFn): + batch_format = "pandas" + elif callable(collate_fn): + batch_format = "numpy" + warnings.warn( + "Passing a function to `iter_torch_batches(collate_fn)` is " + "deprecated in Ray 2.47. Please switch to using a callable class that " + "inherits from `ArrowBatchCollateFn`, `NumpyBatchCollateFn`, or " + "`PandasBatchCollateFn`.", + RayDeprecationWarning, + ) + else: + raise ValueError(f"Unsupported collate function: {type(collate_fn)}") + + return self._iter_batches( + prefetch_batches=prefetch_batches, + batch_size=batch_size, + batch_format=batch_format, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + _collate_fn=collate_fn, + _finalize_fn=default_finalize_fn, + ) + + def iter_tf_batches( + self, + *, + prefetch_batches: int = 1, + batch_size: Optional[int] = 256, + dtypes: Optional[Union["tf.dtypes.DType", Dict[str, "tf.dtypes.DType"]]] = None, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + ) -> Iterable["TensorFlowTensorBatchType"]: + """Return a batched iterable of TensorFlow Tensors over the dataset. + + This iterable will yield single-tensor batches of the underlying dataset + consists of a single column; otherwise, it will yield a dictionary of + column-tensors. + + .. tip:: + If you don't need the additional flexibility provided by this method, + consider using :meth:`~ray.data.Dataset.to_tf` instead. It's easier + to use. + + Examples: + >>> import ray + >>> for batch in ray.data.range( # doctest: +SKIP + ... 12, + ... ).iter_tf_batches(batch_size=4): + ... print(batch.shape) # doctest: +SKIP + (4, 1) + (4, 1) + (4, 1) + + Time complexity: O(1) + + Args: + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool will be used + to fetch the objects to the local node, format the batches, and apply + the collate_fn. Defaults to 1. + batch_size: The number of rows in each batch, or None to use entire blocks + as batches (blocks may contain different number of rows). + The final batch may include fewer than ``batch_size`` rows if + ``drop_last`` is ``False``. Defaults to 256. + dtypes: The TensorFlow dtype(s) for the created tensor(s); if None, the + dtype will be inferred from the tensor data. + drop_last: Whether to drop the last batch if it's incomplete. + local_shuffle_buffer_size: If non-None, the data will be randomly shuffled + using a local in-memory shuffle buffer, and this value will serve as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer will be drained. This + buffer size must be greater than or equal to ``batch_size``, and + therefore ``batch_size`` must also be specified when using local + shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + + Returns: + An iterator over TensorFlow Tensor batches. + """ + from ray.air._internal.tensorflow_utils import ( + convert_ndarray_batch_to_tf_tensor_batch, + ) + + batch_iterable = self._iter_batches( + prefetch_batches=prefetch_batches, + batch_size=batch_size, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + ) + mapped_iterable = map( + lambda batch: convert_ndarray_batch_to_tf_tensor_batch( + batch, dtypes=dtypes + ), + batch_iterable, + ) + + return mapped_iterable + + def to_torch( + self, + *, + label_column: Optional[str] = None, + feature_columns: Optional[ + Union[List[str], List[List[str]], Dict[str, List[str]]] + ] = None, + label_column_dtype: Optional["torch.dtype"] = None, + feature_column_dtypes: Optional[ + Union["torch.dtype", List["torch.dtype"], Dict[str, "torch.dtype"]] + ] = None, + batch_size: int = 1, + prefetch_batches: int = 1, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + unsqueeze_label_tensor: bool = True, + unsqueeze_feature_tensors: bool = True, + ) -> "torch.utils.data.IterableDataset": + """Return a Torch IterableDataset over this dataset. + + This is only supported for datasets convertible to Arrow records. + + It is recommended to use the returned ``IterableDataset`` directly + instead of passing it into a torch ``DataLoader``. + + Each element in IterableDataset will be a tuple consisting of 2 + elements. The first item contains the feature tensor(s), and the + second item is the label tensor. Those can take on different + forms, depending on the specified arguments. + + For the features tensor (N is the ``batch_size`` and n, m, k + are the number of features per tensor): + + * If ``feature_columns`` is a ``List[str]``, the features will be + a tensor of shape (N, n), with columns corresponding to + ``feature_columns`` + + * If ``feature_columns`` is a ``List[List[str]]``, the features will be + a list of tensors of shape [(N, m),...,(N, k)], with columns of each + tensor corresponding to the elements of ``feature_columns`` + + * If ``feature_columns`` is a ``Dict[str, List[str]]``, the features + will be a dict of key-tensor pairs of shape + {key1: (N, m),..., keyN: (N, k)}, with columns of each + tensor corresponding to the value of ``feature_columns`` under the + key. + + If ``unsqueeze_label_tensor=True`` (default), the label tensor will be + of shape (N, 1). Otherwise, it will be of shape (N,). + If ``label_column`` is specified as ``None``, then no column from the + ``Dataset`` will be treated as the label, and the output label tensor + will be ``None``. + + Note that you probably want to call ``.split()`` on this dataset if + there are to be multiple Torch workers consuming the data. + + Time complexity: O(1) + + Args: + label_column: The name of the column used as the + label (second element of the output list). Can be None for + prediction, in which case the second element of returned + tuple will also be None. + feature_columns: The names of the columns + to use as the features. Can be a list of lists or + a dict of string-list pairs for multi-tensor output. + If None, then use all columns except the label column as + the features. + label_column_dtype: The torch dtype to + use for the label column. If None, then automatically infer + the dtype. + feature_column_dtypes: The dtypes to use for the feature + tensors. This should match the format of ``feature_columns``, + or be a single dtype, in which case it will be applied to + all tensors. If None, then automatically infer the dtype. + batch_size: How many samples per batch to yield at a time. + Defaults to 1. + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool will be used + to fetch the objects to the local node, format the batches, and apply + the collate_fn. Defaults to 1. + drop_last: Set to True to drop the last incomplete batch, + if the dataset size is not divisible by the batch size. If + False and the size of dataset is not divisible by the batch + size, then the last batch will be smaller. Defaults to False. + local_shuffle_buffer_size: If non-None, the data will be randomly shuffled + using a local in-memory shuffle buffer, and this value will serve as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer will be drained. This + buffer size must be greater than or equal to ``batch_size``, and + therefore ``batch_size`` must also be specified when using local + shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + unsqueeze_label_tensor: If set to True, the label tensor + will be unsqueezed (reshaped to (N, 1)). Otherwise, it will + be left as is, that is (N, ). In general, regression loss + functions expect an unsqueezed tensor, while classification + loss functions expect a squeezed one. Defaults to True. + unsqueeze_feature_tensors: If set to True, the features tensors + will be unsqueezed (reshaped to (N, 1)) before being concatenated into + the final features tensor. Otherwise, they will be left as is, that is + (N, ). Defaults to True. + + Returns: + A torch IterableDataset. + """ + import torch + + from ray.air._internal.torch_utils import convert_pandas_to_torch_tensor + from ray.data._internal.torch_iterable_dataset import TorchIterableDataset + + # If an empty collection is passed in, treat it the same as None + if not feature_columns: + feature_columns = None + + if feature_column_dtypes and not isinstance(feature_column_dtypes, torch.dtype): + if isinstance(feature_columns, dict): + if not isinstance(feature_column_dtypes, dict): + raise TypeError( + "If `feature_columns` is a dict, " + "`feature_column_dtypes` must be None, `torch.dtype`," + f" or dict, got {type(feature_column_dtypes)}." + ) + if set(feature_columns) != set(feature_column_dtypes): + raise ValueError( + "`feature_columns` and `feature_column_dtypes` " + "must have the same keys." + ) + if any(not subcolumns for subcolumns in feature_columns.values()): + raise ValueError("column list may not be empty") + elif isinstance(feature_columns[0], (list, tuple)): + if not isinstance(feature_column_dtypes, (list, tuple)): + raise TypeError( + "If `feature_columns` is a list of lists, " + "`feature_column_dtypes` must be None, `torch.dtype`," + f" or a sequence, got {type(feature_column_dtypes)}." + ) + if len(feature_columns) != len(feature_column_dtypes): + raise ValueError( + "`feature_columns` and `feature_column_dtypes` " + "must have the same length." + ) + if any(not subcolumns for subcolumns in feature_columns): + raise ValueError("column list may not be empty") + + def make_generator(): + for batch in self._iter_batches( + batch_size=batch_size, + batch_format="pandas", + prefetch_batches=prefetch_batches, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + ): + if label_column: + label_tensor = convert_pandas_to_torch_tensor( + batch, + [label_column], + label_column_dtype, + unsqueeze=unsqueeze_label_tensor, + ) + batch.pop(label_column) + else: + label_tensor = None + + if isinstance(feature_columns, dict): + features_tensor = { + key: convert_pandas_to_torch_tensor( + batch, + feature_columns[key], + ( + feature_column_dtypes[key] + if isinstance(feature_column_dtypes, dict) + else feature_column_dtypes + ), + unsqueeze=unsqueeze_feature_tensors, + ) + for key in feature_columns + } + else: + features_tensor = convert_pandas_to_torch_tensor( + batch, + columns=feature_columns, + column_dtypes=feature_column_dtypes, + unsqueeze=unsqueeze_feature_tensors, + ) + + yield (features_tensor, label_tensor) + + return TorchIterableDataset(make_generator) + + @PublicAPI + def to_tf( + self, + feature_columns: Union[str, List[str]], + label_columns: Union[str, List[str]], + *, + additional_columns: Union[Optional[str], Optional[List[str]]] = None, + prefetch_batches: int = 1, + batch_size: int = 1, + drop_last: bool = False, + local_shuffle_buffer_size: Optional[int] = None, + local_shuffle_seed: Optional[int] = None, + feature_type_spec: Union["tf.TypeSpec", Dict[str, "tf.TypeSpec"]] = None, + label_type_spec: Union["tf.TypeSpec", Dict[str, "tf.TypeSpec"]] = None, + additional_type_spec: Union[ + Optional["tf.TypeSpec"], Optional[Dict[str, "tf.TypeSpec"]] + ] = None, + ) -> "tf.data.Dataset": + """Return a TF Dataset over this dataset. + + .. warning:: + If your dataset contains ragged tensors, this method errors. To prevent + errors, :ref:`resize your tensors `. + + Examples: + >>> import ray + >>> ds = ray.data.read_csv( + ... "s3://anonymous@air-example-data/iris.csv" + ... ) + >>> it = ds.iterator(); it + DataIterator(Dataset(num_rows=?, schema=...)) + + If your model accepts a single tensor as input, specify a single feature column. + + >>> it.to_tf(feature_columns="sepal length (cm)", label_columns="target") + <_OptionsDataset element_spec=(TensorSpec(shape=(None,), dtype=tf.float64, name='sepal length (cm)'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'))> + + If your model accepts a dictionary as input, specify a list of feature columns. + + >>> it.to_tf(["sepal length (cm)", "sepal width (cm)"], "target") + <_OptionsDataset element_spec=({'sepal length (cm)': TensorSpec(shape=(None,), dtype=tf.float64, name='sepal length (cm)'), 'sepal width (cm)': TensorSpec(shape=(None,), dtype=tf.float64, name='sepal width (cm)')}, TensorSpec(shape=(None,), dtype=tf.int64, name='target'))> + + If your dataset contains multiple features but your model accepts a single + tensor as input, combine features with + :class:`~ray.data.preprocessors.Concatenator`. + + >>> from ray.data.preprocessors import Concatenator + >>> columns_to_concat = ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"] + >>> preprocessor = Concatenator(columns=columns_to_concat, output_column_name="features") + >>> it = preprocessor.transform(ds).iterator() + >>> it + DataIterator(Concatenator + +- Dataset(num_rows=?, schema=...)) + >>> it.to_tf("features", "target") + <_OptionsDataset element_spec=(TensorSpec(shape=(None, 4), dtype=tf.float64, name='features'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'))> + + If your model accepts different types, shapes, or names of tensors as input, specify the type spec. + If type specs are not specified, they are automatically inferred from the schema of the iterator. + + >>> import tensorflow as tf + >>> it.to_tf( + ... feature_columns="features", + ... label_columns="target", + ... feature_type_spec=tf.TensorSpec(shape=(None, 4), dtype=tf.float32, name="features"), + ... label_type_spec=tf.TensorSpec(shape=(None,), dtype=tf.float32, name="label") + ... ) + <_OptionsDataset element_spec=(TensorSpec(shape=(None, 4), dtype=tf.float32, name='features'), TensorSpec(shape=(None,), dtype=tf.float32, name='label'))> + + If your model accepts additional metadata aside from features and label, specify a single additional column or a list of additional columns. + A common use case is to include sample weights in the data samples and train a ``tf.keras.Model`` with ``tf.keras.Model.fit``. + + >>> import pandas as pd + >>> ds = ds.add_column("sample weights", lambda df: pd.Series([1] * len(df))) + >>> it = ds.iterator() + >>> it.to_tf(feature_columns="sepal length (cm)", label_columns="target", additional_columns="sample weights") + <_OptionsDataset element_spec=(TensorSpec(shape=(None,), dtype=tf.float64, name='sepal length (cm)'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'), TensorSpec(shape=(None,), dtype=tf.int64, name='sample weights'))> + + If your model accepts different types, shapes, or names for the additional metadata, specify the type spec of the additional column. + + >>> it.to_tf( + ... feature_columns="sepal length (cm)", + ... label_columns="target", + ... additional_columns="sample weights", + ... additional_type_spec=tf.TensorSpec(shape=(None,), dtype=tf.float32, name="weight") + ... ) + <_OptionsDataset element_spec=(TensorSpec(shape=(None,), dtype=tf.float64, name='sepal length (cm)'), TensorSpec(shape=(None,), dtype=tf.int64, name='target'), TensorSpec(shape=(None,), dtype=tf.float32, name='weight'))> + + Args: + feature_columns: Columns that correspond to model inputs. If this is a + string, the input data is a tensor. If this is a list, the input data + is a ``dict`` that maps column names to their tensor representation. + label_columns: Columns that correspond to model targets. If this is a + string, the target data is a tensor. If this is a list, the target data + is a ``dict`` that maps column names to their tensor representation. + additional_columns: Columns that correspond to sample weights or other metadata. + If this is a string, the weight data is a tensor. If this is a list, the + weight data is a ``dict`` that maps column names to their tensor representation. + prefetch_batches: The number of batches to fetch ahead of the current batch + to fetch. If set to greater than 0, a separate threadpool will be used + to fetch the objects to the local node, format the batches, and apply + the collate_fn. Defaults to 1. + batch_size: Record batch size. Defaults to 1. + drop_last: Set to True to drop the last incomplete batch, + if the dataset size is not divisible by the batch size. If + False and the size of dataset is not divisible by the batch + size, then the last batch will be smaller. Defaults to False. + local_shuffle_buffer_size: If non-None, the data will be randomly shuffled + using a local in-memory shuffle buffer, and this value will serve as the + minimum number of rows that must be in the local in-memory shuffle + buffer in order to yield a batch. When there are no more rows to add to + the buffer, the remaining rows in the buffer will be drained. This + buffer size must be greater than or equal to ``batch_size``, and + therefore ``batch_size`` must also be specified when using local + shuffling. + local_shuffle_seed: The seed to use for the local random shuffle. + feature_type_spec: The `tf.TypeSpec` of `feature_columns`. If there is + only one column, specify a `tf.TypeSpec`. If there are multiple columns, + specify a ``dict`` that maps column names to their `tf.TypeSpec`. + Default is `None` to automatically infer the type of each column. + label_type_spec: The `tf.TypeSpec` of `label_columns`. If there is + only one column, specify a `tf.TypeSpec`. If there are multiple columns, + specify a ``dict`` that maps column names to their `tf.TypeSpec`. + Default is `None` to automatically infer the type of each column. + additional_type_spec: The `tf.TypeSpec` of `additional_columns`. If there + is only one column, specify a `tf.TypeSpec`. If there are multiple + columns, specify a ``dict`` that maps column names to their `tf.TypeSpec`. + Default is `None` to automatically infer the type of each column. + + Returns: + A ``tf.data.Dataset`` that yields inputs and targets. + """ # noqa: E501 + + from ray.air._internal.tensorflow_utils import ( + convert_ndarray_to_tf_tensor, + get_type_spec, + ) + + try: + import tensorflow as tf + except ImportError: + raise ValueError("tensorflow must be installed!") + + def validate_column(column: str) -> None: + if column not in valid_columns: + raise ValueError( + f"You specified '{column}' in `feature_columns`, " + f"`label_columns`, or `additional_columns`, but there's no " + f"column named '{column}' in the dataset. " + f"Valid column names are: {valid_columns}." + ) + + def validate_columns(columns: Union[str, List]) -> None: + if isinstance(columns, list): + for column in columns: + validate_column(column) + else: + validate_column(columns) + + def convert_batch_to_tensors( + batch: Dict[str, np.ndarray], + *, + columns: Union[str, List[str]], + type_spec: Union[tf.TypeSpec, Dict[str, tf.TypeSpec]], + ) -> Union[tf.Tensor, Dict[str, tf.Tensor]]: + if isinstance(columns, str): + return convert_ndarray_to_tf_tensor(batch[columns], type_spec=type_spec) + return { + column: convert_ndarray_to_tf_tensor( + batch[column], type_spec=type_spec[column] + ) + for column in columns + } + + def generator(): + for batch in self._iter_batches( + prefetch_batches=prefetch_batches, + batch_size=batch_size, + drop_last=drop_last, + local_shuffle_buffer_size=local_shuffle_buffer_size, + local_shuffle_seed=local_shuffle_seed, + ): + assert isinstance(batch, dict) + features = convert_batch_to_tensors( + batch, columns=feature_columns, type_spec=feature_type_spec + ) + labels = convert_batch_to_tensors( + batch, columns=label_columns, type_spec=label_type_spec + ) + + if additional_columns is None: + yield features, labels + else: + additional_metadata = convert_batch_to_tensors( + batch, + columns=additional_columns, + type_spec=additional_type_spec, + ) + yield features, labels, additional_metadata + + if feature_type_spec is None or label_type_spec is None: + schema = self.schema() + valid_columns = set(schema.names) + validate_columns(feature_columns) + validate_columns(label_columns) + feature_type_spec = get_type_spec(schema, columns=feature_columns) + label_type_spec = get_type_spec(schema, columns=label_columns) + + if additional_columns is not None and additional_type_spec is None: + schema = self.schema() + valid_columns = set(schema.names) + validate_columns(additional_columns) + additional_type_spec = get_type_spec(schema, columns=additional_columns) + + if additional_columns is not None: + dataset = tf.data.Dataset.from_generator( + generator, + output_signature=( + feature_type_spec, + label_type_spec, + additional_type_spec, + ), + ) + else: + dataset = tf.data.Dataset.from_generator( + generator, output_signature=(feature_type_spec, label_type_spec) + ) + + options = tf.data.Options() + options.experimental_distribute.auto_shard_policy = ( + tf.data.experimental.AutoShardPolicy.OFF + ) + return dataset.with_options(options) + + @PublicAPI + def materialize(self) -> "MaterializedDataset": + """Execute and materialize this data iterator into object store memory. + + .. note:: + This method triggers the execution and materializes all blocks + of the iterator, returning its contents as a + :class:`~ray.data.dataset.MaterializedDataset` for further processing. + """ + + from ray.data.dataset import MaterializedDataset + + ref_bundles_iter, stats, _ = self._to_ref_bundle_iterator() + ref_bundles = list(ref_bundles_iter) + execution_plan = ExecutionPlan(stats, self.get_context()) + logical_plan = LogicalPlan( + InputData(input_data=ref_bundles), + execution_plan._context, + ) + return MaterializedDataset( + execution_plan, + logical_plan, + ) + + def __del__(self): + # Clear metrics on deletion in case the iterator was not fully consumed. + StatsManager.clear_iteration_metrics(self._get_dataset_tag()) + + +# Backwards compatibility alias. +DatasetIterator = DataIterator diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/llm.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/llm.py new file mode 100644 index 0000000000000000000000000000000000000000..bdae67778cfb9bd0ac0ac7a5b0cf70a7c8203614 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/llm.py @@ -0,0 +1,328 @@ +from typing import Optional + +from ray.data.block import UserDefinedFunction +from ray.llm._internal.batch.processor import ( + HttpRequestProcessorConfig as _HttpRequestProcessorConfig, + Processor, + ProcessorConfig as _ProcessorConfig, + SGLangEngineProcessorConfig as _SGLangEngineProcessorConfig, + vLLMEngineProcessorConfig as _vLLMEngineProcessorConfig, +) +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="alpha") +class ProcessorConfig(_ProcessorConfig): + """The processor configuration. + + Args: + batch_size: Configures batch size for the processor. Large batch sizes are + likely to saturate the compute resources and could achieve higher throughput. + On the other hand, small batch sizes are more fault-tolerant and could + reduce bubbles in the data pipeline. You can tune the batch size to balance + the throughput and fault-tolerance based on your use case. + resources_per_bundle: The resource bundles for placement groups. + You can specify a custom device label e.g. {'NPU': 1}. + The default resource bundle for LLM Stage is always a GPU resource i.e. {'GPU': 1}. + accelerator_type: The accelerator type used by the LLM stage in a processor. + Default to None, meaning that only the CPU will be used. + concurrency: The number of workers for data parallelism. Default to 1. + """ + + pass + + +@PublicAPI(stability="alpha") +class HttpRequestProcessorConfig(_HttpRequestProcessorConfig): + """The configuration for the HTTP request processor. + + Args: + batch_size: The batch size to send to the HTTP request. + url: The URL to send the HTTP request to. + headers: The headers to send with the HTTP request. + concurrency: The number of concurrent requests to send. + + Examples: + .. testcode:: + :skipif: True + + import ray + from ray.data.llm import HttpRequestProcessorConfig, build_llm_processor + + config = HttpRequestProcessorConfig( + url="https://api.openai.com/v1/chat/completions", + headers={"Authorization": "Bearer sk-..."}, + concurrency=1, + ) + processor = build_llm_processor( + config, + preprocess=lambda row: dict( + payload=dict( + model="gpt-4o-mini", + messages=[ + {"role": "system", "content": "You are a calculator"}, + {"role": "user", "content": f"{row['id']} ** 3 = ?"}, + ], + temperature=0.3, + max_tokens=20, + ), + ), + postprocess=lambda row: dict( + resp=row["http_response"]["choices"][0]["message"]["content"], + ), + ) + + ds = ray.data.range(10) + ds = processor(ds) + for row in ds.take_all(): + print(row) + """ + + pass + + +@PublicAPI(stability="alpha") +class vLLMEngineProcessorConfig(_vLLMEngineProcessorConfig): + """The configuration for the vLLM engine processor. + + Args: + model_source: The model source to use for the vLLM engine. + batch_size: The batch size to send to the vLLM engine. Large batch sizes are + likely to saturate the compute resources and could achieve higher throughput. + On the other hand, small batch sizes are more fault-tolerant and could + reduce bubbles in the data pipeline. You can tune the batch size to balance + the throughput and fault-tolerance based on your use case. + engine_kwargs: The kwargs to pass to the vLLM engine. Default engine kwargs are + pipeline_parallel_size: 1, tensor_parallel_size: 1, max_num_seqs: 128, + distributed_executor_backend: "mp". + task_type: The task type to use. If not specified, will use 'generate' by default. + runtime_env: The runtime environment to use for the vLLM engine. See + :ref:`this doc ` for more details. + max_pending_requests: The maximum number of pending requests. If not specified, + will use the default value from the vLLM engine. + max_concurrent_batches: The maximum number of concurrent batches in the engine. + This is to overlap the batch processing to avoid the tail latency of + each batch. The default value may not be optimal when the batch size + or the batch processing latency is too small, but it should be good + enough for batch size >= 64. + apply_chat_template: Whether to apply chat template. + chat_template: The chat template to use. This is usually not needed if the + model checkpoint already contains the chat template. + tokenize: Whether to tokenize the input before passing it to the vLLM engine. + If not, vLLM will tokenize the prompt in the engine. + detokenize: Whether to detokenize the output. + has_image: Whether the input messages have images. + accelerator_type: The accelerator type used by the LLM stage in a processor. + Default to None, meaning that only the CPU will be used. + concurrency: The number of workers for data parallelism. Default to 1. + + Examples: + + .. testcode:: + :skipif: True + + import ray + from ray.data.llm import vLLMEngineProcessorConfig, build_llm_processor + + config = vLLMEngineProcessorConfig( + model_source="meta-llama/Meta-Llama-3.1-8B-Instruct", + engine_kwargs=dict( + enable_prefix_caching=True, + enable_chunked_prefill=True, + max_num_batched_tokens=4096, + ), + concurrency=1, + batch_size=64, + ) + processor = build_llm_processor( + config, + preprocess=lambda row: dict( + messages=[ + {"role": "system", "content": "You are a calculator"}, + {"role": "user", "content": f"{row['id']} ** 3 = ?"}, + ], + sampling_params=dict( + temperature=0.3, + max_tokens=20, + detokenize=False, + ), + ), + postprocess=lambda row: dict( + resp=row["generated_text"], + ), + ) + + # The processor requires specific input columns, which depend on + # your processor config. You can use the following API to check + # the required input columns: + processor.log_input_column_names() + # Example log: + # The first stage of the processor is ChatTemplateStage. + # Required input columns: + # messages: A list of messages in OpenAI chat format. + + ds = ray.data.range(300) + ds = processor(ds) + for row in ds.take_all(): + print(row) + """ + + pass + + +@PublicAPI(stability="alpha") +class SGLangEngineProcessorConfig(_SGLangEngineProcessorConfig): + """The configuration for the SGLang engine processor. + + Args: + model_source: The model source to use for the SGLang engine. + batch_size: The batch size to send to the vLLM engine. Large batch sizes are + likely to saturate the compute resources and could achieve higher throughput. + On the other hand, small batch sizes are more fault-tolerant and could + reduce bubbles in the data pipeline. You can tune the batch size to balance + the throughput and fault-tolerance based on your use case. + engine_kwargs: The kwargs to pass to the SGLang engine. Default engine kwargs are + tp_size: 1, dp_size: 1, skip_tokenizer_init: True. + task_type: The task type to use. If not specified, will use 'generate' by default. + runtime_env: The runtime environment to use for the SGLang engine. See + :ref:`this doc ` for more details. + max_pending_requests: The maximum number of pending requests. If not specified, + will use the default value from the SGLang engine. + max_concurrent_batches: The maximum number of concurrent batches in the engine. + This is to overlap the batch processing to avoid the tail latency of + each batch. The default value may not be optimal when the batch size + or the batch processing latency is too small, but it should be good + enough for batch size >= 64. + apply_chat_template: Whether to apply chat template. + chat_template: The chat template to use. This is usually not needed if the + model checkpoint already contains the chat template. + tokenize: Whether to tokenize the input before passing it to the vLLM engine. + If not, vLLM will tokenize the prompt in the engine. + detokenize: Whether to detokenize the output. + accelerator_type: The accelerator type used by the LLM stage in a processor. + Default to None, meaning that only the CPU will be used. + concurrency: The number of workers for data parallelism. Default to 1. + + Examples: + .. testcode:: + :skipif: True + + import ray + from ray.data.llm import SGLangEngineProcessorConfig, build_llm_processor + + config = SGLangEngineProcessorConfig( + model_source="meta-llama/Meta-Llama-3.1-8B-Instruct", + engine_kwargs=dict( + dtype="half", + ), + concurrency=1, + batch_size=64, + ) + processor = build_llm_processor( + config, + preprocess=lambda row: dict( + messages=[ + {"role": "system", "content": "You are a calculator"}, + {"role": "user", "content": f"{row['id']} ** 3 = ?"}, + ], + sampling_params=dict( + temperature=0.3, + max_new_tokens=20, + ), + ), + postprocess=lambda row: dict( + resp=row["generated_text"], + ), + ) + + ds = ray.data.range(300) + ds = processor(ds) + for row in ds.take_all(): + print(row) + """ + + pass + + +@PublicAPI(stability="alpha") +def build_llm_processor( + config: ProcessorConfig, + preprocess: Optional[UserDefinedFunction] = None, + postprocess: Optional[UserDefinedFunction] = None, +) -> Processor: + """Build a LLM processor using the given config. + + Args: + config: The processor config. + preprocess: An optional lambda function that takes a row (dict) as input + and returns a preprocessed row (dict). The output row must contain the + required fields for the following processing stages. Each row + can contain a `sampling_params` field which will be used by the + engine for row-specific sampling parameters. + Note that all columns will be carried over until the postprocess stage. + postprocess: An optional lambda function that takes a row (dict) as input + and returns a postprocessed row (dict). To keep all the original columns, + you can use the `**row` syntax to return all the original columns. + + Returns: + The built processor. + + Example: + .. testcode:: + :skipif: True + + import ray + from ray.data.llm import vLLMEngineProcessorConfig, build_llm_processor + + config = vLLMEngineProcessorConfig( + model_source="meta-llama/Meta-Llama-3.1-8B-Instruct", + engine_kwargs=dict( + enable_prefix_caching=True, + enable_chunked_prefill=True, + max_num_batched_tokens=4096, + ), + concurrency=1, + batch_size=64, + ) + + processor = build_llm_processor( + config, + preprocess=lambda row: dict( + messages=[ + {"role": "system", "content": "You are a calculator"}, + {"role": "user", "content": f"{row['id']} ** 3 = ?"}, + ], + sampling_params=dict( + temperature=0.3, + max_tokens=20, + detokenize=False, + ), + ), + postprocess=lambda row: dict( + resp=row["generated_text"], + **row, # This will return all the original columns in the dataset. + ), + ) + + ds = ray.data.range(300) + ds = processor(ds) + for row in ds.take_all(): + print(row) + """ + from ray.llm._internal.batch.processor import ProcessorBuilder + + return ProcessorBuilder.build( + config, + preprocess=preprocess, + postprocess=postprocess, + ) + + +__all__ = [ + "ProcessorConfig", + "Processor", + "HttpRequestProcessorConfig", + "vLLMEngineProcessorConfig", + "SGLangEngineProcessorConfig", + "build_llm_processor", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/preprocessor.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/preprocessor.py new file mode 100644 index 0000000000000000000000000000000000000000..e3f7ce37ee02119cefe2704fff1666e44cd92852 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/preprocessor.py @@ -0,0 +1,390 @@ +import abc +import base64 +import collections +import pickle +import warnings +from enum import Enum +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union + +from ray.air.util.data_batch_conversion import BatchFormat +from ray.util.annotations import DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + import numpy as np + import pandas as pd + + from ray.air.data_batch_type import DataBatchType + from ray.data import Dataset + + +@PublicAPI(stability="beta") +class PreprocessorNotFittedException(RuntimeError): + """Error raised when the preprocessor needs to be fitted first.""" + + pass + + +@PublicAPI(stability="beta") +class Preprocessor(abc.ABC): + """Implements an ML preprocessing operation. + + Preprocessors are stateful objects that can be fitted against a Dataset and used + to transform both local data batches and distributed data. For example, a + Normalization preprocessor may calculate the mean and stdev of a field during + fitting, and uses these attributes to implement its normalization transform. + + Preprocessors can also be stateless and transform data without needed to be fitted. + For example, a preprocessor may simply remove a column, which does not require + any state to be fitted. + + If you are implementing your own Preprocessor sub-class, you should override the + following: + + * ``_fit`` if your preprocessor is stateful. Otherwise, set + ``_is_fittable=False``. + * ``_transform_pandas`` and/or ``_transform_numpy`` for best performance, + implement both. Otherwise, the data will be converted to the match the + implemented method. + """ + + class FitStatus(str, Enum): + """The fit status of preprocessor.""" + + NOT_FITTABLE = "NOT_FITTABLE" + NOT_FITTED = "NOT_FITTED" + # Only meaningful for Chain preprocessors. + # At least one contained preprocessor in the chain preprocessor + # is fitted and at least one that can be fitted is not fitted yet. + # This is a state that show up if caller only interacts + # with the chain preprocessor through intended Preprocessor APIs. + PARTIALLY_FITTED = "PARTIALLY_FITTED" + FITTED = "FITTED" + + # Preprocessors that do not need to be fitted must override this. + _is_fittable = True + + def _check_has_fitted_state(self): + """Checks if the Preprocessor has fitted state. + + This is also used as an indiciation if the Preprocessor has been fit, following + convention from Ray versions prior to 2.6. + This allows preprocessors that have been fit in older versions of Ray to be + used to transform data in newer versions. + """ + + fitted_vars = [v for v in vars(self) if v.endswith("_")] + return bool(fitted_vars) + + def fit_status(self) -> "Preprocessor.FitStatus": + if not self._is_fittable: + return Preprocessor.FitStatus.NOT_FITTABLE + elif ( + hasattr(self, "_fitted") and self._fitted + ) or self._check_has_fitted_state(): + return Preprocessor.FitStatus.FITTED + else: + return Preprocessor.FitStatus.NOT_FITTED + + def fit(self, ds: "Dataset") -> "Preprocessor": + """Fit this Preprocessor to the Dataset. + + Fitted state attributes will be directly set in the Preprocessor. + + Calling it more than once will overwrite all previously fitted state: + ``preprocessor.fit(A).fit(B)`` is equivalent to ``preprocessor.fit(B)``. + + Args: + ds: Input dataset. + + Returns: + Preprocessor: The fitted Preprocessor with state attributes. + """ + fit_status = self.fit_status() + if fit_status == Preprocessor.FitStatus.NOT_FITTABLE: + # No-op as there is no state to be fitted. + return self + + if fit_status in ( + Preprocessor.FitStatus.FITTED, + Preprocessor.FitStatus.PARTIALLY_FITTED, + ): + warnings.warn( + "`fit` has already been called on the preprocessor (or at least one " + "contained preprocessors if this is a chain). " + "All previously fitted state will be overwritten!" + ) + + fitted_ds = self._fit(ds) + self._fitted = True + return fitted_ds + + def fit_transform( + self, + ds: "Dataset", + *, + transform_num_cpus: Optional[float] = None, + transform_memory: Optional[float] = None, + transform_batch_size: Optional[int] = None, + transform_concurrency: Optional[int] = None, + ) -> "Dataset": + """Fit this Preprocessor to the Dataset and then transform the Dataset. + + Calling it more than once will overwrite all previously fitted state: + ``preprocessor.fit_transform(A).fit_transform(B)`` + is equivalent to ``preprocessor.fit_transform(B)``. + + Args: + ds: Input Dataset. + transform_num_cpus: [experimental] The number of CPUs to reserve for each parallel map worker. + transform_memory: [experimental] The heap memory in bytes to reserve for each parallel map worker. + transform_batch_size: [experimental] The maximum number of rows to return. + transform_concurrency: [experimental] The maximum number of Ray workers to use concurrently. + + Returns: + ray.data.Dataset: The transformed Dataset. + """ + self.fit(ds) + return self.transform( + ds, + num_cpus=transform_num_cpus, + memory=transform_memory, + batch_size=transform_batch_size, + concurrency=transform_concurrency, + ) + + def transform( + self, + ds: "Dataset", + *, + batch_size: Optional[int] = None, + num_cpus: Optional[float] = None, + memory: Optional[float] = None, + concurrency: Optional[int] = None, + ) -> "Dataset": + """Transform the given dataset. + + Args: + ds: Input Dataset. + batch_size: [experimental] Advanced configuration for adjusting input size for each worker. + num_cpus: [experimental] The number of CPUs to reserve for each parallel map worker. + memory: [experimental] The heap memory in bytes to reserve for each parallel map worker. + concurrency: [experimental] The maximum number of Ray workers to use concurrently. + + Returns: + ray.data.Dataset: The transformed Dataset. + + Raises: + PreprocessorNotFittedException: if ``fit`` is not called yet. + """ + fit_status = self.fit_status() + if fit_status in ( + Preprocessor.FitStatus.PARTIALLY_FITTED, + Preprocessor.FitStatus.NOT_FITTED, + ): + raise PreprocessorNotFittedException( + "`fit` must be called before `transform`, " + "or simply use fit_transform() to run both steps" + ) + transformed_ds = self._transform( + ds, + batch_size=batch_size, + num_cpus=num_cpus, + memory=memory, + concurrency=concurrency, + ) + return transformed_ds + + def transform_batch(self, data: "DataBatchType") -> "DataBatchType": + """Transform a single batch of data. + + The data will be converted to the format supported by the Preprocessor, + based on which ``_transform_*`` methods are implemented. + + Args: + data: Input data batch. + + Returns: + DataBatchType: + The transformed data batch. This may differ + from the input type depending on which ``_transform_*`` methods + are implemented. + """ + fit_status = self.fit_status() + if fit_status in ( + Preprocessor.FitStatus.PARTIALLY_FITTED, + Preprocessor.FitStatus.NOT_FITTED, + ): + raise PreprocessorNotFittedException( + "`fit` must be called before `transform_batch`." + ) + return self._transform_batch(data) + + @DeveloperAPI + def _fit(self, ds: "Dataset") -> "Preprocessor": + """Sub-classes should override this instead of fit().""" + raise NotImplementedError() + + def _determine_transform_to_use(self) -> BatchFormat: + """Determine which batch format to use based on Preprocessor implementation. + + * If only `_transform_pandas` is implemented, then use ``pandas`` batch format. + * If only `_transform_numpy` is implemented, then use ``numpy`` batch format. + * If both are implemented, then use the Preprocessor defined preferred batch + format. + """ + + has_transform_pandas = ( + self.__class__._transform_pandas != Preprocessor._transform_pandas + ) + has_transform_numpy = ( + self.__class__._transform_numpy != Preprocessor._transform_numpy + ) + + if has_transform_numpy and has_transform_pandas: + return self.preferred_batch_format() + elif has_transform_numpy: + return BatchFormat.NUMPY + elif has_transform_pandas: + return BatchFormat.PANDAS + else: + raise NotImplementedError( + "None of `_transform_numpy` or `_transform_pandas` are implemented. " + "At least one of these transform functions must be implemented " + "for Preprocessor transforms." + ) + + def _transform( + self, + ds: "Dataset", + batch_size: Optional[int], + num_cpus: Optional[float] = None, + memory: Optional[float] = None, + concurrency: Optional[int] = None, + ) -> "Dataset": + transform_type = self._determine_transform_to_use() + + # Our user-facing batch format should only be pandas or NumPy, other + # formats {arrow, simple} are internal. + kwargs = self._get_transform_config() + if num_cpus is not None: + kwargs["num_cpus"] = num_cpus + if memory is not None: + kwargs["memory"] = memory + if batch_size is not None: + kwargs["batch_size"] = batch_size + if concurrency is not None: + kwargs["concurrency"] = concurrency + + if transform_type == BatchFormat.PANDAS: + return ds.map_batches( + self._transform_pandas, batch_format=BatchFormat.PANDAS, **kwargs + ) + elif transform_type == BatchFormat.NUMPY: + return ds.map_batches( + self._transform_numpy, batch_format=BatchFormat.NUMPY, **kwargs + ) + else: + raise ValueError( + "Invalid transform type returned from _determine_transform_to_use; " + f'"pandas" and "numpy" allowed, but got: {transform_type}' + ) + + def _get_transform_config(self) -> Dict[str, Any]: + """Returns kwargs to be passed to :meth:`ray.data.Dataset.map_batches`. + + This can be implemented by subclassing preprocessors. + """ + return {} + + def _transform_batch(self, data: "DataBatchType") -> "DataBatchType": + # For minimal install to locally import air modules + import numpy as np + import pandas as pd + + from ray.air.util.data_batch_conversion import ( + _convert_batch_type_to_numpy, + _convert_batch_type_to_pandas, + ) + + try: + import pyarrow + except ImportError: + pyarrow = None + + if not isinstance( + data, (pd.DataFrame, pyarrow.Table, collections.abc.Mapping, np.ndarray) + ): + raise ValueError( + "`transform_batch` is currently only implemented for Pandas " + "DataFrames, pyarrow Tables, NumPy ndarray and dictionary of " + f"ndarray. Got {type(data)}." + ) + + transform_type = self._determine_transform_to_use() + + if transform_type == BatchFormat.PANDAS: + return self._transform_pandas(_convert_batch_type_to_pandas(data)) + elif transform_type == BatchFormat.NUMPY: + return self._transform_numpy(_convert_batch_type_to_numpy(data)) + + @classmethod + def _derive_and_validate_output_columns( + cls, columns: List[str], output_columns: Optional[List[str]] + ) -> List[str]: + """Returns the output columns after validation. + + Checks if the columns are explicitly set, otherwise defaulting to + the input columns. + + Raises: + ValueError: If the length of the output columns does not match the + length of the input columns. + """ + + if output_columns and len(columns) != len(output_columns): + raise ValueError( + "Invalid output_columns: Got len(columns) != len(output_columns). " + "The length of columns and output_columns must match." + ) + return output_columns or columns + + @DeveloperAPI + def _transform_pandas(self, df: "pd.DataFrame") -> "pd.DataFrame": + """Run the transformation on a data batch in a Pandas DataFrame format.""" + raise NotImplementedError() + + @DeveloperAPI + def _transform_numpy( + self, np_data: Union["np.ndarray", Dict[str, "np.ndarray"]] + ) -> Union["np.ndarray", Dict[str, "np.ndarray"]]: + """Run the transformation on a data batch in a NumPy ndarray format.""" + raise NotImplementedError() + + @classmethod + @DeveloperAPI + def preferred_batch_format(cls) -> BatchFormat: + """Batch format hint for upstream producers to try yielding best block format. + + The preferred batch format to use if both `_transform_pandas` and + `_transform_numpy` are implemented. Defaults to Pandas. + + Can be overriden by Preprocessor classes depending on which transform + path is the most optimal. + """ + return BatchFormat.PANDAS + + @DeveloperAPI + def serialize(self) -> str: + """Return this preprocessor serialized as a string. + + Note: This is not a stable serialization format as it uses `pickle`. + """ + # Convert it to a plain string so that it can be included as JSON metadata + # in Trainer checkpoints. + return base64.b64encode(pickle.dumps(self)).decode("ascii") + + @staticmethod + @DeveloperAPI + def deserialize(serialized: str) -> "Preprocessor": + """Load the original preprocessor serialized via `self.serialize()`.""" + return pickle.loads(base64.b64decode(serialized)) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/random_access_dataset.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/random_access_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..309c55824eceaa6ba79939f724d2d144529ea76c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/random_access_dataset.py @@ -0,0 +1,295 @@ +import bisect +import logging +import random +import time +from collections import defaultdict +from typing import TYPE_CHECKING, Any, List, Optional + +import numpy as np + +import ray +from ray.data._internal.execution.interfaces.ref_bundle import ( + _ref_bundles_iterator_to_block_refs_list, +) +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data.block import BlockAccessor +from ray.data.context import DataContext +from ray.types import ObjectRef +from ray.util.annotations import PublicAPI + +try: + import pyarrow as pa +except ImportError: + pa = None + +if TYPE_CHECKING: + from ray.data import Dataset + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="alpha") +class RandomAccessDataset: + """A class that provides distributed, random access to a Dataset. + + See: ``Dataset.to_random_access_dataset()``. + """ + + def __init__( + self, + ds: "Dataset", + key: str, + num_workers: int, + ): + """Construct a RandomAccessDataset (internal API). + + The constructor is a private API. Use ``ds.to_random_access_dataset()`` + to construct a RandomAccessDataset. + """ + schema = ds.schema(fetch_if_missing=True) + if schema is None or isinstance(schema, type): + raise ValueError("RandomAccessDataset only supports Arrow-format blocks.") + + start = time.perf_counter() + logger.info("[setup] Indexing dataset by sort key.") + sorted_ds = ds.sort(key) + get_bounds = cached_remote_fn(_get_bounds) + bundles = sorted_ds.iter_internal_ref_bundles() + blocks = _ref_bundles_iterator_to_block_refs_list(bundles) + + logger.info("[setup] Computing block range bounds.") + bounds = ray.get([get_bounds.remote(b, key) for b in blocks]) + self._non_empty_blocks = [] + self._lower_bound = None + self._upper_bounds = [] + for i, b in enumerate(bounds): + if b: + self._non_empty_blocks.append(blocks[i]) + if self._lower_bound is None: + self._lower_bound = b[0] + self._upper_bounds.append(b[1]) + + logger.info("[setup] Creating {} random access workers.".format(num_workers)) + ctx = DataContext.get_current() + scheduling_strategy = ctx.scheduling_strategy + self._workers = [ + _RandomAccessWorker.options(scheduling_strategy=scheduling_strategy).remote( + key + ) + for _ in range(num_workers) + ] + ( + self._block_to_workers_map, + self._worker_to_blocks_map, + ) = self._compute_block_to_worker_assignments() + + logger.info( + "[setup] Worker to blocks assignment: {}".format(self._worker_to_blocks_map) + ) + ray.get( + [ + w.assign_blocks.remote( + { + i: self._non_empty_blocks[i] + for i in self._worker_to_blocks_map[w] + } + ) + for w in self._workers + ] + ) + + logger.info("[setup] Finished assigning blocks to workers.") + self._build_time = time.perf_counter() - start + + def _compute_block_to_worker_assignments(self): + # Return values. + block_to_workers: dict[int, List["ray.ActorHandle"]] = defaultdict(list) + worker_to_blocks: dict["ray.ActorHandle", List[int]] = defaultdict(list) + + # Aux data structures. + loc_to_workers: dict[str, List["ray.ActorHandle"]] = defaultdict(list) + locs = ray.get([w.ping.remote() for w in self._workers]) + for i, loc in enumerate(locs): + loc_to_workers[loc].append(self._workers[i]) + block_locs = ray.experimental.get_object_locations(self._non_empty_blocks) + + # First, try to assign all blocks to all workers at its location. + for block_idx, block in enumerate(self._non_empty_blocks): + block_info = block_locs[block] + locs = block_info.get("node_ids", []) + for loc in locs: + for worker in loc_to_workers[loc]: + block_to_workers[block_idx].append(worker) + worker_to_blocks[worker].append(block_idx) + + # Randomly assign any leftover blocks to at least one worker. + # TODO: the load balancing here could be improved. + for block_idx, block in enumerate(self._non_empty_blocks): + if len(block_to_workers[block_idx]) == 0: + worker = random.choice(self._workers) + block_to_workers[block_idx].append(worker) + worker_to_blocks[worker].append(block_idx) + + return block_to_workers, worker_to_blocks + + def get_async(self, key: Any) -> ObjectRef[Any]: + """Asynchronously finds the record for a single key. + + Args: + key: The key of the record to find. + + Returns: + ObjectRef containing the record (in pydict form), or None if not found. + """ + block_index = self._find_le(key) + if block_index is None: + return ray.put(None) + return self._worker_for(block_index).get.remote(block_index, key) + + def multiget(self, keys: List[Any]) -> List[Optional[Any]]: + """Synchronously find the records for a list of keys. + + Args: + keys: List of keys to find the records for. + + Returns: + List of found records (in pydict form), or None for missing records. + """ + batches = defaultdict(list) + for k in keys: + batches[self._find_le(k)].append(k) + futures = {} + for index, keybatch in batches.items(): + if index is None: + continue + fut = self._worker_for(index).multiget.remote( + [index] * len(keybatch), keybatch + ) + futures[index] = fut + results = {} + for i, fut in futures.items(): + keybatch = batches[i] + values = ray.get(fut) + for k, v in zip(keybatch, values): + results[k] = v + return [results.get(k) for k in keys] + + def stats(self) -> str: + """Returns a string containing access timing information.""" + stats = ray.get([w.stats.remote() for w in self._workers]) + total_time = sum(s["total_time"] for s in stats) + accesses = [s["num_accesses"] for s in stats] + blocks = [s["num_blocks"] for s in stats] + msg = "RandomAccessDataset:\n" + msg += "- Build time: {}s\n".format(round(self._build_time, 2)) + msg += "- Num workers: {}\n".format(len(stats)) + msg += "- Blocks per worker: {} min, {} max, {} mean\n".format( + min(blocks), max(blocks), int(sum(blocks) / len(blocks)) + ) + msg += "- Accesses per worker: {} min, {} max, {} mean\n".format( + min(accesses), max(accesses), int(sum(accesses) / len(accesses)) + ) + msg += "- Mean access time: {}us\n".format( + int(total_time / (1 + sum(accesses)) * 1e6) + ) + return msg + + def _worker_for(self, block_index: int): + return random.choice(self._block_to_workers_map[block_index]) + + def _find_le(self, x: Any) -> int: + i = bisect.bisect_left(self._upper_bounds, x) + if i >= len(self._upper_bounds) or x < self._lower_bound: + return None + return i + + +@ray.remote(num_cpus=0) +class _RandomAccessWorker: + def __init__(self, key_field): + self.blocks = None + self.key_field = key_field + self.num_accesses = 0 + self.total_time = 0 + + def assign_blocks(self, block_ref_dict): + self.blocks = {k: ray.get(ref) for k, ref in block_ref_dict.items()} + + def get(self, block_index, key): + start = time.perf_counter() + result = self._get(block_index, key) + self.total_time += time.perf_counter() - start + self.num_accesses += 1 + return result + + def multiget(self, block_indices, keys): + start = time.perf_counter() + block = self.blocks[block_indices[0]] + if len(set(block_indices)) == 1 and isinstance( + self.blocks[block_indices[0]], pa.Table + ): + # Fast path: use np.searchsorted for vectorized search on a single block. + # This is ~3x faster than the naive case. + block = self.blocks[block_indices[0]] + col = block[self.key_field] + indices = np.searchsorted(col, keys) + acc = BlockAccessor.for_block(block) + result = [ + acc._get_row(i) if k1.as_py() == k2 else None + for i, k1, k2 in zip(indices, col.take(indices), keys) + ] + else: + result = [self._get(i, k) for i, k in zip(block_indices, keys)] + self.total_time += time.perf_counter() - start + self.num_accesses += 1 + return result + + def ping(self): + return ray.get_runtime_context().get_node_id() + + def stats(self) -> dict: + return { + "num_blocks": len(self.blocks), + "num_accesses": self.num_accesses, + "total_time": self.total_time, + } + + def _get(self, block_index, key): + if block_index is None: + return None + block = self.blocks[block_index] + column = block[self.key_field] + if isinstance(block, pa.Table): + column = _ArrowListWrapper(column) + i = _binary_search_find(column, key) + if i is None: + return None + acc = BlockAccessor.for_block(block) + return acc._get_row(i) + + +def _binary_search_find(column, x): + i = bisect.bisect_left(column, x) + if i != len(column) and column[i] == x: + return i + return None + + +class _ArrowListWrapper: + def __init__(self, arrow_col): + self.arrow_col = arrow_col + + def __getitem__(self, i): + return self.arrow_col[i].as_py() + + def __len__(self): + return len(self.arrow_col) + + +def _get_bounds(block, key): + if len(block) == 0: + return None + b = (block[key][0], block[key][len(block) - 1]) + if isinstance(block, pa.Table): + b = (b[0].as_py(), b[1].as_py()) + return b diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/read_api.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/read_api.py new file mode 100644 index 0000000000000000000000000000000000000000..ec7b2ba6e26ce9caa922b7d179dcdebc36b0cc31 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/data/read_api.py @@ -0,0 +1,3995 @@ +import collections +import logging +import os +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + List, + Literal, + Optional, + Tuple, + TypeVar, + Union, +) + +import numpy as np +from packaging.version import parse as parse_version + +import ray +from ray._private.arrow_utils import get_pyarrow_version +from ray._private.auto_init_hook import wrap_auto_init +from ray.air.util.tensor_extensions.utils import _create_possibly_ragged_ndarray +from ray.data._internal.datasource.audio_datasource import AudioDatasource +from ray.data._internal.datasource.avro_datasource import AvroDatasource +from ray.data._internal.datasource.bigquery_datasource import BigQueryDatasource +from ray.data._internal.datasource.binary_datasource import BinaryDatasource +from ray.data._internal.datasource.clickhouse_datasource import ClickHouseDatasource +from ray.data._internal.datasource.csv_datasource import CSVDatasource +from ray.data._internal.datasource.delta_sharing_datasource import ( + DeltaSharingDatasource, +) +from ray.data._internal.datasource.hudi_datasource import HudiDatasource +from ray.data._internal.datasource.iceberg_datasource import IcebergDatasource +from ray.data._internal.datasource.image_datasource import ( + ImageDatasource, + ImageFileMetadataProvider, +) +from ray.data._internal.datasource.json_datasource import ( + JSON_FILE_EXTENSIONS, + ArrowJSONDatasource, + PandasJSONDatasource, +) +from ray.data._internal.datasource.lance_datasource import LanceDatasource +from ray.data._internal.datasource.mongo_datasource import MongoDatasource +from ray.data._internal.datasource.numpy_datasource import NumpyDatasource +from ray.data._internal.datasource.parquet_bulk_datasource import ParquetBulkDatasource +from ray.data._internal.datasource.parquet_datasource import ParquetDatasource +from ray.data._internal.datasource.range_datasource import RangeDatasource +from ray.data._internal.datasource.sql_datasource import SQLDatasource +from ray.data._internal.datasource.text_datasource import TextDatasource +from ray.data._internal.datasource.tfrecords_datasource import TFRecordDatasource +from ray.data._internal.datasource.torch_datasource import TorchDatasource +from ray.data._internal.datasource.unity_catalog_datasource import UnityCatalogConnector +from ray.data._internal.datasource.video_datasource import VideoDatasource +from ray.data._internal.datasource.webdataset_datasource import WebDatasetDatasource +from ray.data._internal.delegating_block_builder import DelegatingBlockBuilder +from ray.data._internal.logical.interfaces import LogicalPlan +from ray.data._internal.logical.operators.from_operators import ( + FromArrow, + FromBlocks, + FromItems, + FromNumpy, + FromPandas, +) +from ray.data._internal.logical.operators.read_operator import Read +from ray.data._internal.plan import ExecutionPlan +from ray.data._internal.remote_fn import cached_remote_fn +from ray.data._internal.stats import DatasetStats +from ray.data._internal.util import ( + _autodetect_parallelism, + get_table_block_metadata_schema, + ndarray_to_block, + pandas_df_to_arrow_block, +) +from ray.data.block import ( + Block, + BlockExecStats, + BlockMetadataWithSchema, +) +from ray.data.context import DataContext +from ray.data.dataset import Dataset, MaterializedDataset +from ray.data.datasource import ( + BaseFileMetadataProvider, + Connection, + Datasource, + PathPartitionFilter, +) +from ray.data.datasource.datasource import Reader +from ray.data.datasource.file_based_datasource import ( + FileShuffleConfig, + _validate_shuffle_arg, +) +from ray.data.datasource.file_meta_provider import ( + DefaultFileMetadataProvider, + FastFileMetadataProvider, +) +from ray.data.datasource.parquet_meta_provider import ParquetMetadataProvider +from ray.data.datasource.partitioning import Partitioning +from ray.types import ObjectRef +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + +if TYPE_CHECKING: + import daft + import dask + import datasets + import mars + import modin + import pandas + import pyarrow + import pymongoarrow.api + import pyspark + import tensorflow as tf + import torch + from pyiceberg.expressions import BooleanExpression + from tensorflow_metadata.proto.v0 import schema_pb2 + + from ray.data._internal.datasource.tfrecords_datasource import TFXReadOptions + +T = TypeVar("T") + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +def from_blocks(blocks: List[Block]): + """Create a :class:`~ray.data.Dataset` from a list of blocks. + + This method is primarily used for testing. Unlike other methods like + :func:`~ray.data.from_pandas` and :func:`~ray.data.from_arrow`, this method + gaurentees that it won't modify the number of blocks. + + Args: + blocks: List of blocks to create the dataset from. + + Returns: + A :class:`~ray.data.Dataset` holding the blocks. + """ + block_refs = [ray.put(block) for block in blocks] + meta_with_schema = [BlockMetadataWithSchema.from_block(block) for block in blocks] + + from_blocks_op = FromBlocks(block_refs, meta_with_schema) + execution_plan = ExecutionPlan( + DatasetStats(metadata={"FromBlocks": meta_with_schema}, parent=None), + DataContext.get_current().copy(), + ) + logical_plan = LogicalPlan(from_blocks_op, execution_plan._context) + return MaterializedDataset( + execution_plan, + logical_plan, + ) + + +@PublicAPI +def from_items( + items: List[Any], + *, + parallelism: int = -1, + override_num_blocks: Optional[int] = None, +) -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a list of local Python objects. + + Use this method to create small datasets from data that fits in memory. The column + name defaults to "item". + + Examples: + + >>> import ray + >>> ds = ray.data.from_items([1, 2, 3, 4, 5]) + >>> ds + MaterializedDataset(num_blocks=..., num_rows=5, schema={item: int64}) + >>> ds.schema() + Column Type + ------ ---- + item int64 + + Args: + items: List of local Python objects. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` holding the items. + """ + import builtins + + parallelism = _get_num_output_blocks(parallelism, override_num_blocks) + if parallelism == 0: + raise ValueError(f"parallelism must be -1 or > 0, got: {parallelism}") + + detected_parallelism, _, _ = _autodetect_parallelism( + parallelism, + ray.util.get_current_placement_group(), + DataContext.get_current(), + ) + # Truncate parallelism to number of items to avoid empty blocks. + detected_parallelism = min(len(items), detected_parallelism) + + if detected_parallelism > 0: + block_size, remainder = divmod(len(items), detected_parallelism) + else: + block_size, remainder = 0, 0 + # NOTE: We need to explicitly use the builtins range since we override range below, + # with the definition of ray.data.range. + blocks: List[ObjectRef[Block]] = [] + meta_with_schema: List[BlockMetadataWithSchema] = [] + for i in builtins.range(detected_parallelism): + stats = BlockExecStats.builder() + builder = DelegatingBlockBuilder() + # Evenly distribute remainder across block slices while preserving record order. + block_start = i * block_size + min(i, remainder) + block_end = (i + 1) * block_size + min(i + 1, remainder) + for j in builtins.range(block_start, block_end): + item = items[j] + if not isinstance(item, collections.abc.Mapping): + item = {"item": item} + builder.add(item) + block = builder.build() + blocks.append(ray.put(block)) + meta_with_schema.append( + BlockMetadataWithSchema.from_block(block, stats=stats.build()) + ) + + from_items_op = FromItems(blocks, meta_with_schema) + execution_plan = ExecutionPlan( + DatasetStats(metadata={"FromItems": meta_with_schema}, parent=None), + DataContext.get_current().copy(), + ) + logical_plan = LogicalPlan(from_items_op, execution_plan._context) + return MaterializedDataset( + execution_plan, + logical_plan, + ) + + +@PublicAPI +def range( + n: int, + *, + parallelism: int = -1, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Creates a :class:`~ray.data.Dataset` from a range of integers [0..n). + + This function allows for easy creation of synthetic datasets for testing or + benchmarking :ref:`Ray Data `. The column name defaults to "id". + + Examples: + + >>> import ray + >>> ds = ray.data.range(10000) + >>> ds + Dataset(num_rows=10000, schema={id: int64}) + >>> ds.map(lambda row: {"id": row["id"] * 2}).take(4) + [{'id': 0}, {'id': 2}, {'id': 4}, {'id': 6}] + + Args: + n: The upper bound of the range of integers. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` producing the integers from the range 0 to n. + + .. seealso:: + + :meth:`~ray.data.range_tensor` + Call this method for creating synthetic datasets of tensor data. + + """ + datasource = RangeDatasource(n=n, block_format="arrow", column_name="id") + return read_datasource( + datasource, + parallelism=parallelism, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def range_tensor( + n: int, + *, + shape: Tuple = (1,), + parallelism: int = -1, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Creates a :class:`~ray.data.Dataset` tensors of the provided shape from range + [0...n]. + + This function allows for easy creation of synthetic tensor datasets for testing or + benchmarking :ref:`Ray Data `. The column name defaults to "data". + + Examples: + + >>> import ray + >>> ds = ray.data.range_tensor(1000, shape=(2, 2)) + >>> ds + Dataset(num_rows=1000, schema={data: numpy.ndarray(shape=(2, 2), dtype=int64)}) + >>> ds.map_batches(lambda row: {"data": row["data"] * 2}).take(2) + [{'data': array([[0, 0], + [0, 0]])}, {'data': array([[2, 2], + [2, 2]])}] + + Args: + n: The upper bound of the range of tensor records. + shape: The shape of each tensor in the dataset. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` producing the tensor data from range 0 to n. + + .. seealso:: + + :meth:`~ray.data.range` + Call this method to create synthetic datasets of integer data. + + """ + datasource = RangeDatasource( + n=n, block_format="tensor", column_name="data", tensor_shape=tuple(shape) + ) + return read_datasource( + datasource, + parallelism=parallelism, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +@wrap_auto_init +def read_datasource( + datasource: Datasource, + *, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **read_args, +) -> Dataset: + """Read a stream from a custom :class:`~ray.data.Datasource`. + + Args: + datasource: The :class:`~ray.data.Datasource` to read data from. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + read_args: Additional kwargs to pass to the :class:`~ray.data.Datasource` + implementation. + + Returns: + :class:`~ray.data.Dataset` that reads data from the :class:`~ray.data.Datasource`. + """ # noqa: E501 + parallelism = _get_num_output_blocks(parallelism, override_num_blocks) + + ctx = DataContext.get_current() + + if ray_remote_args is None: + ray_remote_args = {} + + if not datasource.supports_distributed_reads: + ray_remote_args["scheduling_strategy"] = NodeAffinitySchedulingStrategy( + ray.get_runtime_context().get_node_id(), + soft=False, + ) + + if "scheduling_strategy" not in ray_remote_args: + ray_remote_args["scheduling_strategy"] = ctx.scheduling_strategy + + datasource_or_legacy_reader = _get_datasource_or_legacy_reader( + datasource, + ctx, + read_args, + ) + + cur_pg = ray.util.get_current_placement_group() + requested_parallelism, _, inmemory_size = _autodetect_parallelism( + parallelism, + ctx.target_max_block_size, + DataContext.get_current(), + datasource_or_legacy_reader, + placement_group=cur_pg, + ) + + # TODO(hchen/chengsu): Remove the duplicated get_read_tasks call here after + # removing LazyBlockList code path. + read_tasks = datasource_or_legacy_reader.get_read_tasks(requested_parallelism) + + stats = DatasetStats( + metadata={"Read": [read_task.metadata for read_task in read_tasks]}, + parent=None, + ) + read_op = Read( + datasource, + datasource_or_legacy_reader, + parallelism, + inmemory_size, + len(read_tasks) if read_tasks else 0, + ray_remote_args, + concurrency, + ) + execution_plan = ExecutionPlan( + stats, + DataContext.get_current().copy(), + ) + logical_plan = LogicalPlan(read_op, execution_plan._context) + return Dataset( + plan=execution_plan, + logical_plan=logical_plan, + ) + + +@PublicAPI(stability="alpha") +def read_audio( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Optional[Partitioning] = None, + include_paths: bool = False, + ignore_missing_paths: bool = False, + file_extensions: Optional[List[str]] = AudioDatasource._FILE_EXTENSIONS, + shuffle: Union[Literal["files"], None] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, +): + """Creates a :class:`~ray.data.Dataset` from audio files. + + The column names default to "amplitude" and "sample_rate". + + Examples: + >>> import ray + >>> path = "s3://anonymous@air-example-data-2/6G-audio-data-LibriSpeech-train-clean-100-flac/train-clean-100/5022/29411/5022-29411-0000.flac" + >>> ds = ray.data.read_audio(path) + >>> ds.schema() + Column Type + ------ ---- + amplitude numpy.ndarray(shape=(1, 191760), dtype=float) + sample_rate int64 + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + filesystem: The pyarrow filesystem + implementation to read from. These filesystems are specified in the + `pyarrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. Use + with a custom callback to read only selected partitions of a dataset. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to ``None``. + include_paths: If ``True``, include the path to each image. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file/directory paths in ``paths`` + that are not found. Defaults to False. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + ray_remote_args: kwargs passed to :meth:`~ray.remote` in the read tasks. + + Returns: + A :class:`~ray.data.Dataset` containing audio amplitudes and associated + metadata. + """ # noqa: E501 + datasource = AudioDatasource( + paths, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=DefaultFileMetadataProvider(), + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_videos( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Optional[Partitioning] = None, + include_paths: bool = False, + include_timestamps: bool = False, + ignore_missing_paths: bool = False, + file_extensions: Optional[List[str]] = VideoDatasource._FILE_EXTENSIONS, + shuffle: Union[Literal["files"], None] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, +): + """Creates a :class:`~ray.data.Dataset` from video files. + + Each row in the resulting dataset represents a video frame. The column names default + to "frame", "frame_index" and "frame_timestamp". + + Examples: + >>> import ray + >>> path = "s3://anonymous@ray-example-data/basketball.mp4" + >>> ds = ray.data.read_videos(path) + >>> ds.schema() + Column Type + ------ ---- + frame numpy.ndarray(shape=(720, 1280, 3), dtype=uint8) + frame_index int64 + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + filesystem: The pyarrow filesystem + implementation to read from. These filesystems are specified in the + `pyarrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. Use + with a custom callback to read only selected partitions of a dataset. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to ``None``. + include_paths: If ``True``, include the path to each image. File paths are + stored in the ``'path'`` column. + include_timestmaps: If ``True``, include the frame timestamps from the video + as a ``'frame_timestamp'`` column. + ignore_missing_paths: If True, ignores any file/directory paths in ``paths`` + that are not found. Defaults to False. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + ray_remote_args: kwargs passed to :meth:`~ray.remote` in the read tasks. + + Returns: + A :class:`~ray.data.Dataset` containing video frames from the video files. + """ + datasource = VideoDatasource( + paths, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=DefaultFileMetadataProvider(), + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + include_timestamps=include_timestamps, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_mongo( + uri: str, + database: str, + collection: str, + *, + pipeline: Optional[List[Dict]] = None, + schema: Optional["pymongoarrow.api.Schema"] = None, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **mongo_args, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from a MongoDB database. + + The data to read from is specified via the ``uri``, ``database`` and ``collection`` + of the MongoDB. The dataset is created from the results of executing + ``pipeline`` against the ``collection``. If ``pipeline`` is None, the entire + ``collection`` is read. + + .. tip:: + + For more details about these MongoDB concepts, see the following: + - URI: https://www.mongodb.com/docs/manual/reference/connection-string/ + - Database and Collection: https://www.mongodb.com/docs/manual/core/databases-and-collections/ + - Pipeline: https://www.mongodb.com/docs/manual/core/aggregation-pipeline/ + + To read the MongoDB in parallel, the execution of the pipeline is run on partitions + of the collection, with a Ray read task to handle a partition. Partitions are + created in an attempt to evenly distribute the documents into the specified number + of partitions. The number of partitions is determined by ``parallelism`` which can + be requested from this interface or automatically chosen if unspecified (see the + ``parallelism`` arg below). + + Examples: + >>> import ray + >>> from pymongoarrow.api import Schema # doctest: +SKIP + >>> ds = ray.data.read_mongo( # doctest: +SKIP + ... uri="mongodb://username:password@mongodb0.example.com:27017/?authSource=admin", # noqa: E501 + ... database="my_db", + ... collection="my_collection", + ... pipeline=[{"$match": {"col2": {"$gte": 0, "$lt": 100}}}, {"$sort": "sort_field"}], # noqa: E501 + ... schema=Schema({"col1": pa.string(), "col2": pa.int64()}), + ... override_num_blocks=10, + ... ) + + Args: + uri: The URI of the source MongoDB where the dataset is + read from. For the URI format, see details in the `MongoDB docs `_. + database: The name of the database hosted in the MongoDB. This database + must exist otherwise ValueError is raised. + collection: The name of the collection in the database. This collection + must exist otherwise ValueError is raised. + pipeline: A `MongoDB pipeline `_, which is executed on the given collection + with results used to create Dataset. If None, the entire collection will + be read. + schema: The schema used to read the collection. If None, it'll be inferred from + the results of pipeline. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + mongo_args: kwargs passed to `aggregate_arrow_all() `_ in pymongoarrow in producing + Arrow-formatted results. + + Returns: + :class:`~ray.data.Dataset` producing rows from the results of executing the pipeline on the specified MongoDB collection. + + Raises: + ValueError: if ``database`` doesn't exist. + ValueError: if ``collection`` doesn't exist. + """ + datasource = MongoDatasource( + uri=uri, + database=database, + collection=collection, + pipeline=pipeline, + schema=schema, + **mongo_args, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_bigquery( + project_id: str, + dataset: Optional[str] = None, + query: Optional[str] = None, + *, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Create a dataset from BigQuery. + + The data to read from is specified via the ``project_id``, ``dataset`` + and/or ``query`` parameters. The dataset is created from the results of + executing ``query`` if a query is provided. Otherwise, the entire + ``dataset`` is read. + + For more information about BigQuery, see the following concepts: + + - Project id: `Creating and Managing Projects `_ + + - Dataset: `Datasets Intro `_ + + - Query: `Query Syntax `_ + + This method uses the BigQuery Storage Read API which reads in parallel, + with a Ray read task to handle each stream. The number of streams is + determined by ``parallelism`` which can be requested from this interface + or automatically chosen if unspecified (see the ``parallelism`` arg below). + + .. warning:: + The maximum query response size is 10GB. + + Examples: + .. testcode:: + :skipif: True + + import ray + # Users will need to authenticate beforehand (https://cloud.google.com/sdk/gcloud/reference/auth/login) + ds = ray.data.read_bigquery( + project_id="my_project", + query="SELECT * FROM `bigquery-public-data.samples.gsod` LIMIT 1000", + ) + + Args: + project_id: The name of the associated Google Cloud Project that hosts the dataset to read. + For more information, see `Creating and Managing Projects `_. + dataset: The name of the dataset hosted in BigQuery in the format of ``dataset_id.table_id``. + Both the dataset_id and table_id must exist otherwise an exception will be raised. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + Dataset producing rows from the results of executing the query (or reading the entire dataset) + on the specified BigQuery dataset. + """ # noqa: E501 + datasource = BigQueryDatasource(project_id=project_id, dataset=dataset, query=query) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def read_parquet( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + columns: Optional[List[str]] = None, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + tensor_column_schema: Optional[Dict[str, Tuple[np.dtype, Tuple[int, ...]]]] = None, + meta_provider: Optional[ParquetMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Optional[Partitioning] = Partitioning("hive"), + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + include_paths: bool = False, + file_extensions: Optional[List[str]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **arrow_parquet_args, +) -> Dataset: + """Creates a :class:`~ray.data.Dataset` from parquet files. + + + Examples: + Read a file in remote storage. + + >>> import ray + >>> ds = ray.data.read_parquet("s3://anonymous@ray-example-data/iris.parquet") + >>> ds.schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + petal.length double + petal.width double + variety string + + Read a directory in remote storage. + + >>> ds = ray.data.read_parquet("s3://anonymous@ray-example-data/iris-parquet/") + + Read multiple local files. + + >>> ray.data.read_parquet( + ... ["local:///path/to/file1", "local:///path/to/file2"]) # doctest: +SKIP + + Specify a schema for the parquet file. + + >>> import pyarrow as pa + >>> fields = [("sepal.length", pa.float32()), + ... ("sepal.width", pa.float32()), + ... ("petal.length", pa.float32()), + ... ("petal.width", pa.float32()), + ... ("variety", pa.string())] + >>> ds = ray.data.read_parquet("s3://anonymous@ray-example-data/iris.parquet", + ... schema=pa.schema(fields)) + >>> ds.schema() + Column Type + ------ ---- + sepal.length float + sepal.width float + petal.length float + petal.width float + variety string + + The Parquet reader also supports projection and filter pushdown, allowing column + selection and row filtering to be pushed down to the file scan. + + .. testcode:: + + import pyarrow as pa + + # Create a Dataset by reading a Parquet file, pushing column selection and + # row filtering down to the file scan. + ds = ray.data.read_parquet( + "s3://anonymous@ray-example-data/iris.parquet", + columns=["sepal.length", "variety"], + filter=pa.dataset.field("sepal.length") > 5.0, + ) + + ds.show(2) + + .. testoutput:: + + {'sepal.length': 5.1, 'variety': 'Setosa'} + {'sepal.length': 5.4, 'variety': 'Setosa'} + + For further arguments you can pass to PyArrow as a keyword argument, see the + `PyArrow API reference `_. + + Args: + paths: A single file path or directory, or a list of file paths. Multiple + directories are not supported. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `pyarrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the ``S3FileSystem`` is + used. If ``None``, this function uses a system-chosen implementation. + columns: A list of column names to read. Only the specified columns are + read during the file scan. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + tensor_column_schema: A dict of column name to PyArrow dtype and shape + mappings for converting a Parquet column containing serialized + tensors (ndarrays) as their elements to PyArrow tensors. This function + assumes that the tensors are serialized in the raw + NumPy array format in C-contiguous order (e.g., via + `arr.tobytes()`). + meta_provider: A :ref:`file metadata provider `. Custom + metadata providers may be able to resolve file metadata more quickly and/or + accurately. In most cases you do not need to set this parameter. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. Use + with a custom callback to read only selected partitions of a dataset. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to HIVE partitioning. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + arrow_parquet_args: Other parquet read options to pass to PyArrow. For the full + set of arguments, see the `PyArrow API `_ + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` producing records read from the specified parquet + files. + """ + _emit_meta_provider_deprecation_warning(meta_provider) + _validate_shuffle_arg(shuffle) + + if meta_provider is None: + meta_provider = ParquetMetadataProvider() + arrow_parquet_args = _resolve_parquet_args( + tensor_column_schema, + **arrow_parquet_args, + ) + + dataset_kwargs = arrow_parquet_args.pop("dataset_kwargs", None) + _block_udf = arrow_parquet_args.pop("_block_udf", None) + schema = arrow_parquet_args.pop("schema", None) + datasource = ParquetDatasource( + paths, + columns=columns, + dataset_kwargs=dataset_kwargs, + to_batch_kwargs=arrow_parquet_args, + _block_udf=_block_udf, + filesystem=filesystem, + schema=schema, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="beta") +def read_images( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + meta_provider: Optional[BaseFileMetadataProvider] = None, + ray_remote_args: Dict[str, Any] = None, + arrow_open_file_args: Optional[Dict[str, Any]] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Partitioning = None, + size: Optional[Tuple[int, int]] = None, + mode: Optional[str] = None, + include_paths: bool = False, + ignore_missing_paths: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = ImageDatasource._FILE_EXTENSIONS, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Creates a :class:`~ray.data.Dataset` from image files. + + The column name defaults to "image". + + Examples: + >>> import ray + >>> path = "s3://anonymous@ray-example-data/batoidea/JPEGImages/" + >>> ds = ray.data.read_images(path) + >>> ds.schema() + Column Type + ------ ---- + image numpy.ndarray(shape=(32, 32, 3), dtype=uint8) + + If you need image file paths, set ``include_paths=True``. + + >>> ds = ray.data.read_images(path, include_paths=True) + >>> ds.schema() + Column Type + ------ ---- + image numpy.ndarray(shape=(32, 32, 3), dtype=uint8) + path string + >>> ds.take(1)[0]["path"] + 'ray-example-data/batoidea/JPEGImages/1.jpeg' + + If your images are arranged like: + + .. code:: + + root/dog/xxx.png + root/dog/xxy.png + + root/cat/123.png + root/cat/nsdf3.png + + Then you can include the labels by specifying a + :class:`~ray.data.datasource.partitioning.Partitioning`. + + >>> import ray + >>> from ray.data.datasource.partitioning import Partitioning + >>> root = "s3://anonymous@ray-example-data/image-datasets/dir-partitioned" + >>> partitioning = Partitioning("dir", field_names=["class"], base_dir=root) + >>> ds = ray.data.read_images(root, size=(224, 224), partitioning=partitioning) + >>> ds.schema() + Column Type + ------ ---- + image numpy.ndarray(shape=(224, 224, 3), dtype=uint8) + class string + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + filesystem: The pyarrow filesystem + implementation to read from. These filesystems are specified in the + `pyarrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + arrow_open_file_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. Use + with a custom callback to read only selected partitions of a dataset. + By default, this filters out any file paths whose file extension does not + match ``*.png``, ``*.jpg``, ``*.jpeg``, ``*.tiff``, ``*.bmp``, or ``*.gif``. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to ``None``. + size: The desired height and width of loaded images. If unspecified, images + retain their original shape. + mode: A `Pillow mode `_ + describing the desired type and depth of pixels. If unspecified, image + modes are inferred by + `Pillow `_. + include_paths: If ``True``, include the path to each image. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file/directory paths in ``paths`` + that are not found. Defaults to False. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` producing tensors that represent the images at + the specified paths. For information on working with tensors, read the + :ref:`tensor data guide `. + + Raises: + ValueError: if ``size`` contains non-positive numbers. + ValueError: if ``mode`` is unsupported. + """ + _emit_meta_provider_deprecation_warning(meta_provider) + + if meta_provider is None: + meta_provider = ImageFileMetadataProvider() + + datasource = ImageDatasource( + paths, + size=size, + mode=mode, + include_paths=include_paths, + filesystem=filesystem, + meta_provider=meta_provider, + open_stream_args=arrow_open_file_args, + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@Deprecated +def read_parquet_bulk( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + columns: Optional[List[str]] = None, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + arrow_open_file_args: Optional[Dict[str, Any]] = None, + tensor_column_schema: Optional[Dict[str, Tuple[np.dtype, Tuple[int, ...]]]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + include_paths: bool = False, + file_extensions: Optional[List[str]] = ParquetBulkDatasource._FILE_EXTENSIONS, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **arrow_parquet_args, +) -> Dataset: + """Create :class:`~ray.data.Dataset` from parquet files without reading metadata. + + Use :meth:`~ray.data.read_parquet` for most cases. + + Use :meth:`~ray.data.read_parquet_bulk` if all the provided paths point to files + and metadata fetching using :meth:`~ray.data.read_parquet` takes too long or the + parquet files do not all have a unified schema. + + Performance slowdowns are possible when using this method with parquet files that + are very large. + + .. warning:: + + Only provide file paths as input (i.e., no directory paths). An + OSError is raised if one or more paths point to directories. If your + use-case requires directory paths, use :meth:`~ray.data.read_parquet` + instead. + + Examples: + Read multiple local files. You should always provide only input file paths + (i.e. no directory paths) when known to minimize read latency. + + >>> ray.data.read_parquet_bulk( # doctest: +SKIP + ... ["/path/to/file1", "/path/to/file2"]) + + Args: + paths: A single file path or a list of file paths. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are + specified in the + `PyArrow docs `_. + Specify this parameter if you need to provide specific configurations to + the filesystem. By default, the filesystem is automatically selected based + on the scheme of the paths. For example, if the path begins with ``s3://``, + the `S3FileSystem` is used. + columns: A list of column names to read. Only the + specified columns are read during the file scan. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + arrow_open_file_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + tensor_column_schema: A dict of column name to PyArrow dtype and shape + mappings for converting a Parquet column containing serialized + tensors (ndarrays) as their elements to PyArrow tensors. This function + assumes that the tensors are serialized in the raw + NumPy array format in C-contiguous order (e.g. via + `arr.tobytes()`). + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. Use + with a custom callback to read only selected partitions of a dataset. + By default, this filters out any file paths whose file extension does not + match "*.parquet*". + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + arrow_parquet_args: Other parquet read options to pass to PyArrow. For the full + set of arguments, see + the `PyArrow API `_ + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` producing records read from the specified paths. + """ + _emit_meta_provider_deprecation_warning(meta_provider) + + warnings.warn( + "`read_parquet_bulk` is deprecated and will be removed after May 2025. Use " + "`read_parquet` instead.", + DeprecationWarning, + ) + + if meta_provider is None: + meta_provider = FastFileMetadataProvider() + read_table_args = _resolve_parquet_args( + tensor_column_schema, + **arrow_parquet_args, + ) + if columns is not None: + read_table_args["columns"] = columns + + datasource = ParquetBulkDatasource( + paths, + read_table_args=read_table_args, + filesystem=filesystem, + open_stream_args=arrow_open_file_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def read_json( + paths: Union[str, List[str]], + *, + lines: bool = False, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Partitioning = Partitioning("hive"), + include_paths: bool = False, + ignore_missing_paths: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = JSON_FILE_EXTENSIONS, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **arrow_json_args, +) -> Dataset: + """Creates a :class:`~ray.data.Dataset` from JSON and JSONL files. + + For JSON file, the whole file is read as one row. + For JSONL file, each line of file is read as separate row. + + Examples: + Read a JSON file in remote storage. + + >>> import ray + >>> ds = ray.data.read_json("s3://anonymous@ray-example-data/log.json") + >>> ds.schema() + Column Type + ------ ---- + timestamp timestamp[...] + size int64 + + Read a JSONL file in remote storage. + + >>> ds = ray.data.read_json("s3://anonymous@ray-example-data/train.jsonl", lines=True) + >>> ds.schema() + Column Type + ------ ---- + input + + Read multiple local files. + + >>> ray.data.read_json( # doctest: +SKIP + ... ["local:///path/to/file1", "local:///path/to/file2"]) + + Read multiple directories. + + >>> ray.data.read_json( # doctest: +SKIP + ... ["s3://bucket/path1", "s3://bucket/path2"]) + + By default, :meth:`~ray.data.read_json` parses + `Hive-style partitions `_ + from file paths. If your data adheres to a different partitioning scheme, set + the ``partitioning`` parameter. + + >>> ds = ray.data.read_json("s3://anonymous@ray-example-data/year=2022/month=09/sales.json") + >>> ds.take(1) + [{'order_number': 10107, 'quantity': 30, 'year': '2022', 'month': '09'}] + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + lines: [Experimental] If ``True``, read files assuming line-delimited JSON. + If set, will ignore the ``filesystem``, ``arrow_open_stream_args``, and + ``arrow_json_args`` parameters. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `PyArrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. + Use with a custom callback to read only selected partitions of a + dataset. + By default, this filters out any file paths whose file extension does not + match "*.json" or "*.jsonl". + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. By default, this function parses + `Hive-style partitions `_. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file paths in ``paths`` that are not + found. Defaults to False. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to ``FileShuffleConfig``, you can pass a random seed to shuffle + the input files, e.g. ``FileShuffleConfig(seed=42)``. + Defaults to not shuffle with ``None``. + arrow_json_args: JSON read options to pass to `pyarrow.json.read_json `_. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` producing records read from the specified paths. + """ # noqa: E501 + _emit_meta_provider_deprecation_warning(meta_provider) + + if lines: + incompatible_params = { + "filesystem": filesystem, + "arrow_open_stream_args": arrow_open_stream_args, + "arrow_json_args": arrow_json_args, + } + for param, value in incompatible_params.items(): + if value: + raise ValueError(f"`{param}` is not supported when `lines=True`. ") + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + + file_based_datasource_kwargs = dict( + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + if lines: + target_output_size_bytes = ( + ray.data.context.DataContext.get_current().target_max_block_size + ) + datasource = PandasJSONDatasource( + paths, + target_output_size_bytes=target_output_size_bytes, + **file_based_datasource_kwargs, + ) + else: + datasource = ArrowJSONDatasource( + paths, + arrow_json_args=arrow_json_args, + **file_based_datasource_kwargs, + ) + + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def read_csv( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Partitioning = Partitioning("hive"), + include_paths: bool = False, + ignore_missing_paths: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **arrow_csv_args, +) -> Dataset: + """Creates a :class:`~ray.data.Dataset` from CSV files. + + Examples: + Read a file in remote storage. + + >>> import ray + >>> ds = ray.data.read_csv("s3://anonymous@ray-example-data/iris.csv") + >>> ds.schema() + Column Type + ------ ---- + sepal length (cm) double + sepal width (cm) double + petal length (cm) double + petal width (cm) double + target int64 + + Read multiple local files. + + >>> ray.data.read_csv( # doctest: +SKIP + ... ["local:///path/to/file1", "local:///path/to/file2"]) + + Read a directory from remote storage. + + >>> ds = ray.data.read_csv("s3://anonymous@ray-example-data/iris-csv/") + + Read files that use a different delimiter. For more uses of ParseOptions see + https://arrow.apache.org/docs/python/generated/pyarrow.csv.ParseOptions.html # noqa: #501 + + >>> from pyarrow import csv + >>> parse_options = csv.ParseOptions(delimiter="\\t") + >>> ds = ray.data.read_csv( + ... "s3://anonymous@ray-example-data/iris.tsv", + ... parse_options=parse_options) + >>> ds.schema() + Column Type + ------ ---- + sepal.length double + sepal.width double + petal.length double + petal.width double + variety string + + Convert a date column with a custom format from a CSV file. For more uses of ConvertOptions see https://arrow.apache.org/docs/python/generated/pyarrow.csv.ConvertOptions.html # noqa: #501 + + >>> from pyarrow import csv + >>> convert_options = csv.ConvertOptions( + ... timestamp_parsers=["%m/%d/%Y"]) + >>> ds = ray.data.read_csv( + ... "s3://anonymous@ray-example-data/dow_jones.csv", + ... convert_options=convert_options) + + By default, :meth:`~ray.data.read_csv` parses + `Hive-style partitions `_ + from file paths. If your data adheres to a different partitioning scheme, set + the ``partitioning`` parameter. + + >>> ds = ray.data.read_csv("s3://anonymous@ray-example-data/year=2022/month=09/sales.csv") + >>> ds.take(1) + [{'order_number': 10107, 'quantity': 30, 'year': '2022', 'month': '09'}] + + By default, :meth:`~ray.data.read_csv` reads all files from file paths. If you want to filter + files by file extensions, set the ``file_extensions`` parameter. + + Read only ``*.csv`` files from a directory. + + >>> ray.data.read_csv("s3://anonymous@ray-example-data/different-extensions/", + ... file_extensions=["csv"]) + Dataset(num_rows=?, schema=...) + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `pyarrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. + Use with a custom callback to read only selected partitions of a + dataset. By default, no files are filtered. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. By default, this function parses + `Hive-style partitions `_. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file paths in ``paths`` that are not + found. Defaults to False. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + arrow_csv_args: CSV read options to pass to + `pyarrow.csv.open_csv `_ + when opening CSV files. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` producing records read from the specified paths. + """ + _emit_meta_provider_deprecation_warning(meta_provider) + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + + datasource = CSVDatasource( + paths, + arrow_csv_args=arrow_csv_args, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def read_text( + paths: Union[str, List[str]], + *, + encoding: str = "utf-8", + drop_empty_lines: bool = True, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + ray_remote_args: Optional[Dict[str, Any]] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Partitioning = None, + include_paths: bool = False, + ignore_missing_paths: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from lines stored in text files. + + The column name default to "text". + + Examples: + Read a file in remote storage. + + >>> import ray + >>> ds = ray.data.read_text("s3://anonymous@ray-example-data/this.txt") + >>> ds.schema() + Column Type + ------ ---- + text string + + Read multiple local files. + + >>> ray.data.read_text( # doctest: +SKIP + ... ["local:///path/to/file1", "local:///path/to/file2"]) + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + encoding: The encoding of the files (e.g., "utf-8" or "ascii"). + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `PyArrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks and + in the subsequent text decoding map task. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. + Use with a custom callback to read only selected partitions of a + dataset. By default, no files are filtered. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to ``None``. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file paths in ``paths`` that are not + found. Defaults to False. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` producing lines of text read from the specified + paths. + """ + _emit_meta_provider_deprecation_warning(meta_provider) + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + + datasource = TextDatasource( + paths, + drop_empty_lines=drop_empty_lines, + encoding=encoding, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def read_avro( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + ray_remote_args: Optional[Dict[str, Any]] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Partitioning = None, + include_paths: bool = False, + ignore_missing_paths: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from records stored in Avro files. + + Examples: + Read an Avro file in remote storage or local storage. + + >>> import ray + >>> ds = ray.data.read_avro("s3://anonymous@ray-example-data/mnist.avro") + >>> ds.schema() + Column Type + ------ ---- + features list + label int64 + dataType string + + >>> ray.data.read_avro( # doctest: +SKIP + ... ["local:///path/to/file1", "local:///path/to/file2"]) + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `PyArrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks and + in the subsequent text decoding map task. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. + Use with a custom callback to read only selected partitions of a + dataset. By default, no files are filtered. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to ``None``. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file paths in ``paths`` that are not + found. Defaults to False. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` holding records from the Avro files. + """ + _emit_meta_provider_deprecation_warning(meta_provider) + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + + datasource = AvroDatasource( + paths, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def read_numpy( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Partitioning = None, + include_paths: bool = False, + ignore_missing_paths: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = NumpyDatasource._FILE_EXTENSIONS, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **numpy_load_args, +) -> Dataset: + """Create an Arrow dataset from numpy files. + + The column name defaults to "data". + + Examples: + Read a directory of files in remote storage. + + >>> import ray + >>> ray.data.read_numpy("s3://bucket/path") # doctest: +SKIP + + Read multiple local files. + + >>> ray.data.read_numpy(["/path/to/file1", "/path/to/file2"]) # doctest: +SKIP + + Read multiple directories. + + >>> ray.data.read_numpy( # doctest: +SKIP + ... ["s3://bucket/path1", "s3://bucket/path2"]) + + Args: + paths: A single file/directory path or a list of file/directory paths. + A list of paths can contain both files and directories. + filesystem: The filesystem implementation to read from. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_stream `_. + numpy_load_args: Other options to pass to np.load. + meta_provider: File metadata provider. Custom metadata providers may + be able to resolve file metadata more quickly and/or accurately. If + ``None``, this function uses a system-chosen implementation. + partition_filter: Path-based partition filter, if any. Can be used + with a custom callback to read only selected partitions of a dataset. + By default, this filters out any file paths whose file extension does not + match "*.npy*". + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to ``None``. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file paths in ``paths`` that are not + found. Defaults to False. + shuffle: If setting to "files", randomly shuffle input files order before read. + if setting to ``FileShuffleConfig``, the random seed can be passed toshuffle the + input files, i.e. ``FileShuffleConfig(seed = 42)``. + Defaults to not shuffle with ``None``. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + Dataset holding Tensor records read from the specified paths. + """ # noqa: E501 + _emit_meta_provider_deprecation_warning(meta_provider) + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + + datasource = NumpyDatasource( + paths, + numpy_load_args=numpy_load_args, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_tfrecords( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + include_paths: bool = False, + ignore_missing_paths: bool = False, + tf_schema: Optional["schema_pb2.Schema"] = None, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + tfx_read_options: Optional["TFXReadOptions"] = None, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from TFRecord files that contain + `tf.train.Example `_ + messages. + + .. tip:: + Using the ``tfx-bsl`` library is more performant when reading large + datasets (for example, in production use cases). To use this + implementation, you must first install ``tfx-bsl``: + + 1. `pip install tfx_bsl --no-dependencies` + 2. Pass tfx_read_options to read_tfrecords, for example: + `ds = read_tfrecords(path, ..., tfx_read_options=TFXReadOptions())` + + .. warning:: + This function exclusively supports ``tf.train.Example`` messages. If a file + contains a message that isn't of type ``tf.train.Example``, then this function + fails. + + Examples: + >>> import ray + >>> ray.data.read_tfrecords("s3://anonymous@ray-example-data/iris.tfrecords") + Dataset(num_rows=?, schema=...) + + We can also read compressed TFRecord files, which use one of the + `compression types supported by Arrow `_: + + >>> ray.data.read_tfrecords( + ... "s3://anonymous@ray-example-data/iris.tfrecords.gz", + ... arrow_open_stream_args={"compression": "gzip"}, + ... ) + Dataset(num_rows=?, schema=...) + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `PyArrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + when opening input files to read. To read a compressed TFRecord file, + pass the corresponding compression type (e.g., for ``GZIP`` or ``ZLIB``), + use ``arrow_open_stream_args={'compression': 'gzip'}``). + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. + Use with a custom callback to read only selected partitions of a + dataset. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + ignore_missing_paths: If True, ignores any file paths in ``paths`` that are not + found. Defaults to False. + tf_schema: Optional TensorFlow Schema which is used to explicitly set the schema + of the underlying Dataset. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + tfx_read_options: Specifies read options when reading TFRecord files with TFX. + When no options are provided, the default version without tfx-bsl will + be used to read the tfrecords. + Returns: + A :class:`~ray.data.Dataset` that contains the example features. + + Raises: + ValueError: If a file contains a message that isn't a ``tf.train.Example``. + """ + import platform + + _emit_meta_provider_deprecation_warning(meta_provider) + + tfx_read = False + + if tfx_read_options and platform.processor() != "arm": + try: + import tfx_bsl # noqa: F401 + + tfx_read = True + except ModuleNotFoundError: + # override the tfx_read_options given that tfx-bsl is not installed + tfx_read_options = None + logger.warning( + "Please install tfx-bsl package with" + " `pip install tfx_bsl --no-dependencies`." + " This can help speed up the reading of large TFRecord files." + ) + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + datasource = TFRecordDatasource( + paths, + tf_schema=tf_schema, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + tfx_read_options=tfx_read_options, + ) + ds = read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + if ( + tfx_read_options + and tfx_read_options.auto_infer_schema + and tfx_read + and not tf_schema + ): + from ray.data._internal.datasource.tfrecords_datasource import ( + _infer_schema_and_transform, + ) + + return _infer_schema_and_transform(ds) + + return ds + + +@PublicAPI(stability="alpha") +def read_webdataset( + paths: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + decoder: Optional[Union[bool, str, callable, list]] = True, + fileselect: Optional[Union[list, callable]] = None, + filerename: Optional[Union[list, callable]] = None, + suffixes: Optional[Union[list, callable]] = None, + verbose_open: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + include_paths: bool = False, + file_extensions: Optional[List[str]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + expand_json: bool = False, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from + `WebDataset `_ files. + + Args: + paths: A single file/directory path or a list of file/directory paths. + A list of paths can contain both files and directories. + filesystem: The filesystem implementation to read from. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + arrow_open_stream_args: Key-word arguments passed to + `pyarrow.fs.FileSystem.open_input_stream `_. + To read a compressed TFRecord file, + pass the corresponding compression type (e.g. for ``GZIP`` or ``ZLIB``, use + ``arrow_open_stream_args={'compression': 'gzip'}``). + meta_provider: File metadata provider. Custom metadata providers may + be able to resolve file metadata more quickly and/or accurately. If + ``None``, this function uses a system-chosen implementation. + partition_filter: Path-based partition filter, if any. Can be used + with a custom callback to read only selected partitions of a dataset. + decoder: A function or list of functions to decode the data. + fileselect: A callable or list of glob patterns to select files. + filerename: A function or list of tuples to rename files prior to grouping. + suffixes: A function or list of suffixes to select for creating samples. + verbose_open: Whether to print the file names as they are opened. + shuffle: If setting to "files", randomly shuffle input files order before read. + if setting to ``FileShuffleConfig``, the random seed can be passed toshuffle the + input files, i.e. ``FileShuffleConfig(seed = 42)``. + Defaults to not shuffle with ``None``. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + expand_json: If ``True``, expand JSON objects into individual samples. + Defaults to ``False``. + + Returns: + A :class:`~ray.data.Dataset` that contains the example features. + + Raises: + ValueError: If a file contains a message that isn't a `tf.train.Example`_. + + .. _tf.train.Example: https://www.tensorflow.org/api_docs/python/tf/train/Example + """ # noqa: E501 + _emit_meta_provider_deprecation_warning(meta_provider) + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + + datasource = WebDatasetDatasource( + paths, + decoder=decoder, + fileselect=fileselect, + filerename=filerename, + suffixes=suffixes, + verbose_open=verbose_open, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + expand_json=expand_json, + ) + return read_datasource( + datasource, + parallelism=parallelism, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def read_binary_files( + paths: Union[str, List[str]], + *, + include_paths: bool = False, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + parallelism: int = -1, + ray_remote_args: Dict[str, Any] = None, + arrow_open_stream_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[BaseFileMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Partitioning = None, + ignore_missing_paths: bool = False, + shuffle: Optional[Union[Literal["files"], FileShuffleConfig]] = None, + file_extensions: Optional[List[str]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from binary files of arbitrary contents. + + Examples: + Read a file in remote storage. + + >>> import ray + >>> path = "s3://anonymous@ray-example-data/pdf-sample_0.pdf" + >>> ds = ray.data.read_binary_files(path) + >>> ds.schema() + Column Type + ------ ---- + bytes binary + + Read multiple local files. + + >>> ray.data.read_binary_files( # doctest: +SKIP + ... ["local:///path/to/file1", "local:///path/to/file2"]) + + Read a file with the filepaths included as a column in the dataset. + + >>> path = "s3://anonymous@ray-example-data/pdf-sample_0.pdf" + >>> ds = ray.data.read_binary_files(path, include_paths=True) + >>> ds.take(1)[0]["path"] + 'ray-example-data/pdf-sample_0.pdf' + + + Args: + paths: A single file or directory, or a list of file or directory paths. + A list of paths can contain both files and directories. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `PyArrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the `S3FileSystem` is used. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + arrow_open_stream_args: kwargs passed to + `pyarrow.fs.FileSystem.open_input_file `_. + meta_provider: [Deprecated] A :ref:`file metadata provider `. + Custom metadata providers may be able to resolve file metadata more quickly + and/or accurately. In most cases, you do not need to set this. If ``None``, + this function uses a system-chosen implementation. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. + Use with a custom callback to read only selected partitions of a + dataset. By default, no files are filtered. + By default, this does not filter out any files. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to ``None``. + ignore_missing_paths: If True, ignores any file paths in ``paths`` that are not + found. Defaults to False. + shuffle: If setting to "files", randomly shuffle input files order before read. + If setting to :class:`~ray.data.FileShuffleConfig`, you can pass a seed to + shuffle the input files. Defaults to not shuffle with ``None``. + file_extensions: A list of file extensions to filter files by. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` producing rows read from the specified paths. + """ + _emit_meta_provider_deprecation_warning(meta_provider) + + if meta_provider is None: + meta_provider = DefaultFileMetadataProvider() + + datasource = BinaryDatasource( + paths, + include_paths=include_paths, + filesystem=filesystem, + open_stream_args=arrow_open_stream_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + ignore_missing_paths=ignore_missing_paths, + shuffle=shuffle, + file_extensions=file_extensions, + ) + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_sql( + sql: str, + connection_factory: Callable[[], Connection], + *, + shard_keys: Optional[list[str]] = None, + shard_hash_fn: str = "MD5", + parallelism: int = -1, + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Read from a database that provides a + `Python DB API2-compliant `_ connector. + + .. note:: + + Parallelism is supported by databases that support sharding. This means + that the database needs to support all of the following operations: + ``MOD``, ``ABS``, and ``CONCAT``. + + You can use ``shard_hash_fn`` to specify the hash function to use for sharding. + The default is ``MD5``, but other common alternatives include ``hash``, + ``unicode``, and ``SHA``. + + If the database does not support sharding, the read operation will be + executed in a single task. + + Examples: + + For examples of reading from larger databases like MySQL and PostgreSQL, see + :ref:`Reading from SQL Databases `. + + .. testcode:: + + import sqlite3 + + import ray + + # Create a simple database + connection = sqlite3.connect("example.db") + connection.execute("CREATE TABLE movie(title, year, score)") + connection.execute( + \"\"\" + INSERT INTO movie VALUES + ('Monty Python and the Holy Grail', 1975, 8.2), + ("Monty Python Live at the Hollywood Bowl", 1982, 7.9), + ("Monty Python's Life of Brian", 1979, 8.0), + ("Rocky II", 1979, 7.3) + \"\"\" + ) + connection.commit() + connection.close() + + def create_connection(): + return sqlite3.connect("example.db") + + # Get all movies + ds = ray.data.read_sql("SELECT * FROM movie", create_connection) + # Get movies after the year 1980 + ds = ray.data.read_sql( + "SELECT title, score FROM movie WHERE year >= 1980", create_connection + ) + # Get the number of movies per year + ds = ray.data.read_sql( + "SELECT year, COUNT(*) FROM movie GROUP BY year", create_connection + ) + + .. testcode:: + :hide: + + import os + os.remove("example.db") + + Args: + sql: The SQL query to execute. + connection_factory: A function that takes no arguments and returns a + Python DB API2 + `Connection object `_. + shard_keys: The keys to shard the data by. + shard_hash_fn: The hash function string to use for sharding. Defaults to "MD5". + For other databases, common alternatives include "hash" and "SHA". + This is applied to the shard keys. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + This is used for sharding when shard_keys is provided. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`Dataset` containing the queried data. + """ + datasource = SQLDatasource( + sql=sql, + shard_keys=shard_keys, + shard_hash_fn=shard_hash_fn, + connection_factory=connection_factory, + ) + if override_num_blocks and override_num_blocks > 1: + if shard_keys is None: + raise ValueError("shard_keys must be provided when override_num_blocks > 1") + + if not datasource.supports_sharding(override_num_blocks): + raise ValueError( + "Database does not support sharding. Please set override_num_blocks to 1." + ) + + return read_datasource( + datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_databricks_tables( + *, + warehouse_id: str, + table: Optional[str] = None, + query: Optional[str] = None, + catalog: Optional[str] = None, + schema: Optional[str] = None, + parallelism: int = -1, + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Read a Databricks unity catalog table or Databricks SQL execution result. + + Before calling this API, set the ``DATABRICKS_TOKEN`` environment + variable to your Databricks warehouse access token. + + .. code-block:: console + + export DATABRICKS_TOKEN=... + + If you're not running your program on the Databricks runtime, also set the + ``DATABRICKS_HOST`` environment variable. + + .. code-block:: console + + export DATABRICKS_HOST=adb-..azuredatabricks.net + + .. note:: + + This function is built on the + `Databricks statement execution API `_. + + Examples: + + .. testcode:: + :skipif: True + + import ray + + ds = ray.data.read_databricks_tables( + warehouse_id='...', + catalog='catalog_1', + schema='db_1', + query='select id from table_1 limit 750000', + ) + + Args: + warehouse_id: The ID of the Databricks warehouse. The query statement is + executed on this warehouse. + table: The name of UC table you want to read. If this argument is set, + you can't set ``query`` argument, and the reader generates query + of ``select * from {table_name}`` under the hood. + query: The query you want to execute. If this argument is set, + you can't set ``table_name`` argument. + catalog: (Optional) The default catalog name used by the query. + schema: (Optional) The default schema used by the query. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`Dataset` containing the queried data. + """ # noqa: E501 + from ray.data._internal.datasource.databricks_uc_datasource import ( + DatabricksUCDatasource, + ) + + def get_dbutils(): + no_dbutils_error = RuntimeError("No dbutils module found.") + try: + import IPython + + ip_shell = IPython.get_ipython() + if ip_shell is None: + raise no_dbutils_error + return ip_shell.ns_table["user_global"]["dbutils"] + except ImportError: + raise no_dbutils_error + except KeyError: + raise no_dbutils_error + + token = os.environ.get("DATABRICKS_TOKEN") + + if not token: + raise ValueError( + "Please set environment variable 'DATABRICKS_TOKEN' to " + "databricks workspace access token." + ) + + host = os.environ.get("DATABRICKS_HOST") + if not host: + from ray.util.spark.utils import is_in_databricks_runtime + + if is_in_databricks_runtime(): + ctx = ( + get_dbutils().notebook.entry_point.getDbutils().notebook().getContext() + ) + host = ctx.tags().get("browserHostName").get() + else: + raise ValueError( + "You are not in databricks runtime, please set environment variable " + "'DATABRICKS_HOST' to databricks workspace URL" + '(e.g. "adb-..azuredatabricks.net").' + ) + + if not catalog: + from ray.util.spark.utils import get_spark_session + + catalog = get_spark_session().sql("SELECT CURRENT_CATALOG()").collect()[0][0] + + if not schema: + from ray.util.spark.utils import get_spark_session + + schema = get_spark_session().sql("SELECT CURRENT_DATABASE()").collect()[0][0] + + if query is not None and table is not None: + raise ValueError("Only one of 'query' and 'table' arguments can be set.") + + if table: + query = f"select * from {table}" + + if query is None: + raise ValueError("One of 'query' and 'table' arguments should be set.") + + datasource = DatabricksUCDatasource( + host=host, + token=token, + warehouse_id=warehouse_id, + catalog=catalog, + schema=schema, + query=query, + ) + return read_datasource( + datasource=datasource, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_hudi( + table_uri: str, + *, + storage_options: Optional[Dict[str, str]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """ + Create a :class:`~ray.data.Dataset` from an + `Apache Hudi table `_. + + Examples: + >>> import ray + >>> ds = ray.data.read_hudi( # doctest: +SKIP + ... table_uri="/hudi/trips", + ... ) + + Args: + table_uri: The URI of the Hudi table to read from. Local file paths, S3, and GCS + are supported. + storage_options: Extra options that make sense for a particular storage + connection. This is used to store connection parameters like credentials, + endpoint, etc. See more explanation + `here `_. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` producing records read from the Hudi table. + """ # noqa: E501 + datasource = HudiDatasource( + table_uri=table_uri, + storage_options=storage_options, + ) + + return read_datasource( + datasource=datasource, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def from_daft(df: "daft.DataFrame") -> Dataset: + """Create a :class:`~ray.data.Dataset` from a `Daft DataFrame `_. + + .. warning:: + + This function only works with PyArrow 13 or lower. For more details, see + https://github.com/ray-project/ray/issues/53278. + + Args: + df: A Daft DataFrame + + Returns: + A :class:`~ray.data.Dataset` holding rows read from the DataFrame. + """ + pyarrow_version = get_pyarrow_version() + assert pyarrow_version is not None + if pyarrow_version >= parse_version("14.0.0"): + raise RuntimeError( + "`from_daft` only works with PyArrow 13 or lower. For more details, see " + "https://github.com/ray-project/ray/issues/53278." + ) + + # NOTE: Today this returns a MaterializedDataset. We should also integrate Daft such + # that we can stream object references into a Ray dataset. Unfortunately this is + # very tricky today because of the way Ray Datasources are implemented with a fully- + # materialized `list` of ReadTasks, rather than an iterator which can lazily return + # these tasks. + return df.to_ray_dataset() + + +@PublicAPI +def from_dask(df: "dask.dataframe.DataFrame") -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a + `Dask DataFrame `_. + + Args: + df: A `Dask DataFrame`_. + + Returns: + A :class:`~ray.data.MaterializedDataset` holding rows read from the DataFrame. + """ # noqa: E501 + import dask + + from ray.util.dask import ray_dask_get + + partitions = df.to_delayed() + persisted_partitions = dask.persist(*partitions, scheduler=ray_dask_get) + + import pandas + + def to_ref(df): + if isinstance(df, pandas.DataFrame): + return ray.put(df) + elif isinstance(df, ray.ObjectRef): + return df + else: + raise ValueError( + "Expected a Ray object ref or a Pandas DataFrame, " f"got {type(df)}" + ) + + ds = from_pandas_refs( + [to_ref(next(iter(part.dask.values()))) for part in persisted_partitions], + ) + return ds + + +@PublicAPI +def from_mars(df: "mars.dataframe.DataFrame") -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a + `Mars DataFrame `_. + + Args: + df: A `Mars DataFrame`_, which must be executed by Mars-on-Ray. + + Returns: + A :class:`~ray.data.MaterializedDataset` holding rows read from the DataFrame. + """ # noqa: E501 + import mars.dataframe as md + + ds: Dataset = md.to_ray_dataset(df) + return ds + + +@PublicAPI +def from_modin(df: "modin.pandas.dataframe.DataFrame") -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a + `Modin DataFrame `_. + + Args: + df: A `Modin DataFrame`_, which must be using the Ray backend. + + Returns: + A :class:`~ray.data.MaterializedDataset` rows read from the DataFrame. + """ # noqa: E501 + from modin.distributed.dataframe.pandas.partitions import unwrap_partitions + + parts = unwrap_partitions(df, axis=0) + ds = from_pandas_refs(parts) + return ds + + +@PublicAPI +def from_pandas( + dfs: Union["pandas.DataFrame", List["pandas.DataFrame"]], + override_num_blocks: Optional[int] = None, +) -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a list of pandas dataframes. + + Examples: + >>> import pandas as pd + >>> import ray + >>> df = pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}) + >>> ray.data.from_pandas(df) + MaterializedDataset(num_blocks=1, num_rows=3, schema={a: int64, b: int64}) + + Create a Ray Dataset from a list of Pandas DataFrames. + + >>> ray.data.from_pandas([df, df]) + MaterializedDataset(num_blocks=2, num_rows=6, schema={a: int64, b: int64}) + + Args: + dfs: A pandas dataframe or a list of pandas dataframes. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` holding data read from the dataframes. + """ + import pandas as pd + + if isinstance(dfs, pd.DataFrame): + dfs = [dfs] + + if override_num_blocks is not None: + if len(dfs) > 1: + # I assume most users pass a single DataFrame as input. For simplicity, I'm + # concatenating DataFrames, even though it's not efficient. + ary = pd.concat(dfs, axis=0) + else: + ary = dfs[0] + dfs = np.array_split(ary, override_num_blocks) + + from ray.air.util.data_batch_conversion import ( + _cast_ndarray_columns_to_tensor_extension, + ) + + context = DataContext.get_current() + if context.enable_tensor_extension_casting: + dfs = [_cast_ndarray_columns_to_tensor_extension(df.copy()) for df in dfs] + + return from_pandas_refs([ray.put(df) for df in dfs]) + + +@DeveloperAPI +def from_pandas_refs( + dfs: Union[ObjectRef["pandas.DataFrame"], List[ObjectRef["pandas.DataFrame"]]], +) -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a list of Ray object references to + pandas dataframes. + + Examples: + >>> import pandas as pd + >>> import ray + >>> df_ref = ray.put(pd.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]})) + >>> ray.data.from_pandas_refs(df_ref) + MaterializedDataset(num_blocks=1, num_rows=3, schema={a: int64, b: int64}) + + Create a Ray Dataset from a list of Pandas Dataframes references. + + >>> ray.data.from_pandas_refs([df_ref, df_ref]) + MaterializedDataset(num_blocks=2, num_rows=6, schema={a: int64, b: int64}) + + Args: + dfs: A Ray object reference to a pandas dataframe, or a list of + Ray object references to pandas dataframes. + + Returns: + :class:`~ray.data.Dataset` holding data read from the dataframes. + """ + if isinstance(dfs, ray.ObjectRef): + dfs = [dfs] + elif isinstance(dfs, list): + for df in dfs: + if not isinstance(df, ray.ObjectRef): + raise ValueError( + "Expected list of Ray object refs, " + f"got list containing {type(df)}" + ) + else: + raise ValueError( + "Expected Ray object ref or list of Ray object refs, " f"got {type(df)}" + ) + + context = DataContext.get_current() + if context.enable_pandas_block: + get_metadata_schema = cached_remote_fn(get_table_block_metadata_schema) + metadata_schema = ray.get([get_metadata_schema.remote(df) for df in dfs]) + execution_plan = ExecutionPlan( + DatasetStats(metadata={"FromPandas": metadata_schema}, parent=None), + DataContext.get_current().copy(), + ) + logical_plan = LogicalPlan( + FromPandas(dfs, metadata_schema), execution_plan._context + ) + return MaterializedDataset( + execution_plan, + logical_plan, + ) + + df_to_block = cached_remote_fn(pandas_df_to_arrow_block, num_returns=2) + + res = [df_to_block.remote(df) for df in dfs] + blocks, metadata_schema = map(list, zip(*res)) + metadata_schema = ray.get(metadata_schema) + execution_plan = ExecutionPlan( + DatasetStats(metadata={"FromPandas": metadata_schema}, parent=None), + DataContext.get_current().copy(), + ) + logical_plan = LogicalPlan( + FromPandas(blocks, metadata_schema), execution_plan._context + ) + return MaterializedDataset( + execution_plan, + logical_plan, + ) + + +@PublicAPI +def from_numpy(ndarrays: Union[np.ndarray, List[np.ndarray]]) -> MaterializedDataset: + """Creates a :class:`~ray.data.Dataset` from a list of NumPy ndarrays. + + The column name defaults to "data". + + Examples: + >>> import numpy as np + >>> import ray + >>> arr = np.array([1]) + >>> ray.data.from_numpy(arr) + MaterializedDataset(num_blocks=1, num_rows=1, schema={data: int64}) + + Create a Ray Dataset from a list of NumPy arrays. + + >>> ray.data.from_numpy([arr, arr]) + MaterializedDataset(num_blocks=2, num_rows=2, schema={data: int64}) + + Args: + ndarrays: A NumPy ndarray or a list of NumPy ndarrays. + + Returns: + :class:`~ray.data.Dataset` holding data from the given ndarrays. + """ + if isinstance(ndarrays, np.ndarray): + ndarrays = [ndarrays] + + return from_numpy_refs([ray.put(ndarray) for ndarray in ndarrays]) + + +@DeveloperAPI +def from_numpy_refs( + ndarrays: Union[ObjectRef[np.ndarray], List[ObjectRef[np.ndarray]]], +) -> MaterializedDataset: + """Creates a :class:`~ray.data.Dataset` from a list of Ray object references to + NumPy ndarrays. + + The column name defaults to "data". + + Examples: + >>> import numpy as np + >>> import ray + >>> arr_ref = ray.put(np.array([1])) + >>> ray.data.from_numpy_refs(arr_ref) + MaterializedDataset(num_blocks=1, num_rows=1, schema={data: int64}) + + Create a Ray Dataset from a list of NumPy array references. + + >>> ray.data.from_numpy_refs([arr_ref, arr_ref]) + MaterializedDataset(num_blocks=2, num_rows=2, schema={data: int64}) + + Args: + ndarrays: A Ray object reference to a NumPy ndarray or a list of Ray object + references to NumPy ndarrays. + + Returns: + :class:`~ray.data.Dataset` holding data from the given ndarrays. + """ + if isinstance(ndarrays, ray.ObjectRef): + ndarrays = [ndarrays] + elif isinstance(ndarrays, list): + for ndarray in ndarrays: + if not isinstance(ndarray, ray.ObjectRef): + raise ValueError( + "Expected list of Ray object refs, " + f"got list containing {type(ndarray)}" + ) + else: + raise ValueError( + f"Expected Ray object ref or list of Ray object refs, got {type(ndarray)}" + ) + + ctx = DataContext.get_current() + ndarray_to_block_remote = cached_remote_fn(ndarray_to_block, num_returns=2) + + res = [ndarray_to_block_remote.remote(ndarray, ctx) for ndarray in ndarrays] + blocks, metadata_schema = map(list, zip(*res)) + metadata_schema = ray.get(metadata_schema) + + execution_plan = ExecutionPlan( + DatasetStats(metadata={"FromNumpy": metadata_schema}, parent=None), + DataContext.get_current().copy(), + ) + + logical_plan = LogicalPlan( + FromNumpy(blocks, metadata_schema), execution_plan._context + ) + + return MaterializedDataset( + execution_plan, + logical_plan, + ) + + +@PublicAPI +def from_arrow( + tables: Union["pyarrow.Table", bytes, List[Union["pyarrow.Table", bytes]]], + *, + override_num_blocks: Optional[int] = None, +) -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a list of PyArrow tables. + + Examples: + >>> import pyarrow as pa + >>> import ray + >>> table = pa.table({"x": [1]}) + >>> ray.data.from_arrow(table) + MaterializedDataset(num_blocks=1, num_rows=1, schema={x: int64}) + + Create a Ray Dataset from a list of PyArrow tables. + + >>> ray.data.from_arrow([table, table]) + MaterializedDataset(num_blocks=2, num_rows=2, schema={x: int64}) + + + Args: + tables: A PyArrow table, or a list of PyArrow tables, + or its streaming format in bytes. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + :class:`~ray.data.Dataset` holding data from the PyArrow tables. + """ + import builtins + + import pyarrow as pa + + if isinstance(tables, (pa.Table, bytes)): + tables = [tables] + + if override_num_blocks is not None: + if override_num_blocks <= 0: + raise ValueError("override_num_blocks must be > 0") + combined_table = pa.concat_tables(tables) if len(tables) > 1 else tables[0] + total_rows = len(combined_table) + + if total_rows == 0: + # Handle empty table case + tables = [ + combined_table.slice(0, 0) for _ in builtins.range(override_num_blocks) + ] + else: + batch_size = (total_rows + override_num_blocks - 1) // override_num_blocks + slices = [] + + for i in builtins.range(override_num_blocks): + start = i * batch_size + if start >= total_rows: + break + length = min(batch_size, total_rows - start) + slices.append(combined_table.slice(start, length)) + + # Pad with empty slices if needed + if len(slices) < override_num_blocks: + empty_table = combined_table.slice(0, 0) + slices.extend([empty_table] * (override_num_blocks - len(slices))) + + tables = slices + + return from_arrow_refs([ray.put(t) for t in tables]) + + +@DeveloperAPI +def from_arrow_refs( + tables: Union[ + ObjectRef[Union["pyarrow.Table", bytes]], + List[ObjectRef[Union["pyarrow.Table", bytes]]], + ], +) -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a list of Ray object references to + PyArrow tables. + + Examples: + >>> import pyarrow as pa + >>> import ray + >>> table_ref = ray.put(pa.table({"x": [1]})) + >>> ray.data.from_arrow_refs(table_ref) + MaterializedDataset(num_blocks=1, num_rows=1, schema={x: int64}) + + Create a Ray Dataset from a list of PyArrow table references + + >>> ray.data.from_arrow_refs([table_ref, table_ref]) + MaterializedDataset(num_blocks=2, num_rows=2, schema={x: int64}) + + + Args: + tables: A Ray object reference to Arrow table, or list of Ray object + references to Arrow tables, or its streaming format in bytes. + + Returns: + :class:`~ray.data.Dataset` holding data read from the tables. + """ + if isinstance(tables, ray.ObjectRef): + tables = [tables] + + get_metadata_schema = cached_remote_fn(get_table_block_metadata_schema) + metadata_schema = ray.get([get_metadata_schema.remote(t) for t in tables]) + execution_plan = ExecutionPlan( + DatasetStats(metadata={"FromArrow": metadata_schema}, parent=None), + DataContext.get_current().copy(), + ) + logical_plan = LogicalPlan( + FromArrow(tables, metadata_schema), execution_plan._context + ) + + return MaterializedDataset( + execution_plan, + logical_plan, + ) + + +@PublicAPI(stability="alpha") +def read_delta_sharing_tables( + url: str, + *, + limit: Optional[int] = None, + version: Optional[int] = None, + timestamp: Optional[str] = None, + json_predicate_hints: Optional[str] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """ + Read data from a Delta Sharing table. + Delta Sharing projct https://github.com/delta-io/delta-sharing/tree/main + + This function reads data from a Delta Sharing table specified by the URL. + It supports various options such as limiting the number of rows, specifying + a version or timestamp, and configuring concurrency. + + Before calling this function, ensure that the URL is correctly formatted + to point to the Delta Sharing table you want to access. Make sure you have + a valid delta_share profile in the working directory. + + Examples: + + .. testcode:: + :skipif: True + + import ray + + ds = ray.data.read_delta_sharing_tables( + url=f"your-profile.json#your-share-name.your-schema-name.your-table-name", + limit=100000, + version=1, + ) + + Args: + url: A URL under the format + "#..". + Example can be found at + https://github.com/delta-io/delta-sharing/blob/main/README.md#quick-start + limit: A non-negative integer. Load only the ``limit`` rows if the + parameter is specified. Use this optional parameter to explore the + shared table without loading the entire table into memory. + version: A non-negative integer. Load the snapshot of the table at + the specified version. + timestamp: A timestamp to specify the version of the table to read. + json_predicate_hints: Predicate hints to be applied to the table. For more + details, see: + https://github.com/delta-io/delta-sharing/blob/main/PROTOCOL.md#json-predicates-for-filtering. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control the number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`Dataset` containing the queried data. + + Raises: + ValueError: If the URL is not properly formatted or if there is an issue + with the Delta Sharing table connection. + """ + + datasource = DeltaSharingDatasource( + url=url, + json_predicate_hints=json_predicate_hints, + limit=limit, + version=version, + timestamp=timestamp, + ) + # DeltaSharing limit is at the add_files level, it will not return + # exactly the limit number of rows but it will return less files and rows. + return ray.data.read_datasource( + datasource=datasource, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI +def from_spark( + df: "pyspark.sql.DataFrame", + *, + parallelism: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a + `Spark DataFrame `_. + + Args: + df: A `Spark DataFrame`_, which must be created by RayDP (Spark-on-Ray). + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.MaterializedDataset` holding rows read from the DataFrame. + """ # noqa: E501 + import raydp + + parallelism = _get_num_output_blocks(parallelism, override_num_blocks) + return raydp.spark.spark_dataframe_to_ray_dataset(df, parallelism) + + +@PublicAPI +def from_huggingface( + dataset: Union["datasets.Dataset", "datasets.IterableDataset"], + parallelism: int = -1, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Union[MaterializedDataset, Dataset]: + """Create a :class:`~ray.data.MaterializedDataset` from a + `Hugging Face Datasets Dataset `_ + or a :class:`~ray.data.Dataset` from a `Hugging Face Datasets IterableDataset `_. + For an `IterableDataset`, we use a streaming implementation to read data. + + If the dataset is a public Hugging Face Dataset that is hosted on the Hugging Face Hub and + no transformations have been applied, then the `hosted parquet files `_ + will be passed to :meth:`~ray.data.read_parquet` to perform a distributed read. All + other cases will be done with a single node read. + + Example: + + .. + The following `testoutput` is mocked to avoid illustrating download + logs like "Downloading and preparing dataset 162.17 MiB". + + .. testcode:: + + import ray + import datasets + + hf_dataset = datasets.load_dataset("tweet_eval", "emotion") + ray_ds = ray.data.from_huggingface(hf_dataset["train"]) + print(ray_ds) + + hf_dataset_stream = datasets.load_dataset("tweet_eval", "emotion", streaming=True) + ray_ds_stream = ray.data.from_huggingface(hf_dataset_stream["train"]) + print(ray_ds_stream) + + .. testoutput:: + :options: +MOCK + + MaterializedDataset( + num_blocks=..., + num_rows=3257, + schema={text: string, label: int64} + ) + Dataset( + num_rows=3257, + schema={text: string, label: int64} + ) + + Args: + dataset: A `Hugging Face Datasets Dataset`_ or `Hugging Face Datasets IterableDataset`_. + `DatasetDict `_ + and `IterableDatasetDict `_ + are not supported. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` holding rows from the `Hugging Face Datasets Dataset`_. + """ # noqa: E501 + import datasets + from aiohttp.client_exceptions import ClientResponseError + + from ray.data._internal.datasource.huggingface_datasource import ( + HuggingFaceDatasource, + ) + + if isinstance(dataset, (datasets.IterableDataset, datasets.Dataset)): + try: + # Attempt to read data via Hugging Face Hub parquet files. If the + # returned list of files is empty, attempt read via other methods. + file_urls = HuggingFaceDatasource.list_parquet_urls_from_dataset(dataset) + + if len(file_urls) > 0: + # Resolve HTTP 302 redirects + import requests + + resolved_urls = [] + for url in file_urls: + try: + resp = requests.head(url, allow_redirects=True, timeout=5) + if resp.status_code == 200: + resolved_urls.append(resp.url) + else: + logger.warning( + f"Unexpected status {resp.status_code} resolving {url} from " + f"Hugging Face Hub parquet files" + ) + except requests.RequestException as e: + logger.warning( + f"Failed to resolve {url}: {e} from Hugging Face Hub parquet files" + ) + + if not resolved_urls: + raise FileNotFoundError( + "No resolvable Parquet URLs found from Hugging Face Hub parquet files" + ) + + # If file urls are returned, the parquet files are available via API + # TODO: Add support for reading from http filesystem in + # FileBasedDatasource. GH Issue: + # https://github.com/ray-project/ray/issues/42706 + import fsspec.implementations.http + + http = fsspec.implementations.http.HTTPFileSystem() + return read_parquet( + resolved_urls, + parallelism=parallelism, + filesystem=http, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ray_remote_args={ + "retry_exceptions": [FileNotFoundError, ClientResponseError] + }, + ) + + except (FileNotFoundError, ClientResponseError): + logger.warning( + "Distributed read via Hugging Face Hub parquet files failed, " + "falling back on single node read." + ) + + if isinstance(dataset, datasets.IterableDataset): + # For an IterableDataset, we can use a streaming implementation to read data. + return read_datasource( + HuggingFaceDatasource(dataset=dataset), + parallelism=parallelism, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + if isinstance(dataset, datasets.Dataset): + # To get the resulting Arrow table from a Hugging Face Dataset after + # applying transformations (e.g., train_test_split(), shard(), select()), + # we create a copy of the Arrow table, which applies the indices + # mapping from the transformations. + hf_ds_arrow = dataset.with_format("arrow") + ray_ds = from_arrow(hf_ds_arrow[:], override_num_blocks=override_num_blocks) + return ray_ds + elif isinstance(dataset, (datasets.DatasetDict, datasets.IterableDatasetDict)): + available_keys = list(dataset.keys()) + raise DeprecationWarning( + "You provided a Hugging Face DatasetDict or IterableDatasetDict, " + "which contains multiple datasets, but `from_huggingface` now " + "only accepts a single Hugging Face Dataset. To convert just " + "a single Hugging Face Dataset to a Ray Dataset, specify a split. " + "For example, `ray.data.from_huggingface(my_dataset_dictionary" + f"['{available_keys[0]}'])`. " + f"Available splits are {available_keys}." + ) + else: + raise TypeError( + f"`dataset` must be a `datasets.Dataset`, but got {type(dataset)}" + ) + + +@PublicAPI +def from_tf( + dataset: "tf.data.Dataset", +) -> MaterializedDataset: + """Create a :class:`~ray.data.Dataset` from a + `TensorFlow Dataset `_. + + This function is inefficient. Use it to read small datasets or prototype. + + .. warning:: + If your dataset is large, this function may execute slowly or raise an + out-of-memory error. To avoid issues, read the underyling data with a function + like :meth:`~ray.data.read_images`. + + .. note:: + This function isn't parallelized. It loads the entire dataset into the local + node's memory before moving the data to the distributed object store. + + Examples: + >>> import ray + >>> import tensorflow_datasets as tfds + >>> dataset, _ = tfds.load('cifar10', split=["train", "test"]) # doctest: +SKIP + >>> ds = ray.data.from_tf(dataset) # doctest: +SKIP + >>> ds # doctest: +SKIP + MaterializedDataset( + num_blocks=..., + num_rows=50000, + schema={ + id: binary, + image: numpy.ndarray(shape=(32, 32, 3), dtype=uint8), + label: int64 + } + ) + >>> ds.take(1) # doctest: +SKIP + [{'id': b'train_16399', 'image': array([[[143, 96, 70], + [141, 96, 72], + [135, 93, 72], + ..., + [ 96, 37, 19], + [105, 42, 18], + [104, 38, 20]], + ..., + [[195, 161, 126], + [187, 153, 123], + [186, 151, 128], + ..., + [212, 177, 147], + [219, 185, 155], + [221, 187, 157]]], dtype=uint8), 'label': 7}] + + Args: + dataset: A `TensorFlow Dataset`_. + + Returns: + A :class:`MaterializedDataset` that contains the samples stored in the `TensorFlow Dataset`_. + """ # noqa: E501 + # FIXME: `as_numpy_iterator` errors if `dataset` contains ragged tensors. + return from_items(list(dataset.as_numpy_iterator())) + + +@PublicAPI +def from_torch( + dataset: "torch.utils.data.Dataset", + local_read: bool = False, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from a + `Torch Dataset `_. + + The column name defaults to "data". + + .. note:: + The input dataset can either be map-style or iterable-style, and can have arbitrarily large amount of data. + The data will be sequentially streamed with one single read task. + + Examples: + >>> import ray + >>> from torchvision import datasets + >>> dataset = datasets.MNIST("data", download=True) # doctest: +SKIP + >>> ds = ray.data.from_torch(dataset) # doctest: +SKIP + >>> ds # doctest: +SKIP + MaterializedDataset(num_blocks=..., num_rows=60000, schema={item: object}) + >>> ds.take(1) # doctest: +SKIP + {"item": (, 5)} + + Args: + dataset: A `Torch Dataset`_. + local_read: If ``True``, perform the read as a local read. + + Returns: + A :class:`~ray.data.Dataset` containing the Torch dataset samples. + """ # noqa: E501 + + # Files may not be accessible from all nodes, run the read task on current node. + ray_remote_args = {} + if local_read: + ray_remote_args = { + "scheduling_strategy": NodeAffinitySchedulingStrategy( + ray.get_runtime_context().get_node_id(), + soft=False, + ), + # The user might have initialized Ray to have num_cpus = 0 for the head + # node. For a local read we expect the read task to be executed on the + # head node, so we should set num_cpus = 0 for the task to allow it to + # run regardless of the user's head node configuration. + "num_cpus": 0, + } + return read_datasource( + TorchDatasource(dataset=dataset), + ray_remote_args=ray_remote_args, + # Only non-parallel, streaming read is currently supported + override_num_blocks=1, + ) + + +@PublicAPI +def read_iceberg( + *, + table_identifier: str, + row_filter: Union[str, "BooleanExpression"] = None, + parallelism: int = -1, + selected_fields: Tuple[str, ...] = ("*",), + snapshot_id: Optional[int] = None, + scan_kwargs: Optional[Dict[str, str]] = None, + catalog_kwargs: Optional[Dict[str, str]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """Create a :class:`~ray.data.Dataset` from an Iceberg table. + + The table to read from is specified using a fully qualified ``table_identifier``. + Using PyIceberg, any intended row filters, selection of specific fields and + picking of a particular snapshot ID are applied, and the files that satisfy + the query are distributed across Ray read tasks. + The number of output blocks is determined by ``override_num_blocks`` + which can be requested from this interface or automatically chosen if + unspecified. + + .. tip:: + + For more details on PyIceberg, see + - URI: https://py.iceberg.apache.org/ + + Examples: + >>> import ray + >>> from pyiceberg.expressions import EqualTo #doctest: +SKIP + >>> ds = ray.data.read_iceberg( #doctest: +SKIP + ... table_identifier="db_name.table_name", + ... row_filter=EqualTo("column_name", "literal_value"), + ... catalog_kwargs={"name": "default", "type": "glue"} + ... ) + + Args: + table_identifier: Fully qualified table identifier (``db_name.table_name``) + row_filter: A PyIceberg :class:`~pyiceberg.expressions.BooleanExpression` + to use to filter the data *prior* to reading + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + selected_fields: Which columns from the data to read, passed directly to + PyIceberg's load functions. Should be an tuple of string column names. + snapshot_id: Optional snapshot ID for the Iceberg table, by default the latest + snapshot is used + scan_kwargs: Optional arguments to pass to PyIceberg's Table.scan() function + (e.g., case_sensitive, limit, etc.) + catalog_kwargs: Optional arguments to pass to PyIceberg's catalog.load_catalog() + function (e.g., name, type, etc.). For the function definition, see + `pyiceberg catalog + `_. + ray_remote_args: Optional arguments to pass to :func:`ray.remote` in the + read tasks. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources, and capped at the number of + physical files to be read. You shouldn't manually set this value in most + cases. + + Returns: + :class:`~ray.data.Dataset` with rows from the Iceberg table. + """ + + # Setup the Datasource + datasource = IcebergDatasource( + table_identifier=table_identifier, + row_filter=row_filter, + selected_fields=selected_fields, + snapshot_id=snapshot_id, + scan_kwargs=scan_kwargs, + catalog_kwargs=catalog_kwargs, + ) + + dataset = read_datasource( + datasource=datasource, + parallelism=parallelism, + override_num_blocks=override_num_blocks, + ray_remote_args=ray_remote_args, + ) + + return dataset + + +@PublicAPI +def read_lance( + uri: str, + *, + columns: Optional[List[str]] = None, + filter: Optional[str] = None, + storage_options: Optional[Dict[str, str]] = None, + scanner_options: Optional[Dict[str, Any]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """ + Create a :class:`~ray.data.Dataset` from a + `Lance Dataset `_. + + Examples: + >>> import ray + >>> ds = ray.data.read_lance( # doctest: +SKIP + ... uri="./db_name.lance", + ... columns=["image", "label"], + ... filter="label = 2 AND text IS NOT NULL", + ... ) + + Args: + uri: The URI of the Lance dataset to read from. Local file paths, S3, and GCS + are supported. + columns: The columns to read. By default, all columns are read. + filter: Read returns only the rows matching the filter. By default, no + filter is applied. + storage_options: Extra options that make sense for a particular storage + connection. This is used to store connection parameters like credentials, + endpoint, etc. For more information, see `Object Store Configuration `_. + scanner_options: Additional options to configure the `LanceDataset.scanner()` + method, such as `batch_size`. For more information, + see `LanceDB API doc `_ + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` producing records read from the Lance dataset. + """ # noqa: E501 + datasource = LanceDatasource( + uri=uri, + columns=columns, + filter=filter, + storage_options=storage_options, + scanner_options=scanner_options, + ) + + return read_datasource( + datasource=datasource, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_clickhouse( + *, + table: str, + dsn: str, + columns: Optional[List[str]] = None, + filter: Optional[str] = None, + order_by: Optional[Tuple[List[str], bool]] = None, + client_settings: Optional[Dict[str, Any]] = None, + client_kwargs: Optional[Dict[str, Any]] = None, + ray_remote_args: Optional[Dict[str, Any]] = None, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, +) -> Dataset: + """ + Create a :class:`~ray.data.Dataset` from a ClickHouse table or view. + + Examples: + >>> import ray + >>> ds = ray.data.read_clickhouse( # doctest: +SKIP + ... table="default.table", + ... dsn="clickhouse+http://username:password@host:8124/default", + ... columns=["timestamp", "age", "status", "text", "label"], + ... filter="age > 18 AND status = 'active'", + ... order_by=(["timestamp"], False), + ... ) + + Args: + table: Fully qualified table or view identifier (e.g., + "default.table_name"). + dsn: A string in standard DSN (Data Source Name) HTTP format (e.g., + "clickhouse+http://username:password@host:8124/default"). + For more information, see `ClickHouse Connection String doc + `_. + columns: Optional list of columns to select from the data source. + If no columns are specified, all columns will be selected by default. + filter: Optional SQL filter string that will be used in the WHERE statement + (e.g., "label = 2 AND text IS NOT NULL"). The filter string must be valid for use in + a ClickHouse SQL WHERE clause. Please Note: Parallel reads are not currently supported + when a filter is set. Specifying a filter forces the parallelism to 1 to ensure + deterministic and consistent results. For more information, see `ClickHouse SQL WHERE Clause doc + `_. + order_by: Optional tuple containing a list of columns to order by and a boolean indicating whether the order + should be descending (True for DESC, False for ASC). Please Note: order_by is required to support + parallelism. If not provided, the data will be read in a single task. This is to ensure + that the data is read in a consistent order across all tasks. + client_settings: Optional ClickHouse server settings to be used with the session/every request. + For more information, see `ClickHouse Client Settings + `_. + client_kwargs: Optional additional arguments to pass to the ClickHouse client. For more information, + see `ClickHouse Core Settings `_. + ray_remote_args: kwargs passed to :func:`ray.remote` in the read tasks. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + + Returns: + A :class:`~ray.data.Dataset` producing records read from the ClickHouse table or view. + """ # noqa: E501 + datasource = ClickHouseDatasource( + table=table, + dsn=dsn, + columns=columns, + filter=filter, + order_by=order_by, + client_settings=client_settings, + client_kwargs=client_kwargs, + ) + + return read_datasource( + datasource=datasource, + ray_remote_args=ray_remote_args, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + ) + + +@PublicAPI(stability="alpha") +def read_unity_catalog( + table: str, + url: str, + token: str, + *, + data_format: Optional[str] = None, + region: Optional[str] = None, + reader_kwargs: Optional[dict], +) -> Dataset: + """ + Loads a Unity Catalog table or files into a Ray Dataset using Databricks Unity Catalog credential vending, + with automatic short-lived cloud credential handoff for secure, parallel, distributed access from external engines. + + This function works by leveraging Unity Catalog's credential vending feature, which grants temporary, least-privilege + credentials for the cloud storage location backing the requested table or data files. It authenticates via the Unity Catalog + REST API (`Unity Catalog credential vending for external system access`, [Databricks Docs](https://docs.databricks.com/en/data-governance/unity-catalog/credential-vending.html)), + ensuring that permissions are enforced at the Databricks principal (user, group, or service principal) making the request. + The function supports reading data directly from AWS S3, Azure Data Lake, or GCP GCS in standard formats including Delta and Parquet. + + .. note:: + + This ``read_unity_catalog`` function is currently experimental and under active development + + .. warning:: + + The Databricks Unity Catalog credential vending feature is currently in Public Preview and there are important requirements and limitations. + You must read these docs carefully and ensure your workspace and principal are properly configured. + + Features: + - **Secure Access**: Only principals with `EXTERNAL USE SCHEMA` on the containing schema, and after explicit metastore enablement, can obtain short-lived credentials. + - **Format Support**: Supports reading `delta` and `parquet` formats via supported Ray Dataset readers (iceberg coming soon). + - **Cloud Support**: AWS, Azure, and GCP supported, with automatic environment setup for the vended credentials per session. + - **Auto-Infer**: Data format is auto-inferred from table metadata, but can be explicitly specified. + + Examples: + Read a Unity Catalog managed Delta table with credential vending: + + >>> import ray + >>> ds = read_unity_catalog( # doctest: +SKIP + ... table="main.sales.transactions", + ... url="https://dbc-XXXXXXX-XXXX.cloud.databricks.com", # noqa: E501 + ... token="XXXXXXXXXXX" # noqa: E501 + ... ) + >>> ds.show(3) # doctest: +SKIP + + Explicitly specify the format, and pass reader options: + + >>> ds = read_unity_catalog( # doctest: +SKIP + ... table="main.catalog.images", + ... url="https://dbc-XXXXXXX-XXXX.cloud.databricks.com", # noqa: E501 + ... token="XXXXXXXXXXX", # noqa: E501 + ... data_format="delta", + ... region="us-west-2", + ... # Reader kwargs come from the associated reader (ray.data.read_delta in this example) + ... reader_kwargs={"override_num_blocks": 1000} + ... ) + + Args: + table: Unity Catalog table name as `..`. Must be a managed or external table supporting credential vending. + url: Databricks workspace URL, e.g. `"https://dbc-XXXXXXX-XXXX.cloud.databricks.com"` + token: Databricks PAT (Personal Access Token) with `EXTERNAL USE SCHEMA` on the schema containing the table, and with access to the workspace API. + data_format: (Optional) Data format override. If not specified, inferred from Unity Catalog metadata and file extension. Supported: `"delta"`, `"parquet"` + region: (Optional) For S3: AWS region for cloud credential environment setup. + reader_kwargs: Additional arguments forwarded to the underlying Ray Dataset reader (e.g., override_num_blocks, etc.). + + Returns: + A :class:`ray.data.Dataset` containing the data from the external Unity Catalog table. + + References: + - Databricks Credential Vending: https://docs.databricks.com/en/data-governance/unity-catalog/credential-vending.html + - API Reference for temporary credentials: https://docs.databricks.com/api/workspace/unity-catalog/temporary-table-credentials + + """ + reader = UnityCatalogConnector( + base_url=url, + token=token, + table_full_name=table, + data_format=data_format, + region=region, + reader_kwargs=reader_kwargs, + ) + return reader.read() + + +@PublicAPI(stability="alpha") +def read_delta( + path: Union[str, List[str]], + *, + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + columns: Optional[List[str]] = None, + parallelism: int = -1, + ray_remote_args: Optional[Dict[str, Any]] = None, + meta_provider: Optional[ParquetMetadataProvider] = None, + partition_filter: Optional[PathPartitionFilter] = None, + partitioning: Optional[Partitioning] = Partitioning("hive"), + shuffle: Union[Literal["files"], None] = None, + include_paths: bool = False, + concurrency: Optional[int] = None, + override_num_blocks: Optional[int] = None, + **arrow_parquet_args, +): + """Creates a :class:`~ray.data.Dataset` from Delta Lake files. + + Examples: + + >>> import ray + >>> ds = ray.data.read_delta("s3://bucket@path/to/delta-table/") # doctest: +SKIP + + Args: + path: A single file path for a Delta Lake table. Multiple tables are not yet + supported. + filesystem: The PyArrow filesystem + implementation to read from. These filesystems are specified in the + `pyarrow docs `_. Specify this parameter if + you need to provide specific configurations to the filesystem. By default, + the filesystem is automatically selected based on the scheme of the paths. + For example, if the path begins with ``s3://``, the ``S3FileSystem`` is + used. If ``None``, this function uses a system-chosen implementation. + columns: A list of column names to read. Only the specified columns are + read during the file scan. + parallelism: This argument is deprecated. Use ``override_num_blocks`` argument. + ray_remote_args: kwargs passed to :meth:`~ray.remote` in the read tasks. + meta_provider: A :ref:`file metadata provider `. Custom + metadata providers may be able to resolve file metadata more quickly and/or + accurately. In most cases you do not need to set this parameter. + partition_filter: A + :class:`~ray.data.datasource.partitioning.PathPartitionFilter`. Use + with a custom callback to read only selected partitions of a dataset. + partitioning: A :class:`~ray.data.datasource.partitioning.Partitioning` object + that describes how paths are organized. Defaults to HIVE partitioning. + shuffle: If setting to "files", randomly shuffle input files order before read. + Defaults to not shuffle with ``None``. + include_paths: If ``True``, include the path to each file. File paths are + stored in the ``'path'`` column. + concurrency: The maximum number of Ray tasks to run concurrently. Set this + to control number of tasks to run concurrently. This doesn't change the + total number of tasks run or the total number of output blocks. By default, + concurrency is dynamically decided based on the available resources. + override_num_blocks: Override the number of output blocks from all read tasks. + By default, the number of output blocks is dynamically decided based on + input data size and available resources. You shouldn't manually set this + value in most cases. + **arrow_parquet_args: Other parquet read options to pass to PyArrow. For the full + set of arguments, see the `PyArrow API `_ + + Returns: + :class:`~ray.data.Dataset` producing records read from the specified parquet + files. + + """ + # Modified from ray.data._internal.util._check_import, which is meant for objects, + # not functions. Move to _check_import if moved to a DataSource object. + import importlib + + package = "deltalake" + try: + importlib.import_module(package) + except ImportError: + raise ImportError( + f"`ray.data.read_delta` depends on '{package}', but '{package}' " + f"couldn't be imported. You can install '{package}' by running `pip " + f"install {package}`." + ) + + from deltalake import DeltaTable + + # This seems reasonable to keep it at one table, even Spark doesn't really support + # multi-table reads, it's usually up to the developer to keep it in one table. + if not isinstance(path, str): + raise ValueError("Only a single Delta Lake table path is supported.") + + # Get the parquet file paths from the DeltaTable + paths = DeltaTable(path).file_uris() + file_extensions = ["parquet"] + + return read_parquet( + paths, + filesystem=filesystem, + columns=columns, + parallelism=parallelism, + ray_remote_args=ray_remote_args, + meta_provider=meta_provider, + partition_filter=partition_filter, + partitioning=partitioning, + shuffle=shuffle, + include_paths=include_paths, + file_extensions=file_extensions, + concurrency=concurrency, + override_num_blocks=override_num_blocks, + **arrow_parquet_args, + ) + + +def _get_datasource_or_legacy_reader( + ds: Datasource, + ctx: DataContext, + kwargs: dict, +) -> Union[Datasource, Reader]: + """Generates reader. + + Args: + ds: Datasource to read from. + ctx: Dataset config to use. + kwargs: Additional kwargs to pass to the legacy reader if + `Datasource.create_reader` is implemented. + + Returns: + The datasource or a generated legacy reader. + """ + DataContext._set_current(ctx) + + if ds.should_create_reader: + warnings.warn( + "`create_reader` has been deprecated in Ray 2.9. Instead of creating a " + "`Reader`, implement `Datasource.get_read_tasks` and " + "`Datasource.estimate_inmemory_data_size`.", + DeprecationWarning, + ) + datasource_or_legacy_reader = ds.create_reader(**kwargs) + else: + datasource_or_legacy_reader = ds + + return datasource_or_legacy_reader + + +def _resolve_parquet_args( + tensor_column_schema: Optional[Dict[str, Tuple[np.dtype, Tuple[int, ...]]]] = None, + **arrow_parquet_args, +) -> Dict[str, Any]: + if tensor_column_schema is not None: + existing_block_udf = arrow_parquet_args.pop("_block_udf", None) + + def _block_udf(block: "pyarrow.Table") -> "pyarrow.Table": + from ray.data.extensions import ArrowTensorArray + + for tensor_col_name, (dtype, shape) in tensor_column_schema.items(): + # NOTE(Clark): We use NumPy to consolidate these potentially + # non-contiguous buffers, and to do buffer bookkeeping in + # general. + np_col = _create_possibly_ragged_ndarray( + [ + np.ndarray(shape, buffer=buf.as_buffer(), dtype=dtype) + for buf in block.column(tensor_col_name) + ] + ) + + block = block.set_column( + block._ensure_integer_index(tensor_col_name), + tensor_col_name, + ArrowTensorArray.from_numpy(np_col, tensor_col_name), + ) + if existing_block_udf is not None: + # Apply UDF after casting the tensor columns. + block = existing_block_udf(block) + return block + + arrow_parquet_args["_block_udf"] = _block_udf + return arrow_parquet_args + + +def _get_num_output_blocks( + parallelism: int = -1, + override_num_blocks: Optional[int] = None, +) -> int: + if parallelism != -1: + logger.warning( + "The argument ``parallelism`` is deprecated in Ray 2.10. Please specify " + "argument ``override_num_blocks`` instead." + ) + elif override_num_blocks is not None: + parallelism = override_num_blocks + return parallelism + + +def _emit_meta_provider_deprecation_warning( + meta_provider: Optional[BaseFileMetadataProvider], +) -> None: + if meta_provider is not None: + warnings.warn( + "The `meta_provider` argument is deprecated and will be removed after May " + "2025.", + DeprecationWarning, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..57e565dd2d44f878ae6d2009e38b232c814a29a4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/__init__.py @@ -0,0 +1,10 @@ +from ray.experimental.dynamic_resources import set_resource +from ray.experimental.locations import get_local_object_locations, get_object_locations +from ray.experimental.gpu_object_manager import GPUObjectManager + +__all__ = [ + "get_object_locations", + "get_local_object_locations", + "set_resource", + "GPUObjectManager", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/compiled_dag_ref.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/compiled_dag_ref.py new file mode 100644 index 0000000000000000000000000000000000000000..d624457b8b53d419531813643480719274c27136 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/compiled_dag_ref.py @@ -0,0 +1,228 @@ +import asyncio +from typing import Any, List, Optional + +import ray +from ray.exceptions import ( + GetTimeoutError, + RayChannelError, + RayChannelTimeoutError, + RayTaskError, +) +from ray.util.annotations import PublicAPI + + +def _process_return_vals(return_vals: List[Any], return_single_output: bool): + """ + Process return values for return to the DAG caller. Any exceptions found in + return_vals will be raised. If return_single_output=True, it indicates that + the original DAG did not have a MultiOutputNode, so the DAG caller expects + a single return value instead of a list. + """ + # Check for exceptions. + if isinstance(return_vals, Exception): + raise return_vals + + for val in return_vals: + if isinstance(val, RayTaskError): + raise val.as_instanceof_cause() + + if return_single_output: + assert len(return_vals) == 1 + return return_vals[0] + + return return_vals + + +@PublicAPI(stability="alpha") +class CompiledDAGRef: + """ + A reference to a compiled DAG execution result. + + This is a subclass of ObjectRef and resembles ObjectRef. For example, + similar to ObjectRef, ray.get() can be called on it to retrieve the result. + However, there are several major differences: + 1. ray.get() can only be called once per CompiledDAGRef. + 2. ray.wait() is not supported. + 3. CompiledDAGRef cannot be copied, deep copied, or pickled. + 4. CompiledDAGRef cannot be passed as an argument to another task. + """ + + def __init__( + self, + dag: "ray.experimental.CompiledDAG", + execution_index: int, + channel_index: Optional[int] = None, + ): + """ + Args: + dag: The compiled DAG that generated this CompiledDAGRef. + execution_index: The index of the execution for the DAG. + A DAG can be executed multiple times, and execution index + indicates which execution this CompiledDAGRef corresponds to. + actor_execution_loop_refs: The actor execution loop refs that + are used to execute the DAG. This can be used internally to + check the task execution errors in case of exceptions. + channel_index: The index of the DAG's output channel to fetch + the result from. A DAG can have multiple output channels, and + channel index indicates which channel this CompiledDAGRef + corresponds to. If channel index is not provided, this CompiledDAGRef + wraps the results from all output channels. + + """ + self._dag = dag + self._execution_index = execution_index + self._channel_index = channel_index + # Whether ray.get() was called on this CompiledDAGRef. + self._ray_get_called = False + self._dag_output_channels = dag.dag_output_channels + + def __str__(self): + return ( + f"CompiledDAGRef({self._dag.get_id()}, " + f"execution_index={self._execution_index}, " + f"channel_index={self._channel_index})" + ) + + def __copy__(self): + raise ValueError("CompiledDAGRef cannot be copied.") + + def __deepcopy__(self, memo): + raise ValueError("CompiledDAGRef cannot be deep copied.") + + def __reduce__(self): + raise ValueError("CompiledDAGRef cannot be pickled.") + + def __del__(self): + # If the dag is already teardown, it should do nothing. + if self._dag.is_teardown: + return + + if self._ray_get_called: + # get() was already called, no further cleanup is needed. + return + + self._dag._delete_execution_results(self._execution_index, self._channel_index) + + def get(self, timeout: Optional[float] = None): + if self._ray_get_called: + raise ValueError( + "ray.get() can only be called once " + "on a CompiledDAGRef, and it was already called." + ) + + self._ray_get_called = True + try: + self._dag._execute_until( + self._execution_index, self._channel_index, timeout + ) + return_vals = self._dag._get_execution_results( + self._execution_index, self._channel_index + ) + except RayChannelTimeoutError: + raise + except RayChannelError as channel_error: + # If we get a channel error, we'd like to call ray.get() on + # the actor execution loop refs to check if this is a result + # of task execution error which could not be passed down + # (e.g., when a pure NCCL channel is used, it is only + # able to send tensors, but not the wrapped exceptions). + # In this case, we'd like to raise the task execution error + # (which is the actual cause of the channel error) instead + # of the channel error itself. + # TODO(rui): determine which error to raise if multiple + # actor task refs have errors. + actor_execution_loop_refs = list(self._dag.worker_task_refs.values()) + try: + ray.get(actor_execution_loop_refs, timeout=10) + except GetTimeoutError as timeout_error: + raise Exception( + "Timed out when getting the actor execution loop exception. " + "This should not happen, please file a GitHub issue." + ) from timeout_error + except Exception as execution_error: + # Use 'from None' to suppress the context of the original + # channel error, which is not useful to the user. + raise execution_error from None + else: + raise channel_error + except Exception: + raise + return _process_return_vals(return_vals, True) + + +@PublicAPI(stability="alpha") +class CompiledDAGFuture: + """ + A reference to a compiled DAG execution result, when executed with asyncio. + This differs from CompiledDAGRef in that `await` must be called on the + future to get the result, instead of `ray.get()`. + + This resembles async usage of ObjectRefs. For example, similar to + ObjectRef, `await` can be called directly on the CompiledDAGFuture to + retrieve the result. However, there are several major differences: + 1. `await` can only be called once per CompiledDAGFuture. + 2. ray.wait() is not supported. + 3. CompiledDAGFuture cannot be copied, deep copied, or pickled. + 4. CompiledDAGFuture cannot be passed as an argument to another task. + """ + + def __init__( + self, + dag: "ray.experimental.CompiledDAG", + execution_index: int, + fut: "asyncio.Future", + channel_index: Optional[int] = None, + ): + self._dag = dag + self._execution_index = execution_index + self._fut = fut + self._channel_index = channel_index + + def __str__(self): + return ( + f"CompiledDAGFuture({self._dag.get_id()}, " + f"execution_index={self._execution_index}, " + f"channel_index={self._channel_index})" + ) + + def __copy__(self): + raise ValueError("CompiledDAGFuture cannot be copied.") + + def __deepcopy__(self, memo): + raise ValueError("CompiledDAGFuture cannot be deep copied.") + + def __reduce__(self): + raise ValueError("CompiledDAGFuture cannot be pickled.") + + def __await__(self): + if self._fut is None: + raise ValueError( + "CompiledDAGFuture can only be awaited upon once, and it has " + "already been awaited upon." + ) + + # NOTE(swang): If the object is zero-copy deserialized, then it will + # stay in scope as long as this future is in scope. Therefore, we + # delete self._fut here before we return the result to the user. + fut = self._fut + self._fut = None + + if not self._dag._has_execution_results(self._execution_index): + result = yield from fut.__await__() + self._dag._max_finished_execution_index += 1 + self._dag._cache_execution_results(self._execution_index, result) + + return_vals = self._dag._get_execution_results( + self._execution_index, self._channel_index + ) + return _process_return_vals(return_vals, True) + + def __del__(self): + if self._dag.is_teardown: + return + + if self._fut is None: + # await() was already called, no further cleanup is needed. + return + + self._dag._delete_execution_results(self._execution_index, self._channel_index) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/dynamic_resources.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/dynamic_resources.py new file mode 100644 index 0000000000000000000000000000000000000000..bb7bd3948095e911d4a8d1bbb82e13db305e0c4a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/dynamic_resources.py @@ -0,0 +1,7 @@ +def set_resource(resource_name, capacity, node_id=None): + raise DeprecationWarning( + "Dynamic custom resources are deprecated. Consider using placement " + "groups instead (docs.ray.io/en/master/placement-group.html). You " + "can also specify resources at Ray start time with the 'resources' " + "field in the cluster autoscaler." + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/gradio_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/gradio_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..279948c5408b6b0e1a51483dc8575f78bf94d2d3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/gradio_utils.py @@ -0,0 +1,12 @@ +def type_to_string(_type: type) -> str: + """Gets the string representation of a type. + + THe original type can be derived from the returned string representation through + pydoc.locate(). + """ + if _type.__module__ == "typing": + return f"{_type.__module__}.{_type._name}" + elif _type.__module__ == "builtins": + return _type.__name__ + else: + return f"{_type.__module__}.{_type.__name__}" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/internal_kv.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/internal_kv.py new file mode 100644 index 0000000000000000000000000000000000000000..862ff3bacc89364ffa8e2ec247a8ff8ec163fbfe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/internal_kv.py @@ -0,0 +1,121 @@ +from typing import List, Optional, Union + +from ray._private.client_mode_hook import client_mode_hook +from ray._raylet import GcsClient + +_initialized = False +global_gcs_client = None + + +def _internal_kv_reset(): + global global_gcs_client, _initialized + global_gcs_client = None + _initialized = False + + +def internal_kv_get_gcs_client(): + return global_gcs_client + + +def _initialize_internal_kv(gcs_client: GcsClient): + """Initialize the internal KV for use in other function calls.""" + global global_gcs_client, _initialized + assert gcs_client is not None + global_gcs_client = gcs_client + _initialized = True + + +@client_mode_hook +def _internal_kv_initialized(): + return global_gcs_client is not None + + +@client_mode_hook +def _internal_kv_get( + key: Union[str, bytes], *, namespace: Optional[Union[str, bytes]] = None +) -> bytes: + """Fetch the value of a binary key.""" + + if isinstance(key, str): + key = key.encode() + if isinstance(namespace, str): + namespace = namespace.encode() + assert isinstance(key, bytes) + return global_gcs_client.internal_kv_get(key, namespace) + + +@client_mode_hook +def _internal_kv_exists( + key: Union[str, bytes], *, namespace: Optional[Union[str, bytes]] = None +) -> bool: + """Check key exists or not.""" + + if isinstance(key, str): + key = key.encode() + if isinstance(namespace, str): + namespace = namespace.encode() + assert isinstance(key, bytes) + return global_gcs_client.internal_kv_exists(key, namespace) + + +@client_mode_hook +def _pin_runtime_env_uri(uri: str, *, expiration_s: int) -> None: + """Pin a runtime_env URI for expiration_s.""" + return global_gcs_client.pin_runtime_env_uri(uri, expiration_s) + + +@client_mode_hook +def _internal_kv_put( + key: Union[str, bytes], + value: Union[str, bytes], + overwrite: bool = True, + *, + namespace: Optional[Union[str, bytes]] = None +) -> bool: + """Globally associates a value with a given binary key. + + This only has an effect if the key does not already have a value. + + Returns: + already_exists: whether the value already exists. + """ + + if isinstance(key, str): + key = key.encode() + if isinstance(value, str): + value = value.encode() + if isinstance(namespace, str): + namespace = namespace.encode() + assert ( + isinstance(key, bytes) + and isinstance(value, bytes) + and isinstance(overwrite, bool) + ) + return global_gcs_client.internal_kv_put(key, value, overwrite, namespace) == 0 + + +@client_mode_hook +def _internal_kv_del( + key: Union[str, bytes], + *, + del_by_prefix: bool = False, + namespace: Optional[Union[str, bytes]] = None +) -> int: + if isinstance(key, str): + key = key.encode() + if isinstance(namespace, str): + namespace = namespace.encode() + assert isinstance(key, bytes) + return global_gcs_client.internal_kv_del(key, del_by_prefix, namespace) + + +@client_mode_hook +def _internal_kv_list( + prefix: Union[str, bytes], *, namespace: Optional[Union[str, bytes]] = None +) -> List[bytes]: + """List all keys in the internal KV store that start with the prefix.""" + if isinstance(prefix, str): + prefix = prefix.encode() + if isinstance(namespace, str): + namespace = namespace.encode() + return global_gcs_client.internal_kv_keys(prefix, namespace) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/locations.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/locations.py new file mode 100644 index 0000000000000000000000000000000000000000..01d4018904808d1a90468fecc92f2bfc840efe97 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/locations.py @@ -0,0 +1,76 @@ +from typing import Any, Dict, List + +import ray +from ray._raylet import ObjectRef + + +def get_object_locations( + obj_refs: List[ObjectRef], timeout_ms: int = -1 +) -> Dict[ObjectRef, Dict[str, Any]]: + """Lookup the locations for a list of objects. + + It returns a dict maps from an object to its location. The dict excludes + those objects whose location lookup failed. + + Args: + object_refs (List[ObjectRef]): List of object refs. + timeout_ms: The maximum amount of time in micro seconds to wait + before returning. Wait infinitely if it's negative. + + Returns: + A dict maps from an object to its location. The dict excludes those + objects whose location lookup failed. + + The location is stored as a dict with following attributes: + + - node_ids (List[str]): The hex IDs of the nodes that have a + copy of this object. Objects less than 100KB will be in memory + store not plasma store and therefore will have nodes_id = []. + + - object_size (int): The size of data + metadata in bytes. Can be None if the + size is unknown yet (e.g. task not completed). + + Raises: + RuntimeError: if the processes were not started by ray.init(). + ray.exceptions.GetTimeoutError: if it couldn't finish the + request in time. + """ + if not ray.is_initialized(): + raise RuntimeError("Ray hasn't been initialized.") + return ray._private.worker.global_worker.core_worker.get_object_locations( + obj_refs, timeout_ms + ) + + +def get_local_object_locations( + obj_refs: List[ObjectRef], +) -> Dict[ObjectRef, Dict[str, Any]]: + """Lookup the locations for a list of objects *from the local core worker*. No RPCs + are made in this method. + + It returns a dict maps from an object to its location. The dict excludes + those objects whose location lookup failed. + + Args: + object_refs (List[ObjectRef]): List of object refs. + + Returns: + A dict maps from an object to its location. The dict excludes those + objects whose location lookup failed. + + The location is stored as a dict with following attributes: + + - node_ids (List[str]): The hex IDs of the nodes that have a + copy of this object. Objects less than 100KB will be in memory + store not plasma store and therefore will have nodes_id = []. + + - object_size (int): The size of data + metadata in bytes. Can be None if the + size is unknown yet (e.g. task not completed). + + Raises: + RuntimeError: if the processes were not started by ray.init(). + """ + if not ray.is_initialized(): + raise RuntimeError("Ray hasn't been initialized.") + core_worker = ray._private.worker.global_worker.core_worker + return core_worker.get_local_object_locations(obj_refs) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/queue.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/queue.py new file mode 100644 index 0000000000000000000000000000000000000000..c255e987993e02b2c09dbd154c9965e0b4b869c3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/queue.py @@ -0,0 +1,13 @@ +import warnings + +from ray.util.queue import Empty, Full, Queue + +warnings.warn( + DeprecationWarning( + "ray.experimental.queue has been moved to ray.util.queue. " + "Please update your import path." + ), + stacklevel=2, +) + +__all__ = ["Empty", "Full", "Queue"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/shuffle.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/shuffle.py new file mode 100644 index 0000000000000000000000000000000000000000..64ce1792d9d1b42447c177c0ce15f6891b9b2386 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/shuffle.py @@ -0,0 +1,357 @@ +"""A simple distributed shuffle implementation in Ray. + +This utility provides a `simple_shuffle` function that can be used to +redistribute M input partitions into N output partitions. It does this with +a single wave of shuffle map tasks followed by a single wave of shuffle reduce +tasks. Each shuffle map task generates O(N) output objects, and each shuffle +reduce task consumes O(M) input objects, for a total of O(N*M) objects. + +To try an example 10GB shuffle, run: + + $ python -m ray.experimental.shuffle \ + --num-partitions=50 --partition-size=200e6 \ + --object-store-memory=1e9 + +This will print out some statistics on the shuffle execution such as: + + --- Aggregate object store stats across all nodes --- + Plasma memory usage 0 MiB, 0 objects, 0.0% full + Spilled 9487 MiB, 2487 objects, avg write throughput 1023 MiB/s + Restored 9487 MiB, 2487 objects, avg read throughput 1358 MiB/s + Objects consumed by Ray tasks: 9537 MiB. + + Shuffled 9536 MiB in 16.579771757125854 seconds +""" +import time +from typing import Any, Callable, Iterable, List, Tuple, Union + +import ray +from ray import ObjectRef +from ray.cluster_utils import Cluster + +# TODO(ekl) why doesn't TypeVar() deserialize properly in Ray? +# The type produced by the input reader function. +InType = Any +# The type produced by the output writer function. +OutType = Any +# Integer identifying the partition number. +PartitionID = int + + +class ObjectStoreWriter: + """This class is used to stream shuffle map outputs to the object store. + + It can be subclassed to optimize writing (e.g., batching together small + records into larger objects). This will be performance critical if your + input records are small (the example shuffle uses very large records, so + the naive strategy works well). + """ + + def __init__(self): + self.results = [] + + def add(self, item: InType) -> None: + """Queue a single item to be written to the object store. + + This base implementation immediately writes each given item to the + object store as a standalone object. + """ + self.results.append(ray.put(item)) + + def finish(self) -> List[ObjectRef]: + """Return list of object refs representing written items.""" + return self.results + + +class ObjectStoreWriterNonStreaming(ObjectStoreWriter): + def __init__(self): + self.results = [] + + def add(self, item: InType) -> None: + self.results.append(item) + + def finish(self) -> List[Any]: + return self.results + + +def round_robin_partitioner( + input_stream: Iterable[InType], num_partitions: int +) -> Iterable[Tuple[PartitionID, InType]]: + """Round robin partitions items from the input reader. + + You can write custom partitioning functions for your use case. + + Args: + input_stream: Iterator over items from the input reader. + num_partitions: Number of output partitions. + + Yields: + Tuples of (partition id, input item). + """ + i = 0 + for item in input_stream: + yield (i, item) + i += 1 + i %= num_partitions + + +@ray.remote +class _StatusTracker: + def __init__(self): + self.num_map = 0 + self.num_reduce = 0 + self.map_refs = [] + self.reduce_refs = [] + + def register_objectrefs(self, map_refs, reduce_refs): + self.map_refs = map_refs + self.reduce_refs = reduce_refs + + def get_progress(self): + if self.map_refs: + ready, self.map_refs = ray.wait( + self.map_refs, + timeout=1, + num_returns=len(self.map_refs), + fetch_local=False, + ) + self.num_map += len(ready) + elif self.reduce_refs: + ready, self.reduce_refs = ray.wait( + self.reduce_refs, + timeout=1, + num_returns=len(self.reduce_refs), + fetch_local=False, + ) + self.num_reduce += len(ready) + return self.num_map, self.num_reduce + + +def render_progress_bar(tracker, input_num_partitions, output_num_partitions): + from tqdm import tqdm + + num_map = 0 + num_reduce = 0 + map_bar = tqdm(total=input_num_partitions, position=0) + map_bar.set_description("Map Progress.") + reduce_bar = tqdm(total=output_num_partitions, position=1) + reduce_bar.set_description("Reduce Progress.") + + while num_map < input_num_partitions or num_reduce < output_num_partitions: + new_num_map, new_num_reduce = ray.get(tracker.get_progress.remote()) + map_bar.update(new_num_map - num_map) + reduce_bar.update(new_num_reduce - num_reduce) + num_map = new_num_map + num_reduce = new_num_reduce + time.sleep(0.1) + map_bar.close() + reduce_bar.close() + + +def simple_shuffle( + *, + input_reader: Callable[[PartitionID], Iterable[InType]], + input_num_partitions: int, + output_num_partitions: int, + output_writer: Callable[[PartitionID, List[Union[ObjectRef, Any]]], OutType], + partitioner: Callable[ + [Iterable[InType], int], Iterable[PartitionID] + ] = round_robin_partitioner, + object_store_writer: ObjectStoreWriter = ObjectStoreWriter, + tracker: _StatusTracker = None, + streaming: bool = True, +) -> List[OutType]: + """Simple distributed shuffle in Ray. + + Args: + input_reader: Function that generates the input items for a + partition (e.g., data records). + input_num_partitions: The number of input partitions. + output_num_partitions: The desired number of output partitions. + output_writer: Function that consumes a iterator of items for a + given output partition. It returns a single value that will be + collected across all output partitions. + partitioner: Partitioning function to use. Defaults to round-robin + partitioning of input items. + object_store_writer: Class used to write input items to the + object store in an efficient way. Defaults to a naive + implementation that writes each input record as one object. + tracker: Tracker actor that is used to display the progress bar. + streaming: Whether or not if the shuffle will be streaming. + + Returns: + List of outputs from the output writers. + """ + + @ray.remote(num_returns=output_num_partitions) + def shuffle_map(i: PartitionID) -> List[List[Union[Any, ObjectRef]]]: + writers = [object_store_writer() for _ in range(output_num_partitions)] + for out_i, item in partitioner(input_reader(i), output_num_partitions): + writers[out_i].add(item) + return [c.finish() for c in writers] + + @ray.remote + def shuffle_reduce( + i: PartitionID, *mapper_outputs: List[List[Union[Any, ObjectRef]]] + ) -> OutType: + input_objects = [] + assert len(mapper_outputs) == input_num_partitions + for obj_refs in mapper_outputs: + for obj_ref in obj_refs: + input_objects.append(obj_ref) + return output_writer(i, input_objects) + + shuffle_map_out = [shuffle_map.remote(i) for i in range(input_num_partitions)] + + shuffle_reduce_out = [ + shuffle_reduce.remote( + j, *[shuffle_map_out[i][j] for i in range(input_num_partitions)] + ) + for j in range(output_num_partitions) + ] + + if tracker: + tracker.register_objectrefs.remote( + [map_out[0] for map_out in shuffle_map_out], shuffle_reduce_out + ) + render_progress_bar(tracker, input_num_partitions, output_num_partitions) + + return ray.get(shuffle_reduce_out) + + +def build_cluster(num_nodes, num_cpus, object_store_memory): + cluster = Cluster() + for _ in range(num_nodes): + cluster.add_node(num_cpus=num_cpus, object_store_memory=object_store_memory) + cluster.wait_for_nodes() + return cluster + + +def run( + ray_address=None, + object_store_memory=1e9, + num_partitions=5, + partition_size=200e6, + num_nodes=None, + num_cpus=8, + no_streaming=False, + use_wait=False, + tracker=None, +): + import time + + import numpy as np + + is_multi_node = num_nodes + if ray_address: + print("Connecting to a existing cluster...") + ray.init(address=ray_address, ignore_reinit_error=True) + elif is_multi_node: + print("Emulating a cluster...") + print(f"Num nodes: {num_nodes}") + print(f"Num CPU per node: {num_cpus}") + print(f"Object store memory per node: {object_store_memory}") + cluster = build_cluster(num_nodes, num_cpus, object_store_memory) + ray.init(address=cluster.address) + else: + print("Start a new cluster...") + ray.init(num_cpus=num_cpus, object_store_memory=object_store_memory) + + partition_size = int(partition_size) + num_partitions = num_partitions + rows_per_partition = partition_size // (8 * 2) + if tracker is None: + tracker = _StatusTracker.remote() + use_wait = use_wait + + def input_reader(i: PartitionID) -> Iterable[InType]: + for _ in range(num_partitions): + yield np.ones((rows_per_partition // num_partitions, 2), dtype=np.int64) + + def output_writer(i: PartitionID, shuffle_inputs: List[ObjectRef]) -> OutType: + total = 0 + if not use_wait: + for obj_ref in shuffle_inputs: + arr = ray.get(obj_ref) + total += arr.size * arr.itemsize + else: + while shuffle_inputs: + [ready], shuffle_inputs = ray.wait(shuffle_inputs, num_returns=1) + arr = ray.get(ready) + total += arr.size * arr.itemsize + + return total + + def output_writer_non_streaming( + i: PartitionID, shuffle_inputs: List[Any] + ) -> OutType: + total = 0 + for arr in shuffle_inputs: + total += arr.size * arr.itemsize + return total + + if no_streaming: + output_writer_callable = output_writer_non_streaming + object_store_writer = ObjectStoreWriterNonStreaming + else: + object_store_writer = ObjectStoreWriter + output_writer_callable = output_writer + + start = time.time() + output_sizes = simple_shuffle( + input_reader=input_reader, + input_num_partitions=num_partitions, + output_num_partitions=num_partitions, + output_writer=output_writer_callable, + object_store_writer=object_store_writer, + tracker=tracker, + ) + delta = time.time() - start + + time.sleep(0.5) + print() + + summary = None + for i in range(5): + try: + summary = ray._private.internal_api.memory_summary(stats_only=True) + except Exception: + time.sleep(1) + pass + if summary: + break + print(summary) + print() + print( + "Shuffled", int(sum(output_sizes) / (1024 * 1024)), "MiB in", delta, "seconds" + ) + + +def main(): + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--ray-address", type=str, default=None) + parser.add_argument("--object-store-memory", type=float, default=1e9) + parser.add_argument("--num-partitions", type=int, default=5) + parser.add_argument("--partition-size", type=float, default=200e6) + parser.add_argument("--num-nodes", type=int, default=None) + parser.add_argument("--num-cpus", type=int, default=8) + parser.add_argument("--no-streaming", action="store_true", default=False) + parser.add_argument("--use-wait", action="store_true", default=False) + args = parser.parse_args() + + run( + ray_address=args.ray_address, + object_store_memory=args.object_store_memory, + num_partitions=args.num_partitions, + partition_size=args.partition_size, + num_nodes=args.num_nodes, + num_cpus=args.num_cpus, + no_streaming=args.no_streaming, + use_wait=args.use_wait, + ) + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/tf_utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/tf_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..128dc9c8db866ce1b12df8342e32ae899ac2f428 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/tf_utils.py @@ -0,0 +1,4 @@ +raise ImportError( + "ray.experimental.tf_utils has been removed. " + "Use: from ray.rllib.utils import tf_utils." +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/tqdm_ray.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/tqdm_ray.py new file mode 100644 index 0000000000000000000000000000000000000000..e5bcd4943d9ef7ccc18cf97a7edd1e6ebaad5914 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/experimental/tqdm_ray.py @@ -0,0 +1,417 @@ +import builtins +import copy +import json +import logging +import os +import sys +import threading +import time +import uuid +from typing import Any, Dict, Iterable, Optional + +import colorama + +import ray +from ray._private.ray_constants import env_bool +from ray.util.debug import log_once + +try: + import tqdm.auto as real_tqdm +except ImportError: + real_tqdm = None + +logger = logging.getLogger(__name__) + +# Describes the state of a single progress bar. +ProgressBarState = Dict[str, Any] + +# Magic token used to identify Ray TQDM log lines. +RAY_TQDM_MAGIC = "__ray_tqdm_magic_token__" + +# Global manager singleton. +_manager: Optional["_BarManager"] = None +_mgr_lock = threading.Lock() +_print = builtins.print + + +def safe_print(*args, **kwargs): + """Use this as an alternative to `print` that will not corrupt tqdm output. + + By default, the builtin print will be patched to this function when tqdm_ray is + used. To disable this, set RAY_TQDM_PATCH_PRINT=0. + """ + + # Ignore prints to StringIO objects, etc. + if kwargs.get("file") not in [sys.stdout, sys.stderr, None]: + return _print(*args, **kwargs) + + try: + instance().hide_bars() + _print(*args, **kwargs) + finally: + instance().unhide_bars() + + +class tqdm: + """Experimental: Ray distributed tqdm implementation. + + This class lets you use tqdm from any Ray remote task or actor, and have the + progress centrally reported from the driver. This avoids issues with overlapping + / conflicting progress bars, as the driver centrally manages tqdm positions. + + Supports a limited subset of tqdm args. + """ + + DEFAULT_FLUSH_INTERVAL_SECONDS = 1.0 + + def __init__( + self, + iterable: Optional[Iterable] = None, + desc: Optional[str] = None, + total: Optional[int] = None, + unit: Optional[str] = None, + position: Optional[int] = None, + flush_interval_s: Optional[float] = None, + ): + import ray._private.services as services + + if total is None and iterable is not None: + try: + total = len(iterable) + except (TypeError, AttributeError): + total = None + + self._iterable = iterable + self._desc = desc or "" + self._total = total + self._unit = unit or "it" + self._ip = services.get_node_ip_address() + self._pid = os.getpid() + self._pos = position or 0 + self._uuid = uuid.uuid4().hex + self._x = 0 + self._closed = False + self._flush_interval_s = ( + flush_interval_s + if flush_interval_s is not None + else self.DEFAULT_FLUSH_INTERVAL_SECONDS + ) + self._last_flush_time = 0.0 + + def set_description(self, desc): + """Implements tqdm.tqdm.set_description.""" + self._desc = desc + self._dump_state() + + def update(self, n=1): + """Implements tqdm.tqdm.update.""" + self._x += n + self._dump_state() + + def close(self): + """Implements tqdm.tqdm.close.""" + self._closed = True + # Don't bother if ray is shutdown (in __del__ hook). + if ray is not None: + self._dump_state(force_flush=True) + + def refresh(self): + """Implements tqdm.tqdm.refresh.""" + self._dump_state() + + @property + def total(self) -> Optional[int]: + return self._total + + @total.setter + def total(self, total: int): + self._total = total + + def _dump_state(self, force_flush=False) -> None: + now = time.time() + if not force_flush and now - self._last_flush_time < self._flush_interval_s: + return + self._last_flush_time = now + if ray._private.worker.global_worker.mode == ray.WORKER_MODE: + # Include newline in payload to avoid split prints. + # TODO(ekl) we should move this to events.json to avoid log corruption. + print(json.dumps(self._get_state()) + "\n", end="") + else: + instance().process_state_update(copy.deepcopy(self._get_state())) + + def _get_state(self) -> ProgressBarState: + return { + "__magic_token__": RAY_TQDM_MAGIC, + "x": self._x, + "pos": self._pos, + "desc": self._desc, + "total": self._total, + "unit": self._unit, + "ip": self._ip, + "pid": self._pid, + "uuid": self._uuid, + "closed": self._closed, + } + + def __iter__(self): + if self._iterable is None: + raise ValueError("No iterable provided") + for x in iter(self._iterable): + self.update(1) + yield x + + +class _Bar: + """Manages a single virtual progress bar on the driver. + + The actual position of individual bars is calculated as (pos_offset + position), + where `pos_offset` is the position offset determined by the BarManager. + """ + + def __init__(self, state: ProgressBarState, pos_offset: int): + """Initialize a bar. + + Args: + state: The initial progress bar state. + pos_offset: The position offset determined by the BarManager. + """ + self.state = state + self.pos_offset = pos_offset + self.bar = real_tqdm.tqdm( + desc=state["desc"] + " " + str(state["pos"]), + total=state["total"], + unit=state["unit"], + position=pos_offset + state["pos"], + dynamic_ncols=True, + unit_scale=True, + ) + if state["x"]: + self.bar.update(state["x"]) + + def update(self, state: ProgressBarState) -> None: + """Apply the updated worker progress bar state.""" + if state["desc"] != self.state["desc"]: + self.bar.set_description(state["desc"]) + if state["total"] != self.state["total"]: + self.bar.total = state["total"] + self.bar.refresh() + delta = state["x"] - self.state["x"] + if delta: + self.bar.update(delta) + self.bar.refresh() + self.state = state + + def close(self): + """The progress bar has been closed.""" + self.bar.close() + + def update_offset(self, pos_offset: int) -> None: + """Update the position offset assigned by the BarManager.""" + if pos_offset != self.pos_offset: + self.pos_offset = pos_offset + self.bar.clear() + self.bar.pos = -(pos_offset + self.state["pos"]) + self.bar.refresh() + + +class _BarGroup: + """Manages a group of virtual progress bar produced by a single worker. + + All the progress bars in the group have the same `pos_offset` determined by the + BarManager for the process. + """ + + def __init__(self, ip, pid, pos_offset): + self.ip = ip + self.pid = pid + self.pos_offset = pos_offset + self.bars_by_uuid: Dict[str, _Bar] = {} + + def has_bar(self, bar_uuid) -> bool: + """Return whether this bar exists.""" + return bar_uuid in self.bars_by_uuid + + def allocate_bar(self, state: ProgressBarState) -> None: + """Add a new bar to this group.""" + self.bars_by_uuid[state["uuid"]] = _Bar(state, self.pos_offset) + + def update_bar(self, state: ProgressBarState) -> None: + """Update the state of a managed bar in this group.""" + bar = self.bars_by_uuid[state["uuid"]] + bar.update(state) + + def close_bar(self, state: ProgressBarState) -> None: + """Remove a bar from this group.""" + bar = self.bars_by_uuid[state["uuid"]] + # Note: Hide and then unhide bars to prevent flashing of the + # last bar when we are closing multiple bars sequentially. + instance().hide_bars() + bar.close() + del self.bars_by_uuid[state["uuid"]] + instance().unhide_bars() + + def slots_required(self): + """Return the number of pos slots we need to accomodate bars in this group.""" + if not self.bars_by_uuid: + return 0 + return 1 + max(bar.state["pos"] for bar in self.bars_by_uuid.values()) + + def update_offset(self, offset: int) -> None: + """Update the position offset assigned by the BarManager.""" + if offset != self.pos_offset: + self.pos_offset = offset + for bar in self.bars_by_uuid.values(): + bar.update_offset(offset) + + def hide_bars(self) -> None: + """Temporarily hide visible bars to avoid conflict with other log messages.""" + for bar in self.bars_by_uuid.values(): + bar.bar.clear() + + def unhide_bars(self) -> None: + """Opposite of hide_bars().""" + for bar in self.bars_by_uuid.values(): + bar.bar.refresh() + + +class _BarManager: + """Central tqdm manager run on the driver. + + This class holds a collection of BarGroups and updates their `pos_offset` as + needed to ensure individual progress bars do not collide in position, kind of + like a virtual memory manager. + """ + + def __init__(self): + import ray._private.services as services + + self.ip = services.get_node_ip_address() + self.pid = os.getpid() + self.bar_groups = {} + self.in_hidden_state = False + self.num_hides = 0 + self.lock = threading.RLock() + # Avoid colorizing Jupyter output, since the tqdm bar is rendered in + # ipywidgets instead of in the console. + self.should_colorize = not ray.widgets.util.in_notebook() + + def process_state_update(self, state: ProgressBarState) -> None: + """Apply the remote progress bar state update. + + This creates a new bar locally if it doesn't already exist. When a bar is + created or destroyed, we also recalculate and update the `pos_offset` of each + BarGroup on the screen. + """ + with self.lock: + self._process_state_update_locked(state) + + def _process_state_update_locked(self, state: ProgressBarState) -> None: + if not real_tqdm: + if log_once("no_tqdm"): + logger.warning("tqdm is not installed. Progress bars will be disabled.") + return + if state["ip"] == self.ip: + if state["pid"] == self.pid: + prefix = "" + else: + prefix = "(pid={}) ".format(state.get("pid")) + if self.should_colorize: + prefix = "{}{}{}{}".format( + colorama.Style.DIM, + colorama.Fore.CYAN, + prefix, + colorama.Style.RESET_ALL, + ) + else: + prefix = "(pid={}, ip={}) ".format( + state.get("pid"), + state.get("ip"), + ) + if self.should_colorize: + prefix = "{}{}{}{}".format( + colorama.Style.DIM, + colorama.Fore.CYAN, + prefix, + colorama.Style.RESET_ALL, + ) + state["desc"] = prefix + state["desc"] + process = self._get_or_allocate_bar_group(state) + if process.has_bar(state["uuid"]): + # Always call `update_bar` to sync any last remaining updates + # prior to closing. Otherwise, the displayed progress bars + # can be left incomplete, even after execution finishes. + # Fixes https://github.com/ray-project/ray/issues/44983 + process.update_bar(state) + + if state["closed"]: + process.close_bar(state) + self._update_offsets() + else: + process.allocate_bar(state) + self._update_offsets() + + def hide_bars(self) -> None: + """Temporarily hide visible bars to avoid conflict with other log messages.""" + with self.lock: + if not self.in_hidden_state: + self.in_hidden_state = True + self.num_hides += 1 + for group in self.bar_groups.values(): + group.hide_bars() + + def unhide_bars(self) -> None: + """Opposite of hide_bars().""" + with self.lock: + if self.in_hidden_state: + self.in_hidden_state = False + for group in self.bar_groups.values(): + group.unhide_bars() + + def _get_or_allocate_bar_group(self, state: ProgressBarState): + ptuple = (state["ip"], state["pid"]) + if ptuple not in self.bar_groups: + offset = sum(p.slots_required() for p in self.bar_groups.values()) + self.bar_groups[ptuple] = _BarGroup(state["ip"], state["pid"], offset) + return self.bar_groups[ptuple] + + def _update_offsets(self): + offset = 0 + for proc in self.bar_groups.values(): + proc.update_offset(offset) + offset += proc.slots_required() + + +def instance() -> _BarManager: + """Get or create a BarManager for this process.""" + global _manager + + with _mgr_lock: + if _manager is None: + _manager = _BarManager() + if env_bool("RAY_TQDM_PATCH_PRINT", True): + import builtins + + builtins.print = safe_print + return _manager + + +if __name__ == "__main__": + + @ray.remote + def processing(delay): + def sleep(x): + print("Intermediate result", x) + time.sleep(delay) + return x + + ray.data.range(1000, override_num_blocks=100).map( + sleep, compute=ray.data.ActorPoolStrategy(size=1) + ).count() + + ray.get( + [ + processing.remote(0.03), + processing.remote(0.01), + processing.remote(0.05), + ] + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/__init__.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/__init__.pxd new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/common.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/common.pxd new file mode 100644 index 0000000000000000000000000000000000000000..c57822da566085b6f9e145cdc53aa6b02c2376c5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/common.pxd @@ -0,0 +1,777 @@ +from libcpp cimport bool as c_bool +from libcpp.memory cimport shared_ptr, unique_ptr +from libcpp.string cimport string as c_string + +from libc.stdint cimport uint8_t, int32_t, uint64_t, int64_t, uint32_t +from libcpp.unordered_map cimport unordered_map +from libcpp.vector cimport vector as c_vector +from libcpp.pair cimport pair as c_pair +from ray.includes.optional cimport ( + optional, +) +from ray.includes.unique_ids cimport ( + CActorID, + CJobID, + CClusterID, + CWorkerID, + CObjectID, + CTaskID, + CPlacementGroupID, + CNodeID, +) +from ray.includes.function_descriptor cimport ( + CFunctionDescriptor, +) + + +cdef extern from * namespace "polyfill" nogil: + """ + namespace polyfill { + + template + inline typename std::remove_reference::type&& move(T& t) { + return std::move(t); + } + + template + inline typename std::remove_reference::type&& move(T&& t) { + return std::move(t); + } + + } // namespace polyfill + """ + cdef T move[T](T) + + +cdef extern from "ray/common/status.h" namespace "ray" nogil: + # TODO(ryw) in Cython 3.x we can directly use `cdef enum class CStatusCode` + cdef cppclass CStatusCode "ray::StatusCode": + pass + cdef CStatusCode CStatusCode_OK "ray::StatusCode::OK" + c_bool operator==(CStatusCode lhs, CStatusCode rhs) + + cdef cppclass CRayStatus "ray::Status": + CRayStatus() + CRayStatus(CStatusCode code, const c_string &msg) + CRayStatus(CStatusCode code, const c_string &msg, int rpc_code) + CRayStatus(const CRayStatus &s) + + @staticmethod + CRayStatus OK() + + @staticmethod + CRayStatus OutOfMemory(const c_string &msg) + + @staticmethod + CRayStatus KeyError(const c_string &msg) + + @staticmethod + CRayStatus Invalid(const c_string &msg) + + @staticmethod + CRayStatus IOError(const c_string &msg) + + @staticmethod + CRayStatus TypeError(const c_string &msg) + + @staticmethod + CRayStatus UnknownError(const c_string &msg) + + @staticmethod + CRayStatus NotImplemented(const c_string &msg) + + @staticmethod + CRayStatus ObjectStoreFull(const c_string &msg) + + @staticmethod + CRayStatus RedisError(const c_string &msg) + + @staticmethod + CRayStatus TimedOut(const c_string &msg) + + @staticmethod + CRayStatus InvalidArgument(const c_string &msg) + + @staticmethod + CRayStatus Interrupted(const c_string &msg) + + @staticmethod + CRayStatus IntentionalSystemExit(const c_string &msg) + + @staticmethod + CRayStatus UnexpectedSystemExit(const c_string &msg) + + @staticmethod + CRayStatus CreationTaskError(const c_string &msg) + + @staticmethod + CRayStatus NotFound() + + @staticmethod + CRayStatus ObjectRefEndOfStream() + + c_bool ok() + c_bool IsOutOfMemory() + c_bool IsKeyError() + c_bool IsInvalid() + c_bool IsIOError() + c_bool IsTypeError() + c_bool IsUnknownError() + c_bool IsNotImplemented() + c_bool IsObjectStoreFull() + c_bool IsAlreadyExists() + c_bool IsOutOfDisk() + c_bool IsRedisError() + c_bool IsTimedOut() + c_bool IsInvalidArgument() + c_bool IsInterrupted() + c_bool ShouldExitWorker() + c_bool IsObjectNotFound() + c_bool IsNotFound() + c_bool IsObjectUnknownOwner() + c_bool IsRpcError() + c_bool IsOutOfResource() + c_bool IsObjectRefEndOfStream() + c_bool IsIntentionalSystemExit() + c_bool IsUnexpectedSystemExit() + c_bool IsChannelError() + c_bool IsChannelTimeoutError() + + c_string ToString() + c_string CodeAsString() + CStatusCode code() + c_string message() + int rpc_code() + + # We can later add more of the common status factory methods as needed + cdef CRayStatus RayStatus_OK "Status::OK"() + cdef CRayStatus RayStatus_Invalid "Status::Invalid"() + cdef CRayStatus RayStatus_NotImplemented "Status::NotImplemented"() + + +cdef extern from "ray/common/id.h" namespace "ray" nogil: + const CTaskID GenerateTaskId(const CJobID &job_id, + const CTaskID &parent_task_id, + int parent_task_counter) + + +cdef extern from "src/ray/protobuf/common.pb.h" nogil: + cdef cppclass CLanguage "Language": + pass + cdef cppclass CWorkerType "ray::core::WorkerType": + pass + cdef cppclass CWorkerExitType "ray::rpc::WorkerExitType": + pass + cdef cppclass CTaskType "ray::TaskType": + pass + cdef cppclass CTensorTransport "ray::rpc::TensorTransport": + pass + cdef cppclass CPlacementStrategy "ray::core::PlacementStrategy": + pass + cdef cppclass CDefaultSchedulingStrategy "ray::rpc::DefaultSchedulingStrategy": # noqa: E501 + CDefaultSchedulingStrategy() + cdef cppclass CSpreadSchedulingStrategy "ray::rpc::SpreadSchedulingStrategy": # noqa: E501 + CSpreadSchedulingStrategy() + cdef cppclass CPlacementGroupSchedulingStrategy "ray::rpc::PlacementGroupSchedulingStrategy": # noqa: E501 + CPlacementGroupSchedulingStrategy() + void set_placement_group_id(const c_string& placement_group_id) + void set_placement_group_bundle_index(int64_t placement_group_bundle_index) # noqa: E501 + void set_placement_group_capture_child_tasks(c_bool placement_group_capture_child_tasks) # noqa: E501 + cdef cppclass CNodeAffinitySchedulingStrategy "ray::rpc::NodeAffinitySchedulingStrategy": # noqa: E501 + CNodeAffinitySchedulingStrategy() + void set_node_id(const c_string& node_id) + void set_soft(c_bool soft) + void set_spill_on_unavailable(c_bool spill_on_unavailable) + void set_fail_on_unavailable(c_bool fail_on_unavailable) + cdef cppclass CSchedulingStrategy "ray::rpc::SchedulingStrategy": + CSchedulingStrategy() + void clear_scheduling_strategy() + CSpreadSchedulingStrategy* mutable_spread_scheduling_strategy() + CDefaultSchedulingStrategy* mutable_default_scheduling_strategy() + CPlacementGroupSchedulingStrategy* mutable_placement_group_scheduling_strategy() # noqa: E501 + CNodeAffinitySchedulingStrategy* mutable_node_affinity_scheduling_strategy() + CNodeLabelSchedulingStrategy* mutable_node_label_scheduling_strategy() + cdef cppclass CAddress "ray::rpc::Address": + CAddress() + const c_string &SerializeAsString() const + void ParseFromString(const c_string &serialized) + void CopyFrom(const CAddress& address) + const c_string &worker_id() + cdef cppclass CObjectReference "ray::rpc::ObjectReference": + CObjectReference() + CAddress owner_address() const + const c_string &object_id() const + const c_string &call_site() const + cdef cppclass CNodeLabelSchedulingStrategy "ray::rpc::NodeLabelSchedulingStrategy": # noqa: E501 + CNodeLabelSchedulingStrategy() + CLabelMatchExpressions* mutable_hard() + CLabelMatchExpressions* mutable_soft() + cdef cppclass CLabelMatchExpressions "ray::rpc::LabelMatchExpressions": # noqa: E501 + CLabelMatchExpressions() + CLabelMatchExpression* add_expressions() + cdef cppclass CLabelMatchExpression "ray::rpc::LabelMatchExpression": # noqa: E501 + CLabelMatchExpression() + void set_key(const c_string &key) + CLabelOperator* mutable_operator_() + cdef cppclass CLabelIn "ray::rpc::LabelIn": # noqa: E501 + CLabelIn() + void add_values(const c_string &value) + cdef cppclass CLabelNotIn "ray::rpc::LabelNotIn": # noqa: E501 + CLabelNotIn() + void add_values(const c_string &value) + cdef cppclass CLabelExists "ray::rpc::LabelExists": # noqa: E501 + CLabelExists() + cdef cppclass CLabelDoesNotExist "ray::rpc::LabelDoesNotExist": # noqa: E501 + CLabelDoesNotExist() + cdef cppclass CLabelNotIn "ray::rpc::LabelNotIn": # noqa: E501 + CLabelNotIn() + void add_values(const c_string &value) + cdef cppclass CLabelOperator "ray::rpc::LabelOperator": # noqa: E501 + CLabelOperator() + CLabelIn* mutable_label_in() + CLabelNotIn* mutable_label_not_in() + CLabelExists* mutable_label_exists() + CLabelDoesNotExist* mutable_label_does_not_exist() + cdef cppclass CLineageReconstructionTask "ray::rpc::LineageReconstructionTask": + CLineageReconstructionTask() + const c_string &SerializeAsString() const + + +# This is a workaround for C++ enum class since Cython has no corresponding +# representation. +cdef extern from "src/ray/protobuf/common.pb.h" nogil: + cdef CLanguage LANGUAGE_PYTHON "Language::PYTHON" + cdef CLanguage LANGUAGE_CPP "Language::CPP" + cdef CLanguage LANGUAGE_JAVA "Language::JAVA" + +cdef extern from "src/ray/protobuf/common.pb.h" nogil: + cdef CWorkerType WORKER_TYPE_WORKER "ray::core::WorkerType::WORKER" + cdef CWorkerType WORKER_TYPE_DRIVER "ray::core::WorkerType::DRIVER" + cdef CWorkerType WORKER_TYPE_SPILL_WORKER "ray::core::WorkerType::SPILL_WORKER" # noqa: E501 + cdef CWorkerType WORKER_TYPE_RESTORE_WORKER "ray::core::WorkerType::RESTORE_WORKER" # noqa: E501 + cdef CWorkerType WORKER_TYPE_UTIL_WORKER "ray::core::WorkerType::UTIL_WORKER" # noqa: E501 + cdef CWorkerExitType WORKER_EXIT_TYPE_USER_ERROR "ray::rpc::WorkerExitType::USER_ERROR" # noqa: E501 + cdef CWorkerExitType WORKER_EXIT_TYPE_SYSTEM_ERROR "ray::rpc::WorkerExitType::SYSTEM_ERROR" # noqa: E501 + cdef CWorkerExitType WORKER_EXIT_TYPE_INTENTIONAL_SYSTEM_ERROR "ray::rpc::WorkerExitType::INTENDED_SYSTEM_EXIT" # noqa: E501 + +cdef extern from "src/ray/protobuf/common.pb.h" nogil: + cdef CTaskType TASK_TYPE_NORMAL_TASK "ray::TaskType::NORMAL_TASK" + cdef CTaskType TASK_TYPE_ACTOR_CREATION_TASK "ray::TaskType::ACTOR_CREATION_TASK" # noqa: E501 + cdef CTaskType TASK_TYPE_ACTOR_TASK "ray::TaskType::ACTOR_TASK" + +cdef extern from "src/ray/protobuf/common.pb.h" nogil: + cdef CTensorTransport TENSOR_TRANSPORT_OBJECT_STORE "ray::rpc::TensorTransport::OBJECT_STORE" + +cdef extern from "src/ray/protobuf/common.pb.h" nogil: + cdef CPlacementStrategy PLACEMENT_STRATEGY_PACK \ + "ray::core::PlacementStrategy::PACK" + cdef CPlacementStrategy PLACEMENT_STRATEGY_SPREAD \ + "ray::core::PlacementStrategy::SPREAD" + cdef CPlacementStrategy PLACEMENT_STRATEGY_STRICT_PACK \ + "ray::core::PlacementStrategy::STRICT_PACK" + cdef CPlacementStrategy PLACEMENT_STRATEGY_STRICT_SPREAD \ + "ray::core::PlacementStrategy::STRICT_SPREAD" + +cdef extern from "ray/common/buffer.h" namespace "ray" nogil: + cdef cppclass CBuffer "ray::Buffer": + uint8_t *Data() const + size_t Size() const + c_bool IsPlasmaBuffer() const + + cdef cppclass LocalMemoryBuffer(CBuffer): + LocalMemoryBuffer(uint8_t *data, size_t size, c_bool copy_data) + LocalMemoryBuffer(size_t size) + + cdef cppclass SharedMemoryBuffer(CBuffer): + SharedMemoryBuffer( + const shared_ptr[CBuffer] &buffer, + int64_t offset, + int64_t size) + c_bool IsPlasmaBuffer() const + +cdef extern from "ray/common/ray_object.h" nogil: + cdef cppclass CRayObject "ray::RayObject": + CRayObject(const shared_ptr[CBuffer] &data, + const shared_ptr[CBuffer] &metadata, + const c_vector[CObjectReference] &nested_refs) + c_bool HasData() const + c_bool HasMetadata() const + const size_t DataSize() const + const shared_ptr[CBuffer] &GetData() + const shared_ptr[CBuffer] &GetMetadata() const + c_bool IsInPlasmaError() const + CTensorTransport GetTensorTransport() const + +cdef extern from "ray/core_worker/common.h" nogil: + cdef cppclass CRayFunction "ray::core::RayFunction": + CRayFunction() + CRayFunction(CLanguage language, + const CFunctionDescriptor &function_descriptor) + CLanguage GetLanguage() + const CFunctionDescriptor GetFunctionDescriptor() + + cdef cppclass CTaskArg "ray::TaskArg": + pass + + cdef cppclass CTaskArgByReference "ray::TaskArgByReference": + CTaskArgByReference(const CObjectID &object_id, + const CAddress &owner_address, + const c_string &call_site) + + cdef cppclass CTaskArgByValue "ray::TaskArgByValue": + CTaskArgByValue(const shared_ptr[CRayObject] &data) + + cdef cppclass CTaskOptions "ray::core::TaskOptions": + CTaskOptions() + CTaskOptions(c_string name, int num_returns, + unordered_map[c_string, double] &resources, + c_string concurrency_group_name, + int64_t generator_backpressure_num_objects) + CTaskOptions(c_string name, int num_returns, + unordered_map[c_string, double] &resources, + c_string concurrency_group_name, + int64_t generator_backpressure_num_objects, + c_string serialized_runtime_env) + CTaskOptions(c_string name, int num_returns, + unordered_map[c_string, double] &resources, + c_string concurrency_group_name, + int64_t generator_backpressure_num_objects, + c_string serialized_runtime_env, + c_bool enable_task_events, + const unordered_map[c_string, c_string] &labels, + const unordered_map[c_string, c_string] &label_selector, + CTensorTransport tensor_transport) + + cdef cppclass CActorCreationOptions "ray::core::ActorCreationOptions": + CActorCreationOptions() + CActorCreationOptions( + int64_t max_restarts, + int64_t max_task_retries, + int32_t max_concurrency, + const unordered_map[c_string, double] &resources, + const unordered_map[c_string, double] &placement_resources, + const c_vector[c_string] &dynamic_worker_options, + optional[c_bool] is_detached, c_string &name, c_string &ray_namespace, + c_bool is_asyncio, + const CSchedulingStrategy &scheduling_strategy, + c_string serialized_runtime_env, + const c_vector[CConcurrencyGroup] &concurrency_groups, + c_bool execute_out_of_order, + int32_t max_pending_calls, + c_bool enable_task_events, + const unordered_map[c_string, c_string] &labels, + const unordered_map[c_string, c_string] &label_selector) + + cdef cppclass CPlacementGroupCreationOptions \ + "ray::core::PlacementGroupCreationOptions": + CPlacementGroupCreationOptions() + CPlacementGroupCreationOptions( + const c_string &name, + CPlacementStrategy strategy, + const c_vector[unordered_map[c_string, double]] &bundles, + c_bool is_detached, + double max_cpu_fraction_per_node, + CNodeID soft_target_node_id, + const c_vector[unordered_map[c_string, c_string]] &bundle_label_selector, + ) + + cdef cppclass CObjectLocation "ray::core::ObjectLocation": + const CNodeID &GetPrimaryNodeID() const + const int64_t GetObjectSize() const + const c_vector[CNodeID] &GetNodeIDs() const + c_bool IsSpilled() const + const c_string &GetSpilledURL() const + const CNodeID &GetSpilledNodeID() const + const c_bool GetDidSpill() const + +cdef extern from "ray/gcs/gcs_client/python_callbacks.h" namespace "ray::gcs": + cdef cppclass MultiItemPyCallback[T]: + MultiItemPyCallback( + object (*)(CRayStatus, c_vector[T]) nogil, + void (object, object) nogil, + object) nogil + + cdef cppclass OptionalItemPyCallback[T]: + OptionalItemPyCallback( + object (*)(CRayStatus, optional[T]) nogil, + void (object, object) nogil, + object) nogil + + cdef cppclass StatusPyCallback: + StatusPyCallback( + object (*)(CRayStatus) nogil, + void (object, object) nogil, + object) nogil + +cdef extern from "ray/gcs/gcs_client/accessor.h" nogil: + cdef cppclass CActorInfoAccessor "ray::gcs::ActorInfoAccessor": + CRayStatus AsyncGetAllByFilter( + const optional[CActorID] &actor_id, + const optional[CJobID] &job_id, + const optional[c_string] &actor_state_name, + const MultiItemPyCallback[CActorTableData] &callback, + int64_t timeout_ms) + + CRayStatus AsyncKillActor(const CActorID &actor_id, + c_bool force_kill, + c_bool no_restart, + const StatusPyCallback &callback, + int64_t timeout_ms) + + cdef cppclass CJobInfoAccessor "ray::gcs::JobInfoAccessor": + CRayStatus GetAll( + const optional[c_string] &job_or_submission_id, + c_bool skip_submission_job_info_field, + c_bool skip_is_running_tasks_field, + c_vector[CJobTableData] &result, + int64_t timeout_ms) + + CRayStatus AsyncGetAll( + const optional[c_string] &job_or_submission_id, + c_bool skip_submission_job_info_field, + c_bool skip_is_running_tasks_field, + const MultiItemPyCallback[CJobTableData] &callback, + int64_t timeout_ms) + + cdef cppclass CNodeInfoAccessor "ray::gcs::NodeInfoAccessor": + CRayStatus CheckAlive( + const c_vector[c_string] &raylet_addresses, + int64_t timeout_ms, + c_vector[c_bool] &result) + + CRayStatus AsyncCheckAlive( + const c_vector[c_string] &raylet_addresses, + int64_t timeout_ms, + const MultiItemPyCallback[c_bool] &callback) + + CRayStatus DrainNodes( + const c_vector[CNodeID] &node_ids, + int64_t timeout_ms, + c_vector[c_string] &drained_node_ids) + + CRayStatus GetAllNoCache( + int64_t timeout_ms, + c_vector[CGcsNodeInfo] &result) + + CRayStatus AsyncGetAll( + const MultiItemPyCallback[CGcsNodeInfo] &callback, + int64_t timeout_ms, + optional[CNodeID] node_id) + + cdef cppclass CNodeResourceInfoAccessor "ray::gcs::NodeResourceInfoAccessor": + CRayStatus GetAllResourceUsage( + int64_t timeout_ms, + CGetAllResourceUsageReply &serialized_reply) + + cdef cppclass CInternalKVAccessor "ray::gcs::InternalKVAccessor": + CRayStatus Keys( + const c_string &ns, + const c_string &prefix, + int64_t timeout_ms, + c_vector[c_string] &value) + + CRayStatus Put( + const c_string &ns, + const c_string &key, + const c_string &value, + c_bool overwrite, + int64_t timeout_ms, + c_bool &added) + + CRayStatus Get( + const c_string &ns, + const c_string &key, + int64_t timeout_ms, + c_string &value) + + CRayStatus MultiGet( + const c_string &ns, + const c_vector[c_string] &keys, + int64_t timeout_ms, + unordered_map[c_string, c_string] &values) + + CRayStatus Del( + const c_string &ns, + const c_string &key, + c_bool del_by_prefix, + int64_t timeout_ms, + int& num_deleted) + + CRayStatus Exists( + const c_string &ns, + const c_string &key, + int64_t timeout_ms, + c_bool &exists) + + CRayStatus AsyncInternalKVKeys( + const c_string &ns, + const c_string &prefix, + int64_t timeout_ms, + const OptionalItemPyCallback[c_vector[c_string]] &callback) + + CRayStatus AsyncInternalKVGet( + const c_string &ns, + const c_string &key, + int64_t timeout_ms, + const OptionalItemPyCallback[c_string] &callback) + + CRayStatus AsyncInternalKVMultiGet( + const c_string &ns, + const c_vector[c_string] &keys, + int64_t timeout_ms, + const OptionalItemPyCallback[unordered_map[c_string, c_string]] &callback) + + CRayStatus AsyncInternalKVPut( + const c_string &ns, + const c_string &key, + const c_string &value, + c_bool overwrite, + int64_t timeout_ms, + const OptionalItemPyCallback[c_bool] &callback) + + CRayStatus AsyncInternalKVExists( + const c_string &ns, + const c_string &key, + int64_t timeout_ms, + const OptionalItemPyCallback[c_bool] &callback) + + CRayStatus AsyncInternalKVDel( + const c_string &ns, + const c_string &key, + c_bool del_by_prefix, + int64_t timeout_ms, + const OptionalItemPyCallback[int] &callback) + + cdef cppclass CRuntimeEnvAccessor "ray::gcs::RuntimeEnvAccessor": + CRayStatus PinRuntimeEnvUri( + const c_string &uri, + int expiration_s, + int64_t timeout_ms) + + cdef cppclass CAutoscalerStateAccessor "ray::gcs::AutoscalerStateAccessor": + + CRayStatus RequestClusterResourceConstraint( + int64_t timeout_ms, + const c_vector[unordered_map[c_string, double]] &bundles, + const c_vector[int64_t] &count_array + ) + + CRayStatus GetClusterResourceState( + int64_t timeout_ms, + c_string &serialized_reply + ) + + CRayStatus GetClusterStatus( + int64_t timeout_ms, + c_string &serialized_reply + ) + + CRayStatus AsyncGetClusterStatus( + int64_t timeout_ms, + const OptionalItemPyCallback[CGetClusterStatusReply] &callback) + + CRayStatus ReportAutoscalingState( + int64_t timeout_ms, + const c_string &serialized_state + ) + + CRayStatus ReportClusterConfig( + int64_t timeout_ms, + const c_string &serialized_cluster_config + ) + + CRayStatus DrainNode( + const c_string &node_id, + int32_t reason, + const c_string &reason_message, + int64_t deadline_timestamp_ms, + int64_t timeout_ms, + c_bool &is_accepted, + c_string &rejection_reason_message + ) + + cdef cppclass CPublisherAccessor "ray::gcs::PublisherAccessor": + CRayStatus PublishError( + c_string key_id, + CErrorTableData data, + int64_t timeout_ms) + + CRayStatus PublishLogs( + c_string key_id, + CLogBatch data, + int64_t timeout_ms) + + CRayStatus AsyncPublishNodeResourceUsage( + c_string key_id, + c_string node_resource_usage, + const StatusPyCallback &callback + ) + + +cdef extern from "ray/gcs/gcs_client/gcs_client.h" nogil: + cdef enum CGrpcStatusCode "grpc::StatusCode": + UNAVAILABLE "grpc::StatusCode::UNAVAILABLE", + UNKNOWN "grpc::StatusCode::UNKNOWN", + DEADLINE_EXCEEDED "grpc::StatusCode::DEADLINE_EXCEEDED", + RESOURCE_EXHAUSTED "grpc::StatusCode::RESOURCE_EXHAUSTED", + UNIMPLEMENTED "grpc::StatusCode::UNIMPLEMENTED", + + cdef cppclass CGcsClientOptions "ray::gcs::GcsClientOptions": + CGcsClientOptions( + const c_string &gcs_address, int port, CClusterID cluster_id, + c_bool allow_cluster_id_nil, c_bool fetch_cluster_id_if_nil) + + cdef cppclass CGcsClient "ray::gcs::GcsClient": + CGcsClient(const CGcsClientOptions &options) + + c_pair[c_string, int] GetGcsServerAddress() const + CClusterID GetClusterId() const + + CActorInfoAccessor& Actors() + CJobInfoAccessor& Jobs() + CInternalKVAccessor& InternalKV() + CNodeInfoAccessor& Nodes() + CNodeResourceInfoAccessor& NodeResources() + CRuntimeEnvAccessor& RuntimeEnvs() + CAutoscalerStateAccessor& Autoscaler() + CPublisherAccessor& Publisher() + + cdef CRayStatus ConnectOnSingletonIoContext(CGcsClient &gcs_client, int timeout_ms) + +cdef extern from "ray/gcs/gcs_client/gcs_client.h" namespace "ray::gcs" nogil: + unordered_map[c_string, double] PythonGetResourcesTotal( + const CGcsNodeInfo& node_info) + +cdef extern from "ray/gcs/pubsub/gcs_pub_sub.h" nogil: + cdef cppclass CPythonGcsSubscriber "ray::gcs::PythonGcsSubscriber": + + CPythonGcsSubscriber( + const c_string& gcs_address, int gcs_port, CChannelType channel_type, + const c_string& subscriber_id, const c_string& worker_id) + + CRayStatus Subscribe() + + int64_t last_batch_size() + + CRayStatus PollError( + c_string* key_id, int64_t timeout_ms, CErrorTableData* data) + + CRayStatus PollLogs( + c_string* key_id, int64_t timeout_ms, CLogBatch* data) + + CRayStatus PollActor( + c_string* key_id, int64_t timeout_ms, CActorTableData* data) + + CRayStatus Close() + +cdef extern from "ray/gcs/pubsub/gcs_pub_sub.h" namespace "ray::gcs" nogil: + c_vector[c_string] PythonGetLogBatchLines(const CLogBatch& log_batch) + +cdef extern from "ray/gcs/gcs_client/gcs_client.h" namespace "ray::gcs" nogil: + unordered_map[c_string, c_string] PythonGetNodeLabels( + const CGcsNodeInfo& node_info) + +cdef extern from "src/ray/protobuf/gcs.pb.h" nogil: + cdef enum CChannelType "ray::rpc::ChannelType": + RAY_ERROR_INFO_CHANNEL "ray::rpc::ChannelType::RAY_ERROR_INFO_CHANNEL", + RAY_LOG_CHANNEL "ray::rpc::ChannelType::RAY_LOG_CHANNEL", + GCS_ACTOR_CHANNEL "ray::rpc::ChannelType::GCS_ACTOR_CHANNEL", + + cdef cppclass CJobConfig "ray::rpc::JobConfig": + c_string ray_namespace() const + const c_string &SerializeAsString() const + + cdef cppclass CNodeDeathInfo "ray::rpc::NodeDeathInfo": + int reason() const + c_string reason_message() const + + cdef cppclass CGcsNodeInfo "ray::rpc::GcsNodeInfo": + c_string node_id() const + c_string node_name() const + int state() const + c_string node_manager_address() const + c_string node_manager_hostname() const + int node_manager_port() const + int object_manager_port() const + c_string object_store_socket_name() const + c_string raylet_socket_name() const + int metrics_export_port() const + int runtime_env_agent_port() const + CNodeDeathInfo death_info() const + void ParseFromString(const c_string &serialized) + const c_string& SerializeAsString() const + + cdef enum CGcsNodeState "ray::rpc::GcsNodeInfo_GcsNodeState": + ALIVE "ray::rpc::GcsNodeInfo_GcsNodeState_ALIVE", + + cdef cppclass CJobTableData "ray::rpc::JobTableData": + c_string job_id() const + c_bool is_dead() const + CJobConfig config() const + const c_string &SerializeAsString() const + + cdef cppclass CGetAllResourceUsageReply "ray::rpc::GetAllResourceUsageReply": + const c_string& SerializeAsString() const + + cdef cppclass CPythonFunction "ray::rpc::PythonFunction": + void set_key(const c_string &key) + c_string key() const + + cdef cppclass CErrorTableData "ray::rpc::ErrorTableData": + c_string job_id() const + c_string type() const + c_string error_message() const + double timestamp() const + + void set_job_id(const c_string &job_id) + void set_type(const c_string &type) + void set_error_message(const c_string &error_message) + void set_timestamp(double timestamp) + + cdef cppclass CLogBatch "ray::rpc::LogBatch": + c_string ip() const + c_string pid() const + c_string job_id() const + c_bool is_error() const + c_string actor_name() const + c_string task_name() const + + void set_ip(const c_string &ip) + void set_pid(const c_string &pid) + void set_job_id(const c_string &job_id) + void set_is_error(c_bool is_error) + void add_lines(const c_string &line) + void set_actor_name(const c_string &actor_name) + void set_task_name(const c_string &task_name) + + cdef cppclass CActorTableData "ray::rpc::ActorTableData": + CAddress address() const + void ParseFromString(const c_string &serialized) + const c_string &SerializeAsString() const + +cdef extern from "src/ray/protobuf/autoscaler.pb.h" nogil: + cdef cppclass CGetClusterStatusReply "ray::rpc::autoscaler::GetClusterStatusReply": + c_string serialized_cluster_status() const + void ParseFromString(const c_string &serialized) + const c_string &SerializeAsString() const + +cdef extern from "ray/common/task/task_spec.h" nogil: + cdef cppclass CConcurrencyGroup "ray::ConcurrencyGroup": + CConcurrencyGroup( + const c_string &name, + uint32_t max_concurrency, + const c_vector[CFunctionDescriptor] &c_fds) + CConcurrencyGroup() + c_string GetName() const + uint32_t GetMaxConcurrency() const + c_vector[CFunctionDescriptor] GetFunctionDescriptors() const + +cdef extern from "ray/common/constants.h" nogil: + cdef const char[] kWorkerSetupHookKeyName + cdef int kResourceUnitScaling + cdef const char[] kImplicitResourcePrefix + cdef int kStreamingGeneratorReturn + cdef const char[] kGcsAutoscalerStateNamespace + cdef const char[] kGcsAutoscalerV2EnabledKey + cdef const char[] kGcsAutoscalerClusterConfigKey + cdef const char[] kGcsPidKey diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/function_descriptor.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/function_descriptor.pxd new file mode 100644 index 0000000000000000000000000000000000000000..5124405772b8ae0382625f95843943861be55bfb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/function_descriptor.pxd @@ -0,0 +1,80 @@ +from libc.stdint cimport uint8_t, uint64_t +from libcpp cimport bool as c_bool +from libcpp.memory cimport unique_ptr, shared_ptr +from libcpp.string cimport string as c_string +from libcpp.unordered_map cimport unordered_map +from libcpp.vector cimport vector as c_vector + +from ray.includes.common cimport ( + CLanguage, +) +from ray.includes.unique_ids cimport ( + CActorID, + CJobID, + CObjectID, + CTaskID, +) + +cdef extern from "src/ray/protobuf/common.pb.h" nogil: + cdef cppclass CFunctionDescriptorType \ + "ray::FunctionDescriptorType": + pass + + cdef CFunctionDescriptorType EmptyFunctionDescriptorType \ + "ray::FunctionDescriptorType::FUNCTION_DESCRIPTOR_NOT_SET" + cdef CFunctionDescriptorType JavaFunctionDescriptorType \ + "ray::FunctionDescriptorType::kJavaFunctionDescriptor" + cdef CFunctionDescriptorType PythonFunctionDescriptorType \ + "ray::FunctionDescriptorType::kPythonFunctionDescriptor" + cdef CFunctionDescriptorType CppFunctionDescriptorType \ + "ray::FunctionDescriptorType::kCppFunctionDescriptor" + + +cdef extern from "ray/common/function_descriptor.h" nogil: + cdef cppclass CFunctionDescriptorInterface \ + "ray::FunctionDescriptorInterface": + CFunctionDescriptorType Type() + c_string ToString() + c_string Serialize() + + ctypedef shared_ptr[CFunctionDescriptorInterface] CFunctionDescriptor \ + "ray::FunctionDescriptor" + + cdef cppclass CFunctionDescriptorBuilder "ray::FunctionDescriptorBuilder": + @staticmethod + CFunctionDescriptor Empty() + + @staticmethod + CFunctionDescriptor BuildJava(const c_string &class_name, + const c_string &function_name, + const c_string &signature) + + @staticmethod + CFunctionDescriptor BuildPython(const c_string &module_name, + const c_string &class_name, + const c_string &function_name, + const c_string &function_source_hash) + + @staticmethod + CFunctionDescriptor BuildCpp(const c_string &function_name, + const c_string &caller, + const c_string &class_name) + + @staticmethod + CFunctionDescriptor Deserialize(const c_string &serialized_binary) + + cdef cppclass CJavaFunctionDescriptor "ray::JavaFunctionDescriptor": + c_string ClassName() + c_string FunctionName() + c_string Signature() + + cdef cppclass CPythonFunctionDescriptor "ray::PythonFunctionDescriptor": + c_string ModuleName() + c_string ClassName() + c_string FunctionName() + c_string FunctionHash() + + cdef cppclass CCppFunctionDescriptor "ray::CppFunctionDescriptor": + c_string FunctionName() + c_string Caller() + c_string ClassName() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/global_state_accessor.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/global_state_accessor.pxd new file mode 100644 index 0000000000000000000000000000000000000000..f6733151e80050d22cb200759065031440f6b84b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/global_state_accessor.pxd @@ -0,0 +1,147 @@ +from libcpp.string cimport string as c_string +from libcpp cimport bool as c_bool +from libcpp.vector cimport vector as c_vector +from libcpp.unordered_map cimport unordered_map +from libcpp.memory cimport unique_ptr +from libc.stdint cimport ( + int32_t as c_int32_t, + uint32_t as c_uint32_t, + int64_t as c_int64_t, +) +from ray.includes.unique_ids cimport ( + CActorID, + CJobID, + CNodeID, + CObjectID, + CWorkerID, + CPlacementGroupID, +) +from ray.includes.common cimport ( + CRayStatus, + CGcsClientOptions, +) +from ray.includes.optional cimport ( + optional +) + +cdef extern from "ray/gcs/gcs_client/global_state_accessor.h" nogil: + cdef cppclass CGlobalStateAccessor "ray::gcs::GlobalStateAccessor": + CGlobalStateAccessor(const CGcsClientOptions&) + c_bool Connect() + void Disconnect() + c_vector[c_string] GetAllJobInfo( + c_bool skip_submission_job_info_field, c_bool skip_is_running_tasks_field) + CJobID GetNextJobID() + c_vector[c_string] GetAllNodeInfo() + c_vector[c_string] GetAllAvailableResources() + c_vector[c_string] GetAllTotalResources() + unordered_map[CNodeID, c_int64_t] GetDrainingNodes() + unique_ptr[c_string] GetInternalKV( + const c_string &namespace, const c_string &key) + c_vector[c_string] GetAllTaskEvents() + unique_ptr[c_string] GetObjectInfo(const CObjectID &object_id) + unique_ptr[c_string] GetAllResourceUsage() + c_vector[c_string] GetAllActorInfo( + optional[CActorID], optional[CJobID], optional[c_string]) + unique_ptr[c_string] GetActorInfo(const CActorID &actor_id) + unique_ptr[c_string] GetWorkerInfo(const CWorkerID &worker_id) + c_vector[c_string] GetAllWorkerInfo() + c_bool AddWorkerInfo(const c_string &serialized_string) + c_bool UpdateWorkerDebuggerPort(const CWorkerID &worker_id, + const c_uint32_t debuger_port) + c_bool UpdateWorkerNumPausedThreads(const CWorkerID &worker_id, + const c_int32_t num_paused_threads_delta) + c_uint32_t GetWorkerDebuggerPort(const CWorkerID &worker_id) + unique_ptr[c_string] GetPlacementGroupInfo( + const CPlacementGroupID &placement_group_id) + unique_ptr[c_string] GetPlacementGroupByName( + const c_string &placement_group_name, + const c_string &ray_namespace, + ) + c_vector[c_string] GetAllPlacementGroupInfo() + c_string GetSystemConfig() + CRayStatus GetNodeToConnectForDriver( + const c_string &node_ip_address, + c_string *node_to_connect) + CRayStatus GetNode( + const c_string &node_id_hex_str, + c_string *node_info) + +cdef extern from * namespace "ray::gcs" nogil: + """ + #include + #include "ray/gcs/gcs_server/store_client_kv.h" + #include "ray/gcs/redis_client.h" + #include "ray/gcs/store_client/redis_store_client.h" + namespace ray { + namespace gcs { + + bool RedisGetKeySync(const std::string& host, + int32_t port, + const std::string& username, + const std::string& password, + bool use_ssl, + const std::string& config, + const std::string& key, + std::string* data) { + // Logging default value see class `RayLog`. + InitShutdownRAII ray_log_shutdown_raii(ray::RayLog::StartRayLog, + ray::RayLog::ShutDownRayLog, + "ray_init", + ray::RayLogLevel::WARNING, + /*log_filepath=*/"", + /*err_log_filepath=*/"", + /*log_rotation_max_size=*/1ULL << 29, + /*log_rotation_file_num=*/10); + + RedisClientOptions options(host, port, username, password, use_ssl); + + std::string config_list; + RAY_CHECK(absl::Base64Unescape(config, &config_list)); + RayConfig::instance().initialize(config_list); + + instrumented_io_context io_service{/*enable_lag_probe=*/false, /*running_on_single_thread=*/true}; + + auto redis_client = std::make_shared(options); + auto status = redis_client->Connect(io_service); + RAY_CHECK_OK(status) << "Failed to connect to redis."; + + auto cli = std::make_unique( + std::make_unique(std::move(redis_client))); + + bool ret_val = false; + cli->Get("session", key, {[&](std::optional result) { + if (result.has_value()) { + *data = result.value(); + ret_val = true; + } else { + RAY_LOG(INFO) << "Failed to retrieve the key " << key + << " from persistent storage."; + ret_val = false; + } + }, io_service}); + io_service.run_for(std::chrono::milliseconds(1000)); + + return ret_val; + } + + } + } + """ + c_bool RedisGetKeySync(const c_string& host, + c_int32_t port, + const c_string& username, + const c_string& password, + c_bool use_ssl, + const c_string& config, + const c_string& key, + c_string* data) + + +cdef extern from "ray/gcs/store_client/redis_store_client.h" namespace "ray::gcs" nogil: + c_bool RedisDelKeyPrefixSync(const c_string& host, + c_int32_t port, + const c_string& username, + const c_string& password, + c_bool use_ssl, + const c_string& key_prefix) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/libcoreworker.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/libcoreworker.pxd new file mode 100644 index 0000000000000000000000000000000000000000..fd90851311a33a21230997be6a2d1a3211b2873d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/libcoreworker.pxd @@ -0,0 +1,456 @@ +# cython: profile = False +# distutils: language = c++ +# cython: embedsignature = True + +from libc.stdint cimport int64_t, uint64_t +from libcpp cimport bool as c_bool +from libcpp.functional cimport function +from libcpp.memory cimport shared_ptr, unique_ptr +from libcpp.pair cimport pair as c_pair +from libcpp.string cimport string as c_string +from libcpp.unordered_map cimport unordered_map +from libcpp.utility cimport pair +from libcpp.vector cimport vector as c_vector + +from ray.includes.unique_ids cimport ( + CActorID, + CClusterID, + CNodeID, + CJobID, + CTaskID, + CObjectID, + CPlacementGroupID, + CWorkerID, + ObjectIDIndexType, +) + +from ray.includes.common cimport ( + CAddress, + CObjectReference, + CActorCreationOptions, + CBuffer, + CPlacementGroupCreationOptions, + CObjectLocation, + CObjectReference, + CRayFunction, + CRayObject, + CRayStatus, + CTaskArg, + CTaskOptions, + CTaskType, + CWorkerType, + CLanguage, + CGcsClientOptions, + LocalMemoryBuffer, + CJobConfig, + CConcurrencyGroup, + CSchedulingStrategy, + CWorkerExitType, + CLineageReconstructionTask, + CTensorTransport, +) +from ray.includes.function_descriptor cimport ( + CFunctionDescriptor, +) + +from ray.includes.optional cimport ( + optional, +) + +ctypedef unordered_map[c_string, c_vector[pair[int64_t, double]]] \ + ResourceMappingType + +ctypedef void (*ray_callback_function) \ + (shared_ptr[CRayObject] result_object, + CObjectID object_id, void* user_data) + +ctypedef void (*plasma_callback_function) \ + (CObjectID object_id, int64_t data_size, int64_t metadata_size) + +# NOTE: This ctypedef is needed, because Cython doesn't compile +# "pair[shared_ptr[const CActorHandle], CRayStatus]". +# This is a bug of cython: https://github.com/cython/cython/issues/3967. +ctypedef shared_ptr[const CActorHandle] ActorHandleSharedPtr + +cdef extern from "ray/core_worker/profile_event.h" nogil: + cdef cppclass CProfileEvent "ray::core::worker::ProfileEvent": + void SetExtraData(const c_string &extra_data) + +cdef extern from "ray/core_worker/fiber.h" nogil: + cdef cppclass CFiberEvent "ray::core::FiberEvent": + CFiberEvent() + void Wait() + void Notify() + +cdef extern from "ray/core_worker/experimental_mutable_object_manager.h" nogil: + cdef cppclass CReaderRefInfo "ray::experimental::ReaderRefInfo": + CReaderRefInfo() + CObjectID reader_ref_id + CActorID owner_reader_actor_id + int64_t num_reader_actors + + +cdef extern from "ray/core_worker/context.h" nogil: + cdef cppclass CWorkerContext "ray::core::WorkerContext": + c_bool CurrentActorIsAsync() + void SetCurrentActorShouldExit() + c_bool GetCurrentActorShouldExit() + const c_string &GetCurrentSerializedRuntimeEnv() + int CurrentActorMaxConcurrency() + CActorID GetRootDetachedActorID() + +cdef extern from "ray/core_worker/generator_waiter.h" nogil: + cdef cppclass CGeneratorBackpressureWaiter "ray::core::GeneratorBackpressureWaiter": # noqa + CGeneratorBackpressureWaiter( + int64_t generator_backpressure_num_objects, + (CRayStatus() nogil) check_signals) + CRayStatus WaitAllObjectsReported() + +cdef extern from "ray/core_worker/core_worker.h" nogil: + cdef cppclass CActorHandle "ray::core::ActorHandle": + CActorID GetActorID() const + CJobID CreationJobID() const + CLanguage ActorLanguage() const + CFunctionDescriptor ActorCreationTaskFunctionDescriptor() const + c_string ExtensionData() const + int MaxPendingCalls() const + int MaxTaskRetries() const + c_bool EnableTaskEvents() const + + cdef cppclass CCoreWorker "ray::core::CoreWorker": + CWorkerType GetWorkerType() + CLanguage GetLanguage() + + c_vector[CObjectReference] SubmitTask( + const CRayFunction &function, + const c_vector[unique_ptr[CTaskArg]] &args, + const CTaskOptions &options, + int max_retries, + c_bool retry_exceptions, + const CSchedulingStrategy &scheduling_strategy, + c_string debugger_breakpoint, + c_string serialized_retry_exception_allowlist, + c_string call_site, + const CTaskID current_task_id) + CRayStatus CreateActor( + const CRayFunction &function, + const c_vector[unique_ptr[CTaskArg]] &args, + const CActorCreationOptions &options, + const c_string &extension_data, + c_string call_site, + CActorID *actor_id) + CRayStatus CreatePlacementGroup( + const CPlacementGroupCreationOptions &options, + CPlacementGroupID *placement_group_id) + CRayStatus RemovePlacementGroup( + const CPlacementGroupID &placement_group_id) + CRayStatus WaitPlacementGroupReady( + const CPlacementGroupID &placement_group_id, int64_t timeout_seconds) + CRayStatus SubmitActorTask( + const CActorID &actor_id, const CRayFunction &function, + const c_vector[unique_ptr[CTaskArg]] &args, + const CTaskOptions &options, + int max_retries, + c_bool retry_exceptions, + c_string serialized_retry_exception_allowlist, + c_string call_site, + c_vector[CObjectReference] &task_returns, + const CTaskID current_task_id) + CRayStatus KillActor( + const CActorID &actor_id, c_bool force_kill, + c_bool no_restart) + CRayStatus CancelTask(const CObjectID &object_id, c_bool force_kill, + c_bool recursive) + + unique_ptr[CProfileEvent] CreateProfileEvent( + const c_string &event_type) + CRayStatus AllocateReturnObject( + const CObjectID &object_id, + const size_t &data_size, + const shared_ptr[CBuffer] &metadata, + const c_vector[CObjectID] &contained_object_id, + const CAddress &caller_address, + int64_t *task_output_inlined_bytes, + shared_ptr[CRayObject] *return_object) + CRayStatus SealReturnObject( + const CObjectID &return_id, + const shared_ptr[CRayObject] &return_object, + const CObjectID &generator_id, + const CAddress &caller_address + ) + c_bool PinExistingReturnObject( + const CObjectID &return_id, + shared_ptr[CRayObject] *return_object, + const CObjectID &generator_id, + const CAddress &caller_address) + void AsyncDelObjectRefStream(const CObjectID &generator_id) + CRayStatus TryReadObjectRefStream( + const CObjectID &generator_id, + CObjectReference *object_ref_out) + c_bool StreamingGeneratorIsFinished(const CObjectID &generator_id) const + pair[CObjectReference, c_bool] PeekObjectRefStream( + const CObjectID &generator_id) + CObjectID AllocateDynamicReturnId( + const CAddress &owner_address, + const CTaskID &task_id, + optional[ObjectIDIndexType] put_index) + + CJobID GetCurrentJobId() + CTaskID GetCurrentTaskId() + const c_string GetCurrentTaskName() + const c_string GetCurrentTaskFunctionName() + void UpdateTaskIsDebuggerPaused( + const CTaskID &task_id, + const c_bool is_debugger_paused) + int64_t GetCurrentTaskAttemptNumber() + CNodeID GetCurrentNodeId() + int64_t GetTaskDepth() + c_bool GetCurrentTaskRetryExceptions() + CPlacementGroupID GetCurrentPlacementGroupId() const + CWorkerID GetWorkerID() + c_bool ShouldCaptureChildTasksInPlacementGroup() + CActorID GetActorId() const + const c_string GetActorName() + void SetActorTitle(const c_string &title) + void SetActorReprName(const c_string &repr_name) + void SetWebuiDisplay(const c_string &key, const c_string &message) + const ResourceMappingType &GetResourceIDs() const + void RemoveActorHandleReference(const CActorID &actor_id) + optional[int] GetLocalActorState(const CActorID &actor_id) const + CActorID DeserializeAndRegisterActorHandle(const c_string &bytes, const + CObjectID &outer_object_id, + c_bool add_local_ref) + CRayStatus SerializeActorHandle(const CActorID &actor_id, c_string + *bytes, + CObjectID *c_actor_handle_id) + ActorHandleSharedPtr GetActorHandle(const CActorID &actor_id) const + pair[ActorHandleSharedPtr, CRayStatus] GetNamedActorHandle( + const c_string &name, const c_string &ray_namespace) + pair[c_vector[c_pair[c_string, c_string]], CRayStatus] ListNamedActors( + c_bool all_namespaces) + void AddLocalReference(const CObjectID &object_id) + void RemoveLocalReference(const CObjectID &object_id) + void PutObjectIntoPlasma(const CRayObject &object, + const CObjectID &object_id) + const CAddress &GetRpcAddress() const + CRayStatus GetOwnerAddress(const CObjectID &object_id, + CAddress *owner_address) const + c_vector[CObjectReference] GetObjectRefs( + const c_vector[CObjectID] &object_ids) const + + CRayStatus GetOwnershipInfo(const CObjectID &object_id, + CAddress *owner_address, + c_string *object_status) + void RegisterOwnershipInfoAndResolveFuture( + const CObjectID &object_id, + const CObjectID &outer_object_id, + const CAddress &owner_address, + const c_string &object_status) + + CRayStatus Put(const CRayObject &object, + const c_vector[CObjectID] &contained_object_ids, + CObjectID *object_id) + CRayStatus Put(const CRayObject &object, + const c_vector[CObjectID] &contained_object_ids, + const CObjectID &object_id) + CRayStatus CreateOwnedAndIncrementLocalRef( + c_bool is_mutable, + const shared_ptr[CBuffer] &metadata, + const size_t data_size, + const c_vector[CObjectID] &contained_object_ids, + CObjectID *object_id, shared_ptr[CBuffer] *data, + c_bool created_by_worker, + const unique_ptr[CAddress] &owner_address, + c_bool inline_small_object) + CRayStatus CreateExisting(const shared_ptr[CBuffer] &metadata, + const size_t data_size, + const CObjectID &object_id, + const CAddress &owner_address, + shared_ptr[CBuffer] *data, + c_bool created_by_worker) + CRayStatus ExperimentalChannelWriteAcquire( + const CObjectID &object_id, + const shared_ptr[CBuffer] &metadata, + uint64_t data_size, + int64_t num_readers, + int64_t timeout_ms, + shared_ptr[CBuffer] *data) + CRayStatus ExperimentalChannelWriteRelease( + const CObjectID &object_id) + CRayStatus ExperimentalChannelSetError( + const CObjectID &object_id) + CRayStatus ExperimentalRegisterMutableObjectWriter( + const CObjectID &writer_object_id, + const c_vector[CNodeID] &remote_reader_node_ids) + CRayStatus ExperimentalRegisterMutableObjectReader(const CObjectID &object_id) + CRayStatus ExperimentalRegisterMutableObjectReaderRemote( + const CObjectID &object_id, + const c_vector[CReaderRefInfo] &remote_reader_ref_info) + CRayStatus SealOwned(const CObjectID &object_id, c_bool pin_object, + const unique_ptr[CAddress] &owner_address) + CRayStatus SealExisting(const CObjectID &object_id, c_bool pin_object, + const CObjectID &generator_id, + const unique_ptr[CAddress] &owner_address) + CRayStatus Get(const c_vector[CObjectID] &ids, int64_t timeout_ms, + c_vector[shared_ptr[CRayObject]] results) + CRayStatus GetIfLocal( + const c_vector[CObjectID] &ids, + c_vector[shared_ptr[CRayObject]] *results) + CRayStatus Contains(const CObjectID &object_id, c_bool *has_object, + c_bool *is_in_plasma) + CRayStatus Wait(const c_vector[CObjectID] &object_ids, int num_objects, + int64_t timeout_ms, c_vector[c_bool] *results, + c_bool fetch_local) + CRayStatus Delete(const c_vector[CObjectID] &object_ids, + c_bool local_only) + CRayStatus GetLocalObjectLocations( + const c_vector[CObjectID] &object_ids, + c_vector[optional[CObjectLocation]] *results) + CRayStatus GetLocationFromOwner( + const c_vector[CObjectID] &object_ids, + int64_t timeout_ms, + c_vector[shared_ptr[CObjectLocation]] *results) + CRayStatus TriggerGlobalGC() + CRayStatus ReportGeneratorItemReturns( + const pair[CObjectID, shared_ptr[CRayObject]] &dynamic_return_object, + const CObjectID &generator_id, + const CAddress &caller_address, + int64_t item_index, + uint64_t attempt_number, + shared_ptr[CGeneratorBackpressureWaiter] waiter) + c_string MemoryUsageString() + int GetMemoryStoreSize() + + CWorkerContext &GetWorkerContext() + void YieldCurrentFiber(CFiberEvent &coroutine_done) + + unordered_map[CObjectID, pair[size_t, size_t]] GetAllReferenceCounts() + c_vector[CTaskID] GetPendingChildrenTasks(const CTaskID &task_id) const + + void GetAsync(const CObjectID &object_id, + ray_callback_function success_callback, + void* python_user_callback) + + CRayStatus PushError(const CJobID &job_id, const c_string &type, + const c_string &error_message, double timestamp) + CRayStatus SetResource(const c_string &resource_name, + const double capacity, + const CNodeID &client_Id) + + CJobConfig GetJobConfig() + + int64_t GetNumTasksSubmitted() const + + int64_t GetNumLeasesRequested() const + + int64_t GetLocalMemoryStoreBytesUsed() const + + void RecordTaskLogStart( + const CTaskID &task_id, + int attempt_number, + const c_string& stdout_path, + const c_string& stderr_path, + int64_t stdout_start_offset, + int64_t stderr_start_offset) const + + void RecordTaskLogEnd( + const CTaskID &task_id, + int attempt_number, + int64_t stdout_end_offset, + int64_t stderr_end_offset) const + + void Exit(const CWorkerExitType exit_type, + const c_string &detail, + const shared_ptr[LocalMemoryBuffer] &creation_task_exception_pb_bytes) + + unordered_map[CLineageReconstructionTask, uint64_t] \ + GetLocalOngoingLineageReconstructionTasks() const + + cdef cppclass CCoreWorkerOptions "ray::core::CoreWorkerOptions": + CWorkerType worker_type + CLanguage language + c_string store_socket + c_string raylet_socket + CJobID job_id + CGcsClientOptions gcs_options + c_bool enable_logging + c_string log_dir + c_bool install_failure_signal_handler + c_bool interactive + c_string node_ip_address + int node_manager_port + c_string raylet_ip_address + c_string driver_name + (CRayStatus( + const CAddress &caller_address, + CTaskType task_type, + const c_string name, + const CRayFunction &ray_function, + const unordered_map[c_string, double] &resources, + const c_vector[shared_ptr[CRayObject]] &args, + const c_vector[CObjectReference] &arg_refs, + const c_string debugger_breakpoint, + const c_string serialized_retry_exception_allowlist, + c_vector[c_pair[CObjectID, shared_ptr[CRayObject]]] *returns, + c_vector[c_pair[CObjectID, shared_ptr[CRayObject]]] *dynamic_returns, + c_vector[c_pair[CObjectID, c_bool]] *streaming_generator_returns, + shared_ptr[LocalMemoryBuffer] + &creation_task_exception_pb_bytes, + c_bool *is_retryable_error, + c_string *application_error, + const c_vector[CConcurrencyGroup] &defined_concurrency_groups, + const c_string name_of_concurrency_group_to_execute, + c_bool is_reattempt, + c_bool is_streaming_generator, + c_bool should_retry_exceptions, + int64_t generator_backpressure_num_objects, + CTensorTransport tensor_transport + ) nogil) task_execution_callback + (function[void()]() nogil) initialize_thread_callback + (CRayStatus() nogil) check_signals + (void(c_bool) nogil) gc_collect + (c_vector[c_string]( + const c_vector[CObjectReference] &) nogil) spill_objects + (int64_t( + const c_vector[CObjectReference] &, + const c_vector[c_string] &) nogil) restore_spilled_objects + (void( + const c_vector[c_string]&, + CWorkerType) nogil) delete_spilled_objects + (void( + const c_string&, + const c_vector[c_string]&) nogil) run_on_util_worker_handler + (void(const CRayObject&) nogil) unhandled_exception_handler + (c_bool(const CTaskID &c_task_id) nogil) cancel_async_actor_task + (void(c_string *stack_out) nogil) get_lang_stack + c_bool is_local_mode + int num_workers + (c_bool(const CTaskID &) nogil) kill_main + CCoreWorkerOptions() + (void() nogil) terminate_asyncio_thread + c_string serialized_job_config + int metrics_agent_port + int runtime_env_hash + int startup_token + CClusterID cluster_id + c_string session_name + c_string entrypoint + int64_t worker_launch_time_ms + int64_t worker_launched_time_ms + c_string debug_source + c_bool enable_resource_isolation + + cdef cppclass CCoreWorkerProcess "ray::core::CoreWorkerProcess": + @staticmethod + void Initialize(const CCoreWorkerOptions &options) + # Only call this in CoreWorker.__cinit__, + # use CoreWorker.core_worker to access C++ CoreWorker. + + @staticmethod + CCoreWorker &GetCoreWorker() + + @staticmethod + void Shutdown() + + @staticmethod + void RunTaskExecutionLoop() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/metric.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/metric.pxd new file mode 100644 index 0000000000000000000000000000000000000000..32c05aea215160c93cc0f2ef3cdbcf7c6c174d8d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/metric.pxd @@ -0,0 +1,45 @@ +from libcpp.string cimport string as c_string +from libcpp.unordered_map cimport unordered_map +from libcpp.vector cimport vector as c_vector + +cdef extern from "opencensus/tags/tag_key.h" nogil: + cdef cppclass CTagKey "opencensus::tags::TagKey": + @staticmethod + CTagKey Register(c_string &name) + const c_string &name() const + +cdef extern from "ray/stats/metric.h" nogil: + cdef cppclass CMetric "ray::stats::Metric": + CMetric(const c_string &name, + const c_string &description, + const c_string &unit, + const c_vector[c_string] &tag_keys) + c_string GetName() const + void Record(double value) + void Record(double value, + unordered_map[c_string, c_string] &tags) + + cdef cppclass CGauge "ray::stats::Gauge": + CGauge(const c_string &name, + const c_string &description, + const c_string &unit, + const c_vector[c_string] &tag_keys) + + cdef cppclass CCount "ray::stats::Count": + CCount(const c_string &name, + const c_string &description, + const c_string &unit, + const c_vector[c_string] &tag_keys) + + cdef cppclass CSum "ray::stats::Sum": + CSum(const c_string &name, + const c_string &description, + const c_string &unit, + const c_vector[c_string] &tag_keys) + + cdef cppclass CHistogram "ray::stats::Histogram": + CHistogram(const c_string &name, + const c_string &description, + const c_string &unit, + const c_vector[double] &boundaries, + const c_vector[c_string] &tag_keys) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/optional.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/optional.pxd new file mode 100644 index 0000000000000000000000000000000000000000..a3539824ae73a16df48b1203fbf8b877d00fad42 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/optional.pxd @@ -0,0 +1,36 @@ +# Currently Cython does not support std::optional. +# See: https://github.com/cython/cython/pull/3294 +from libcpp cimport bool + +cdef extern from "" namespace "std" nogil: + cdef cppclass nullopt_t: + nullopt_t() + + cdef nullopt_t nullopt + + cdef cppclass optional[T]: + ctypedef T value_type + optional() + optional(nullopt_t) + optional(optional&) except + + optional(T&) except + + bool has_value() + T& value() + T& value_or[U](U& default_value) + void swap(optional&) + void reset() + T& emplace(...) + T& operator*() + # T* operator->() # Not Supported + optional& operator=(optional&) + optional& operator=[U](U&) + bool operator bool() + bool operator!() + bool operator==[U](optional&, U&) + bool operator!=[U](optional&, U&) + bool operator<[U](optional&, U&) + bool operator>[U](optional&, U&) + bool operator<=[U](optional&, U&) + bool operator>=[U](optional&, U&) + + optional[T] make_optional[T](...) except + diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/ray_config.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/ray_config.pxd new file mode 100644 index 0000000000000000000000000000000000000000..7189c2b5bd14e3648c6748433ac71191f2629d8e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/ray_config.pxd @@ -0,0 +1,98 @@ +from libcpp cimport bool as c_bool +from libc.stdint cimport int64_t, uint64_t, uint32_t +from libcpp.string cimport string as c_string +from libcpp.unordered_map cimport unordered_map + + +cdef extern from "ray/common/ray_config.h" nogil: + cdef cppclass RayConfig "RayConfig": + @staticmethod + RayConfig &instance() + + void initialize(const c_string& config_list) + + int64_t ray_cookie() const + + int64_t handler_warning_timeout_ms() const + + int64_t debug_dump_period_milliseconds() const + + int64_t object_timeout_milliseconds() const + + int64_t raylet_client_num_connect_attempts() const + + int64_t raylet_client_connect_timeout_milliseconds() const + + int64_t raylet_fetch_timeout_milliseconds() const + + int64_t kill_worker_timeout_milliseconds() const + + int64_t worker_register_timeout_seconds() const + + int64_t redis_db_connect_retries() + + int64_t redis_db_connect_wait_milliseconds() const + + int object_manager_pull_timeout_ms() const + + int object_manager_push_timeout_ms() const + + uint64_t object_manager_default_chunk_size() const + + uint32_t maximum_gcs_deletion_batch_size() const + + int64_t max_direct_call_object_size() const + + int64_t task_rpc_inlined_bytes_limit() const + + uint64_t metrics_report_interval_ms() const + + c_bool enable_timeline() const + + uint32_t max_grpc_message_size() const + + c_bool record_ref_creation_sites() const + + c_string REDIS_CA_CERT() const + + c_string REDIS_CA_PATH() const + + c_string REDIS_CLIENT_CERT() const + + c_string REDIS_CLIENT_KEY() const + + c_string REDIS_SERVER_NAME() const + + int64_t health_check_initial_delay_ms() const + + int64_t health_check_period_ms() const + + int64_t health_check_timeout_ms() const + + int64_t health_check_failure_threshold() const + + uint64_t memory_monitor_refresh_ms() const + + int64_t grpc_keepalive_time_ms() const + + int64_t grpc_keepalive_timeout_ms() const + + int64_t grpc_client_keepalive_time_ms() const + + int64_t grpc_client_keepalive_timeout_ms() const + + c_bool enable_autoscaler_v2() const + + c_string predefined_unit_instance_resources() const + + c_string custom_unit_instance_resources() const + + int64_t nums_py_gcs_reconnect_retry() const + + int64_t py_gcs_connect_timeout_s() const + + int gcs_rpc_server_reconnect_timeout_s() const + + int maximum_gcs_destroyed_actor_cached_count() const + + c_bool record_task_actor_creation_sites() const diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/setproctitle.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/setproctitle.pxd new file mode 100644 index 0000000000000000000000000000000000000000..788b4a6265fa1a928a373c4e457fe2ec8ad02178 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/setproctitle.pxd @@ -0,0 +1,17 @@ +from libcpp.string cimport string as c_string + +cdef extern from *: + """ + extern "C" { + #include "ray/thirdparty/setproctitle/spt_setup.h" + } + """ + int spt_setup() + +cdef extern from *: + """ + extern "C" { + #include "ray/thirdparty/setproctitle/spt_status.h" + } + """ + void set_ps_display(const char *activity, bint force) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/stream_redirection.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/stream_redirection.pxd new file mode 100644 index 0000000000000000000000000000000000000000..29b7b0c2c55cabf95652020dc833a44b213bd611 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/stream_redirection.pxd @@ -0,0 +1,16 @@ +from libcpp.string cimport string as c_string +from libc.stdint cimport uint64_t +from libcpp cimport bool as c_bool + +cdef extern from "ray/util/stream_redirection_options.h" nogil: + cdef cppclass CStreamRedirectionOptions "ray::StreamRedirectionOption": + CStreamRedirectionOptions() + c_string file_path + uint64_t rotation_max_size + uint64_t rotation_max_file_count + c_bool tee_to_stdout + c_bool tee_to_stderr + +cdef extern from "ray/util/stream_redirection.h" namespace "ray" nogil: + void RedirectStdoutOncePerProcess(const CStreamRedirectionOptions& opt) + void RedirectStderrOncePerProcess(const CStreamRedirectionOptions& opt) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/unique_ids.pxd b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/unique_ids.pxd new file mode 100644 index 0000000000000000000000000000000000000000..fe93a83675b266d7cb4ed57677094d6e43f49a60 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/includes/unique_ids.pxd @@ -0,0 +1,191 @@ +from libcpp cimport bool as c_bool +from libcpp.string cimport string as c_string +from libc.stdint cimport uint8_t, uint32_t, int64_t + +# Note: we removed the staticmethod declarations in +# https://github.com/ray-project/ray/pull/47984 due +# to a compiler bug in Cython 3.0.x -- we should see +# if we can bring them back in Cython 3.1.x if the +# bug is fixed. +cdef extern from "ray/common/id.h" namespace "ray" nogil: + cdef cppclass CBaseID[T]: + size_t Hash() const + c_bool IsNil() const + c_bool operator==(const CBaseID &rhs) const + c_bool operator!=(const CBaseID &rhs) const + const uint8_t *data() const + + c_string Binary() const + c_string Hex() const + + cdef cppclass CUniqueID "ray::UniqueID"(CBaseID[CUniqueID]): + CUniqueID() + + @staticmethod + size_t Size() + + @staticmethod + CUniqueID FromRandom() + + @staticmethod + CUniqueID FromBinary(const c_string &binary) + + @staticmethod + const CUniqueID Nil() + + cdef cppclass CActorClassID "ray::ActorClassID"(CBaseID[CActorClassID]): + + @staticmethod + CActorClassID FromHex(const c_string &hex_str) + + cdef cppclass CActorID "ray::ActorID"(CBaseID[CActorID]): + + @staticmethod + CActorID FromBinary(const c_string &binary) + + @staticmethod + CActorID FromHex(const c_string &hex_str) + + @staticmethod + const CActorID Nil() + + @staticmethod + size_t Size() + + @staticmethod + CActorID Of(CJobID job_id, CTaskID parent_task_id, + int64_t parent_task_counter) + + CJobID JobId() + + cdef cppclass CNodeID "ray::NodeID"(CBaseID[CNodeID]): + + @staticmethod + CNodeID FromHex(const c_string &hex_str) + + @staticmethod + const CNodeID Nil() + + cdef cppclass CConfigID "ray::ConfigID"(CBaseID[CConfigID]): + pass + + cdef cppclass CFunctionID "ray::FunctionID"(CBaseID[CFunctionID]): + + @staticmethod + CFunctionID FromHex(const c_string &hex_str) + + cdef cppclass CJobID "ray::JobID"(CBaseID[CJobID]): + + @staticmethod + CJobID FromBinary(const c_string &binary) + + @staticmethod + CJobID FromHex(const c_string &hex_str) + + @staticmethod + const CJobID Nil() + + @staticmethod + size_t Size() + + @staticmethod + CJobID FromInt(uint32_t value) + + uint32_t ToInt() + + cdef cppclass CTaskID "ray::TaskID"(CBaseID[CTaskID]): + + @staticmethod + CTaskID FromBinary(const c_string &binary) + + @staticmethod + CTaskID FromHex(const c_string &hex_str) + + @staticmethod + const CTaskID Nil() + + @staticmethod + size_t Size() + + @staticmethod + CTaskID ForDriverTask(const CJobID &job_id) + + @staticmethod + CTaskID FromRandom(const CJobID &job_id) + + @staticmethod + CTaskID ForActorCreationTask(CActorID actor_id) + + @staticmethod + CTaskID ForActorTask(CJobID job_id, CTaskID parent_task_id, + int64_t parent_task_counter, CActorID actor_id) + + @staticmethod + CTaskID ForNormalTask(CJobID job_id, CTaskID parent_task_id, + int64_t parent_task_counter) + + CActorID ActorId() const + + CJobID JobId() const + + cdef cppclass CObjectID" ray::ObjectID"(CBaseID[CObjectID]): + + @staticmethod + int64_t MaxObjectIndex() + + @staticmethod + CObjectID FromBinary(const c_string &binary) + + @staticmethod + CObjectID FromRandom() + + @staticmethod + const CObjectID Nil() + + @staticmethod + CObjectID FromIndex(const CTaskID &task_id, int64_t index) + + @staticmethod + size_t Size() + + c_bool is_put() + + int64_t ObjectIndex() const + + CTaskID TaskId() const + + cdef cppclass CClusterID "ray::ClusterID"(CBaseID[CClusterID]): + + @staticmethod + CClusterID FromHex(const c_string &hex_str) + + @staticmethod + CClusterID FromRandom() + + @staticmethod + const CClusterID Nil() + + cdef cppclass CWorkerID "ray::WorkerID"(CBaseID[CWorkerID]): + + @staticmethod + CWorkerID FromHex(const c_string &hex_str) + + cdef cppclass CPlacementGroupID "ray::PlacementGroupID" \ + (CBaseID[CPlacementGroupID]): + + @staticmethod + CPlacementGroupID FromBinary(const c_string &binary) + + @staticmethod + CPlacementGroupID FromHex(const c_string &hex_str) + + @staticmethod + const CPlacementGroupID Nil() + + @staticmethod + size_t Size() + + @staticmethod + CPlacementGroupID Of(CJobID job_id) + + ctypedef uint32_t ObjectIDIndexType diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/internal/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/internal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..36740dd1870a1e010cad2f438bb89ab1a0353047 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/internal/__init__.py @@ -0,0 +1,3 @@ +from ray._private.internal_api import free + +__all__ = ["free"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/jars/ray_dist.jar b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/jars/ray_dist.jar new file mode 100644 index 0000000000000000000000000000000000000000..a0f696d8c5b784e5bfb6c8698a00fb78bcb63c20 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/jars/ray_dist.jar @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3d7afc7162b6c02e81fe4ce474242d44df992e73387898fde3c59b01e6bbaea6 +size 32923253 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/job_submission/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/job_submission/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6a86cf73c329063ce3f730af66073ce3b5da1123 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/job_submission/__init__.py @@ -0,0 +1,12 @@ +from ray.dashboard.modules.job.common import JobInfo, JobStatus +from ray.dashboard.modules.job.pydantic_models import DriverInfo, JobDetails, JobType +from ray.dashboard.modules.job.sdk import JobSubmissionClient + +__all__ = [ + "JobSubmissionClient", + "JobStatus", + "JobInfo", + "JobDetails", + "DriverInfo", + "JobType", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/llm/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/llm/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f63b8173d43382c546dd1aaa1d09c316bd3ba846 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/__init__.py @@ -0,0 +1,55 @@ +import logging + +from ray._private.usage import usage_lib + +# Note: do not introduce unnecessary library dependencies here, e.g. gym. +# This file is imported from the tune module in order to register RLlib agents. +from ray.rllib.env.base_env import BaseEnv +from ray.rllib.env.external_env import ExternalEnv +from ray.rllib.env.multi_agent_env import MultiAgentEnv +from ray.rllib.env.vector_env import VectorEnv +from ray.rllib.evaluation.rollout_worker import RolloutWorker +from ray.rllib.policy.policy import Policy +from ray.rllib.policy.sample_batch import SampleBatch +from ray.rllib.policy.tf_policy import TFPolicy +from ray.rllib.policy.torch_policy import TorchPolicy +from ray.tune.registry import register_trainable + + +def _setup_logger(): + logger = logging.getLogger("ray.rllib") + handler = logging.StreamHandler() + handler.setFormatter( + logging.Formatter( + "%(asctime)s\t%(levelname)s %(filename)s:%(lineno)s -- %(message)s" + ) + ) + logger.addHandler(handler) + logger.propagate = False + + +def _register_all(): + from ray.rllib.algorithms.registry import ALGORITHMS, _get_algorithm_class + + for key, get_trainable_class_and_config in ALGORITHMS.items(): + register_trainable(key, get_trainable_class_and_config()[0]) + + for key in ["__fake", "__sigmoid_fake_data", "__parameter_tuning"]: + register_trainable(key, _get_algorithm_class(key)) + + +_setup_logger() + +usage_lib.record_library_usage("rllib") + +__all__ = [ + "Policy", + "TFPolicy", + "TorchPolicy", + "RolloutWorker", + "SampleBatch", + "BaseEnv", + "MultiAgentEnv", + "VectorEnv", + "ExternalEnv", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afa43c84798eeaa48540f91d07da87269483c0a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f9e711682a3224df3644ba9f821f1ab3869fdaa3e1799eb44357e6828ef91882 +size 167968 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51fe2b0f25fdd900c62a42a28cb70275d43005fd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/algorithms/__pycache__/algorithm_config.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffc3701b823c2a12371defa4e78856b1f8f653c294170fe0189b89e4daf5cc35 +size 259294 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36d493937faba87b9f8c68a91248ccfed0c7d5e0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/rllib/env/__pycache__/multi_agent_episode.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb603f30b358771a01b0b3ddd92a8bdf16f983588ce61816bc5959ecb7e30455 +size 105666 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/runtime_env/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/runtime_env/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f401770d0ef075b7c733116b2e7f5ce14f5825e0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/runtime_env/__init__.py @@ -0,0 +1,8 @@ +from ray._private.runtime_env.mpi import mpi_init # noqa: E402,F401 +from ray.runtime_env.runtime_env import RuntimeEnv, RuntimeEnvConfig # noqa: E402,F401 + +__all__ = [ + "RuntimeEnvConfig", + "RuntimeEnv", + "mpi_init", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/runtime_env/runtime_env.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/runtime_env/runtime_env.py new file mode 100644 index 0000000000000000000000000000000000000000..0682c48539fbb72237bcd9f42e0b39fd5325e9f7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/runtime_env/runtime_env.py @@ -0,0 +1,686 @@ +import json +import logging +import os +from copy import deepcopy +from dataclasses import asdict, is_dataclass +from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union + +import ray +from ray._private.ray_constants import DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS +from ray._private.runtime_env.conda import get_uri as get_conda_uri +from ray._private.runtime_env.default_impl import get_image_uri_plugin_cls +from ray._private.runtime_env.pip import get_uri as get_pip_uri +from ray._private.runtime_env.plugin_schema_manager import RuntimeEnvPluginSchemaManager +from ray._private.runtime_env.uv import get_uri as get_uv_uri +from ray._private.runtime_env.validation import ( + OPTION_TO_VALIDATION_FN, + OPTION_TO_NO_PATH_VALIDATION_FN, +) +from ray._private.thirdparty.dacite import from_dict +from ray.core.generated.runtime_env_common_pb2 import ( + RuntimeEnvConfig as ProtoRuntimeEnvConfig, +) +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="stable") +class RuntimeEnvConfig(dict): + """Used to specify configuration options for a runtime environment. + + The config is not included when calculating the runtime_env hash, + which means that two runtime_envs with the same options but different + configs are considered the same for caching purposes. + + Args: + setup_timeout_seconds: The timeout of runtime environment + creation, timeout is in seconds. The value `-1` means disable + timeout logic, except `-1`, `setup_timeout_seconds` cannot be + less than or equal to 0. The default value of `setup_timeout_seconds` + is 600 seconds. + eager_install: Indicates whether to install the runtime environment + on the cluster at `ray.init()` time, before the workers are leased. + This flag is set to `True` by default. + """ + + known_fields: Set[str] = {"setup_timeout_seconds", "eager_install", "log_files"} + + _default_config: Dict = { + "setup_timeout_seconds": DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS, + "eager_install": True, + "log_files": [], + } + + def __init__( + self, + setup_timeout_seconds: int = DEFAULT_RUNTIME_ENV_TIMEOUT_SECONDS, + eager_install: bool = True, + log_files: Optional[List[str]] = None, + ): + super().__init__() + if not isinstance(setup_timeout_seconds, int): + raise TypeError( + "setup_timeout_seconds must be of type int, " + f"got: {type(setup_timeout_seconds)}" + ) + elif setup_timeout_seconds <= 0 and setup_timeout_seconds != -1: + raise ValueError( + "setup_timeout_seconds must be greater than zero " + f"or equals to -1, got: {setup_timeout_seconds}" + ) + self["setup_timeout_seconds"] = setup_timeout_seconds + + if not isinstance(eager_install, bool): + raise TypeError( + f"eager_install must be a boolean. got {type(eager_install)}" + ) + self["eager_install"] = eager_install + + if log_files is not None: + if not isinstance(log_files, list): + raise TypeError( + "log_files must be a list of strings or None, got " + f"{log_files} with type {type(log_files)}." + ) + for file_name in log_files: + if not isinstance(file_name, str): + raise TypeError("Each item in log_files must be a string.") + else: + log_files = self._default_config["log_files"] + + self["log_files"] = log_files + + @staticmethod + def parse_and_validate_runtime_env_config( + config: Union[Dict, "RuntimeEnvConfig"] + ) -> "RuntimeEnvConfig": + if isinstance(config, RuntimeEnvConfig): + return config + elif isinstance(config, Dict): + unknown_fields = set(config.keys()) - RuntimeEnvConfig.known_fields + if len(unknown_fields): + logger.warning( + "The following unknown entries in the runtime_env_config " + f"dictionary will be ignored: {unknown_fields}." + ) + config_dict = dict() + for field in RuntimeEnvConfig.known_fields: + if field in config: + config_dict[field] = config[field] + return RuntimeEnvConfig(**config_dict) + else: + raise TypeError( + "runtime_env['config'] must be of type dict or RuntimeEnvConfig, " + f"got: {type(config)}" + ) + + @classmethod + def default_config(cls): + return RuntimeEnvConfig(**cls._default_config) + + def build_proto_runtime_env_config(self) -> ProtoRuntimeEnvConfig: + runtime_env_config = ProtoRuntimeEnvConfig() + runtime_env_config.setup_timeout_seconds = self["setup_timeout_seconds"] + runtime_env_config.eager_install = self["eager_install"] + if self["log_files"] is not None: + runtime_env_config.log_files.extend(self["log_files"]) + return runtime_env_config + + @classmethod + def from_proto(cls, runtime_env_config: ProtoRuntimeEnvConfig): + setup_timeout_seconds = runtime_env_config.setup_timeout_seconds + # Cause python class RuntimeEnvConfig has validate to avoid + # setup_timeout_seconds equals zero, so setup_timeout_seconds + # on RuntimeEnvConfig is zero means other Language(except python) + # dosn't assign value to setup_timeout_seconds. So runtime_env_agent + # assign the default value to setup_timeout_seconds. + if setup_timeout_seconds == 0: + setup_timeout_seconds = cls._default_config["setup_timeout_seconds"] + return cls( + setup_timeout_seconds=setup_timeout_seconds, + eager_install=runtime_env_config.eager_install, + log_files=list(runtime_env_config.log_files), + ) + + def to_dict(self) -> Dict: + return dict(deepcopy(self)) + + +# Due to circular reference, field config can only be assigned a value here +OPTION_TO_VALIDATION_FN[ + "config" +] = RuntimeEnvConfig.parse_and_validate_runtime_env_config + + +@PublicAPI +class RuntimeEnv(dict): + """This class is used to define a runtime environment for a job, task, + or actor. + + See :ref:`runtime-environments` for detailed documentation. + + This class can be used interchangeably with an unstructured dictionary + in the relevant API calls. + + Can specify a runtime environment whole job, whether running a script + directly on the cluster, using Ray Job submission, or using Ray Client: + + .. code-block:: python + + from ray.runtime_env import RuntimeEnv + # Starting a single-node local Ray cluster + ray.init(runtime_env=RuntimeEnv(...)) + + .. code-block:: python + + from ray.runtime_env import RuntimeEnv + # Connecting to remote cluster using Ray Client + ray.init("ray://123.456.7.89:10001", runtime_env=RuntimeEnv(...)) + + Can specify different runtime environments per-actor or per-task using + ``.options()`` or the ``@ray.remote`` decorator: + + .. code-block:: python + + from ray.runtime_env import RuntimeEnv + # Invoke a remote task that runs in a specified runtime environment. + f.options(runtime_env=RuntimeEnv(...)).remote() + + # Instantiate an actor that runs in a specified runtime environment. + actor = SomeClass.options(runtime_env=RuntimeEnv(...)).remote() + + # Specify a runtime environment in the task definition. Future invocations via + # `g.remote()` use this runtime environment unless overridden by using + # `.options()` as above. + @ray.remote(runtime_env=RuntimeEnv(...)) + def g(): + pass + + # Specify a runtime environment in the actor definition. Future instantiations + # via `MyClass.remote()` use this runtime environment unless overridden by + # using `.options()` as above. + @ray.remote(runtime_env=RuntimeEnv(...)) + class MyClass: + pass + + Here are some examples of RuntimeEnv initialization: + + .. code-block:: python + + # Example for using conda + RuntimeEnv(conda={ + "channels": ["defaults"], "dependencies": ["codecov"]}) + RuntimeEnv(conda="pytorch_p36") # Found on DLAMIs + + # Example for using container + RuntimeEnv( + container={"image": "anyscale/ray-ml:nightly-py38-cpu", + "run_options": ["--cap-drop SYS_ADMIN","--log-level=debug"]}) + + # Example for set env_vars + RuntimeEnv(env_vars={"OMP_NUM_THREADS": "32", "TF_WARNINGS": "none"}) + + # Example for set pip + RuntimeEnv( + pip={"packages":["tensorflow", "requests"], "pip_check": False, + "pip_version": "==22.0.2;python_version=='3.8.11'"}) + + # Example for using image_uri + RuntimeEnv( + image_uri="rayproject/ray:2.39.0-py312-cu123") + + Args: + py_modules: List of local paths or remote URIs (either in the GCS or external + storage), each of which is a zip file that Ray unpacks and + inserts into the PYTHONPATH of the workers. + working_dir: Local path or remote URI (either in the GCS or external storage) of a zip + file that Ray unpacks in the directory of each task/actor. + pip: Either a list of pip packages, a string + containing the path to a pip requirements.txt file, or a Python + dictionary that has three fields: 1) ``packages`` (required, List[str]): a + list of pip packages, 2) ``pip_check`` (optional, bool): whether enable + pip check at the end of pip install, defaults to False. + 3) ``pip_version`` (optional, str): the version of pip, Ray prepends + the package name "pip" in front of the ``pip_version`` to form the final + requirement string, the syntax of a requirement specifier is defined in + full in PEP 508. + uv: Either a list of pip packages, or a Python dictionary that has one field: + 1) ``packages`` (required, List[str]). + conda: Either the conda YAML config, the name of a + local conda env (e.g., "pytorch_p36"), or the path to a conda + environment.yaml file. + Ray automatically injects the dependency into the conda + env to ensure compatibility with the cluster Ray. Ray may automatically + mangle the conda name to avoid conflicts between runtime envs. + This field can't be specified at the same time as the 'pip' field. + To use pip with conda, specify your pip dependencies within + the conda YAML config: + https://conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html#create-env-file-manually + container: Require a given (Docker) container image, + The Ray worker process runs in a container with this image. + This parameter only works alone, or with the ``config`` or + ``env_vars`` parameters. + The `run_options` list spec is here: + https://docs.docker.com/engine/reference/run/ + env_vars: Environment variables to set. + worker_process_setup_hook: (Experimental) The setup hook that's + called after workers start and before Tasks and Actors are scheduled. + A module name (string type) or callable (function) can be passed. + When a module name is passed, Ray worker should be able to access the + module name. When a callable is passed, callable should be serializable. + When a runtime env is specified by job submission API, + only a module name (string) is allowed. + nsight: Dictionary mapping nsight profile option name to it's value. + rocprof_sys: Dictionary mapping rocprof-sys profile option name and environment + variables to it's value. + config: config for runtime environment. Either + a dict or a RuntimeEnvConfig. Field: (1) setup_timeout_seconds, the + timeout of runtime environment creation, timeout is in seconds. + image_uri: URI to a container image. The Ray worker process runs + in a container with this image. This parameter only works alone, + or with the ``config`` or ``env_vars`` parameters. + """ + + known_fields: Set[str] = { + "py_modules", + "py_executable", + "java_jars", + "working_dir", + "conda", + "pip", + "uv", + "container", + "excludes", + "env_vars", + "_ray_release", + "_ray_commit", + "_inject_current_ray", + "config", + "worker_process_setup_hook", + "_nsight", + "_rocprof_sys", + "mpi", + "image_uri", + } + + extensions_fields: Set[str] = { + "_ray_release", + "_ray_commit", + "_inject_current_ray", + } + + def __init__( + self, + *, + py_modules: Optional[List[str]] = None, + py_executable: Optional[str] = None, + working_dir: Optional[str] = None, + pip: Optional[List[str]] = None, + conda: Optional[Union[Dict[str, str], str]] = None, + container: Optional[Dict[str, str]] = None, + env_vars: Optional[Dict[str, str]] = None, + worker_process_setup_hook: Optional[Union[Callable, str]] = None, + nsight: Optional[Union[str, Dict[str, str]]] = None, + rocprof_sys: Optional[Union[str, Dict[str, Dict[str, str]]]] = None, + config: Optional[Union[Dict, RuntimeEnvConfig]] = None, + _validate: bool = True, + mpi: Optional[Dict] = None, + image_uri: Optional[str] = None, + uv: Optional[List[str]] = None, + **kwargs, + ): + super().__init__() + + runtime_env = kwargs + if py_modules is not None: + runtime_env["py_modules"] = py_modules + if py_executable is not None: + runtime_env["py_executable"] = py_executable + if working_dir is not None: + runtime_env["working_dir"] = working_dir + if pip is not None: + runtime_env["pip"] = pip + if uv is not None: + runtime_env["uv"] = uv + if conda is not None: + runtime_env["conda"] = conda + if nsight is not None: + runtime_env["_nsight"] = nsight + if rocprof_sys is not None: + runtime_env["_rocprof_sys"] = rocprof_sys + if container is not None: + runtime_env["container"] = container + if env_vars is not None: + runtime_env["env_vars"] = env_vars + if config is not None: + runtime_env["config"] = config + if worker_process_setup_hook is not None: + runtime_env["worker_process_setup_hook"] = worker_process_setup_hook + if mpi is not None: + runtime_env["mpi"] = mpi + if image_uri is not None: + runtime_env["image_uri"] = image_uri + + self.update(runtime_env) + + # Blindly trust that the runtime_env has already been validated. + # This is dangerous and should only be used internally (e.g., on the + # deserialization codepath. + if not _validate: + return + + if (self.get("conda") is not None) + (self.get("pip") is not None) + ( + self.get("uv") is not None + ) > 1: + raise ValueError( + "The 'pip' field, 'uv' field, and 'conda' field of " + "runtime_env cannot be specified at the same time.\n" + f"specified pip field: {self.get('pip')}\n" + f"specified conda field: {self.get('conda')}\n" + f"specified uv field: {self.get('uv')}\n" + "To use pip with conda, please only set the 'conda'" + "field, and specify your pip dependencies within the conda YAML " + "config dict: see https://conda.io/projects/conda/en/latest/" + "user-guide/tasks/manage-environments.html" + "#create-env-file-manually" + ) + + if self.get("container"): + invalid_keys = set(runtime_env.keys()) - {"container", "config", "env_vars"} + if len(invalid_keys): + raise ValueError( + "The 'container' field currently cannot be used " + "together with other fields of runtime_env. " + f"Specified fields: {invalid_keys}" + ) + + logger.warning( + "The `container` runtime environment field is DEPRECATED and will be " + "removed after July 31, 2025. Use `image_uri` instead. See " + "https://docs.ray.io/en/latest/serve/advanced-guides/multi-app-container.html." # noqa + ) + + if self.get("image_uri"): + image_uri_plugin_cls = get_image_uri_plugin_cls() + invalid_keys = ( + set(runtime_env.keys()) - image_uri_plugin_cls.get_compatible_keys() + ) + if len(invalid_keys): + raise ValueError( + "The 'image_uri' field currently cannot be used " + "together with other fields of runtime_env. " + f"Specified fields: {invalid_keys}" + ) + + for option, validate_fn in OPTION_TO_VALIDATION_FN.items(): + option_val = self.get(option) + if option_val is not None: + del self[option] + self[option] = option_val + + if "_ray_commit" not in self: + if self.get("pip") or self.get("conda"): + self["_ray_commit"] = ray.__commit__ + + # Used for testing wheels that have not yet been merged into master. + # If this is set to True, then we do not inject Ray into the conda + # or pip dependencies. + if "_inject_current_ray" not in self: + if "RAY_RUNTIME_ENV_LOCAL_DEV_MODE" in os.environ: + self["_inject_current_ray"] = True + + # NOTE(architkulkarni): This allows worker caching code in C++ to check + # if a runtime env is empty without deserializing it. This is a catch- + # all; for validated inputs we won't set the key if the value is None. + if all(val is None for val in self.values()): + self.clear() + + def __setitem__(self, key: str, value: Any) -> None: + if is_dataclass(value): + jsonable_type = asdict(value) + else: + jsonable_type = value + RuntimeEnvPluginSchemaManager.validate(key, jsonable_type) + res_value = jsonable_type + if key in RuntimeEnv.known_fields and key in OPTION_TO_VALIDATION_FN: + res_value = OPTION_TO_VALIDATION_FN[key](jsonable_type) + if res_value is None: + return + return super().__setitem__(key, res_value) + + def set(self, name: str, value: Any) -> None: + self.__setitem__(name, value) + + def get(self, name, default=None, data_class=None): + if name not in self: + return default + if not data_class: + return self.__getitem__(name) + else: + return from_dict(data_class=data_class, data=self.__getitem__(name)) + + @classmethod + def deserialize(cls, serialized_runtime_env: str) -> "RuntimeEnv": # noqa: F821 + return cls(_validate=False, **json.loads(serialized_runtime_env)) + + def serialize(self) -> str: + # To ensure the accuracy of Proto, `__setitem__` can only guarantee the + # accuracy of a certain field, not the overall accuracy + runtime_env = type(self)(_validate=True, **self) + return json.dumps( + runtime_env, + sort_keys=True, + ) + + def to_dict(self) -> Dict: + runtime_env_dict = dict(deepcopy(self)) + + # Replace strongly-typed RuntimeEnvConfig with a dict to allow the returned + # dict to work properly as a field in a dataclass. Details in issue #26986 + if runtime_env_dict.get("config"): + runtime_env_dict["config"] = runtime_env_dict["config"].to_dict() + + return runtime_env_dict + + def has_working_dir(self) -> bool: + return self.get("working_dir") is not None + + def working_dir_uri(self) -> Optional[str]: + return self.get("working_dir") + + def py_modules_uris(self) -> List[str]: + if "py_modules" in self: + return list(self["py_modules"]) + return [] + + def conda_uri(self) -> Optional[str]: + if "conda" in self: + return get_conda_uri(self) + return None + + def pip_uri(self) -> Optional[str]: + if "pip" in self: + return get_pip_uri(self) + return None + + def uv_uri(self) -> Optional[str]: + if "uv" in self: + return get_uv_uri(self) + return None + + def plugin_uris(self) -> List[str]: + """Not implemented yet, always return a empty list""" + return [] + + def working_dir(self) -> str: + return self.get("working_dir", "") + + def py_modules(self) -> List[str]: + if "py_modules" in self: + return list(self["py_modules"]) + return [] + + def py_executable(self) -> Optional[str]: + return self.get("py_executable", None) + + def java_jars(self) -> List[str]: + if "java_jars" in self: + return list(self["java_jars"]) + return [] + + def mpi(self) -> Optional[Union[str, Dict[str, str]]]: + return self.get("mpi", None) + + def nsight(self) -> Optional[Union[str, Dict[str, str]]]: + return self.get("_nsight", None) + + def rocprof_sys(self) -> Optional[Union[str, Dict[str, Dict[str, str]]]]: + return self.get("_rocprof_sys", None) + + def env_vars(self) -> Dict: + return self.get("env_vars", {}) + + def has_conda(self) -> str: + if self.get("conda"): + return True + return False + + def conda_env_name(self) -> str: + if not self.has_conda() or not isinstance(self["conda"], str): + return None + return self["conda"] + + def conda_config(self) -> str: + if not self.has_conda() or not isinstance(self["conda"], dict): + return None + return json.dumps(self["conda"], sort_keys=True) + + def has_pip(self) -> bool: + if self.get("pip"): + return True + return False + + def has_uv(self) -> bool: + if self.get("uv"): + return True + return False + + def virtualenv_name(self) -> Optional[str]: + if not self.has_pip() or not isinstance(self["pip"], str): + return None + return self["pip"] + + def pip_config(self) -> Dict: + if not self.has_pip() or isinstance(self["pip"], str): + return {} + # Parse and validate field pip on method `__setitem__` + self["pip"] = self["pip"] + return self["pip"] + + def uv_config(self) -> Dict: + if not self.has_uv() or isinstance(self["uv"], str): + return {} + # Parse and validate field pip on method `__setitem__` + self["uv"] = self["uv"] + return self["uv"] + + def get_extension(self, key) -> Optional[str]: + if key not in RuntimeEnv.extensions_fields: + raise ValueError( + f"Extension key must be one of {RuntimeEnv.extensions_fields}, " + f"got: {key}" + ) + return self.get(key) + + def has_py_container(self) -> bool: + if self.get("container"): + return True + return False + + def py_container_image(self) -> Optional[str]: + if not self.has_py_container(): + return None + return self["container"].get("image", "") + + def py_container_worker_path(self) -> Optional[str]: + if not self.has_py_container(): + return None + return self["container"].get("worker_path", "") + + def py_container_run_options(self) -> List: + if not self.has_py_container(): + return None + return self["container"].get("run_options", []) + + def image_uri(self) -> Optional[str]: + return self.get("image_uri") + + def plugins(self) -> List[Tuple[str, Any]]: + result = list() + for key, value in self.items(): + if key not in self.known_fields: + result.append((key, value)) + return result + + +def _validate_no_local_paths(runtime_env: RuntimeEnv): + """Checks that options such as working_dir and py_modules only contain URIs.""" + if not isinstance(runtime_env, RuntimeEnv): + raise TypeError( + f"Expected type to be RuntimeEnv but received {type(runtime_env)} instead." + ) + for option, validate_fn in OPTION_TO_NO_PATH_VALIDATION_FN.items(): + option_val = runtime_env.get(option) + if option_val: + validate_fn(option_val) + + +def _merge_runtime_env( + parent: Optional[RuntimeEnv], + child: Optional[RuntimeEnv], + override: bool = False, +) -> Optional[RuntimeEnv]: + """Merge the parent and child runtime environments. + + If override = True, the child's runtime env overrides the parent's + runtime env in the event of a conflict. + + Merging happens per key (i.e., "conda", "pip", ...), but + "env_vars" are merged per env var key. + + It returns None if Ray fails to merge runtime environments because + of a conflict and `override = False`. + + Args: + parent: Parent runtime env. + child: Child runtime env. + override: If True, the child's runtime env overrides + conflicting fields. + Returns: + The merged runtime env's if Ray successfully merges them. + None if the runtime env's conflict. Empty dict if + parent and child are both None. + """ + if parent is None: + parent = {} + if child is None: + child = {} + + parent = deepcopy(parent) + child = deepcopy(child) + parent_env_vars = parent.pop("env_vars", {}) + child_env_vars = child.pop("env_vars", {}) + + if not override: + if set(parent.keys()).intersection(set(child.keys())): + return None + if set(parent_env_vars.keys()).intersection(set(child_env_vars.keys())): # noqa + return None + + parent.update(child) + parent_env_vars.update(child_env_vars) + if parent_env_vars: + parent["env_vars"] = parent_env_vars + + return parent diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/scripts/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/scripts/scripts.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/scripts/scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..76bf5958d9b160db6b82b4deea1b1ea562c97c6f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/scripts/scripts.py @@ -0,0 +1,2746 @@ +import copy +import json +import logging +import os +import platform +import signal +import subprocess +import sys +import time +import urllib +import urllib.parse +import warnings +import shutil +from datetime import datetime +from typing import Optional, Set, List, Tuple +from ray._common.utils import load_class +from ray.dashboard.modules.metrics import install_and_start_prometheus +from ray.util.check_open_ports import check_open_ports +import requests + +import click +import colorama +import psutil +import yaml + +import ray +import ray._private.ray_constants as ray_constants +import ray._private.services as services +from ray._private.label_utils import ( + parse_node_labels_json, + parse_node_labels_from_yaml_file, + parse_node_labels_string, +) +from ray._private.utils import ( + check_ray_client_dependencies_installed, + parse_resources_json, +) +from ray._private.internal_api import memory_summary +from ray._private.usage import usage_lib +import ray._private.usage.usage_constants as usage_constant +from ray.autoscaler._private.cli_logger import add_click_logging_options, cf, cli_logger +from ray.autoscaler._private.commands import ( + RUN_ENV_TYPES, + attach_cluster, + create_or_update_cluster, + debug_status, + exec_cluster, + get_cluster_dump_archive, + get_head_node_ip, + get_local_dump_archive, + get_worker_node_ips, + kill_node, + monitor_cluster, + rsync, + teardown_cluster, +) +from ray.autoscaler._private.constants import RAY_PROCESSES +from ray.autoscaler._private.fake_multi_node.node_provider import FAKE_HEAD_NODE_ID +from ray.util.annotations import PublicAPI +from ray.core.generated import autoscaler_pb2 +from ray._private.resource_isolation_config import ResourceIsolationConfig + + +logger = logging.getLogger(__name__) + + +def _check_ray_version(gcs_client): + import ray._private.usage.usage_lib as ray_usage_lib + + cluster_metadata = ray_usage_lib.get_cluster_metadata(gcs_client) + if cluster_metadata and cluster_metadata["ray_version"] != ray.__version__: + raise RuntimeError( + "Ray version mismatch: cluster has Ray version " + f'{cluster_metadata["ray_version"]} ' + f"but local Ray version is {ray.__version__}" + ) + + +@click.group() +@click.option( + "--logging-level", + required=False, + default=ray_constants.LOGGER_LEVEL, + type=str, + help=ray_constants.LOGGER_LEVEL_HELP, +) +@click.option( + "--logging-format", + required=False, + default=ray_constants.LOGGER_FORMAT, + type=str, + help=ray_constants.LOGGER_FORMAT_HELP, +) +@click.version_option() +def cli(logging_level, logging_format): + level = logging.getLevelName(logging_level.upper()) + ray._private.ray_logging.setup_logger(level, logging_format) + cli_logger.set_format(format_tmpl=logging_format) + + +@click.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--port", + "-p", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_PORT, + help="The local port to forward to the dashboard", +) +@click.option( + "--remote-port", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_PORT, + help="The remote port your dashboard runs on", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@PublicAPI +def dashboard(cluster_config_file, cluster_name, port, remote_port, no_config_cache): + """Port-forward a Ray cluster's dashboard to the local machine.""" + # Sleeping in a loop is preferable to `sleep infinity` because the latter + # only works on linux. + # Find the first open port sequentially from `remote_port`. + try: + port_forward = [ + (port, remote_port), + ] + click.echo( + "Attempting to establish dashboard locally at" + " http://localhost:{}/ connected to" + " remote port {}".format(port, remote_port) + ) + # We want to probe with a no-op that returns quickly to avoid + # exceptions caused by network errors. + exec_cluster( + cluster_config_file, + override_cluster_name=cluster_name, + port_forward=port_forward, + no_config_cache=no_config_cache, + ) + click.echo("Successfully established connection.") + except Exception as e: + raise click.ClickException( + "Failed to forward dashboard from remote port {1} to local port " + "{0}. There are a couple possibilities: \n 1. The remote port is " + "incorrectly specified \n 2. The local port {0} is already in " + "use.\n The exception is: {2}".format(port, remote_port, e) + ) from None + + +def continue_debug_session(live_jobs: Set[str]): + """Continue active debugging session. + + This function will connect 'ray debug' to the right debugger + when a user is stepping between Ray tasks. + """ + active_sessions = ray.experimental.internal_kv._internal_kv_list( + "RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB + ) + + for active_session in active_sessions: + if active_session.startswith(b"RAY_PDB_CONTINUE"): + # Check to see that the relevant job is still alive. + data = ray.experimental.internal_kv._internal_kv_get( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + if json.loads(data)["job_id"] not in live_jobs: + ray.experimental.internal_kv._internal_kv_del( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + continue + + print("Continuing pdb session in different process...") + key = b"RAY_PDB_" + active_session[len("RAY_PDB_CONTINUE_") :] + while True: + data = ray.experimental.internal_kv._internal_kv_get( + key, namespace=ray_constants.KV_NAMESPACE_PDB + ) + if data: + session = json.loads(data) + if "exit_debugger" in session or session["job_id"] not in live_jobs: + ray.experimental.internal_kv._internal_kv_del( + key, namespace=ray_constants.KV_NAMESPACE_PDB + ) + return + host, port = session["pdb_address"].split(":") + ray.util.rpdb._connect_pdb_client(host, int(port)) + ray.experimental.internal_kv._internal_kv_del( + key, namespace=ray_constants.KV_NAMESPACE_PDB + ) + continue_debug_session(live_jobs) + return + time.sleep(1.0) + + +def none_to_empty(s): + if s is None: + return "" + return s + + +def format_table(table): + """Format a table as a list of lines with aligned columns.""" + result = [] + col_width = [max(len(x) for x in col) for col in zip(*table)] + for line in table: + result.append( + " | ".join("{0:{1}}".format(x, col_width[i]) for i, x in enumerate(line)) + ) + return result + + +@cli.command() +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "-v", + "--verbose", + required=False, + is_flag=True, + help="Shows additional fields in breakpoint selection page.", +) +def debug(address: str, verbose: bool): + """Show all active breakpoints and exceptions in the Ray debugger.""" + address = services.canonicalize_bootstrap_address_or_die(address) + logger.info(f"Connecting to Ray instance at {address}.") + ray.init(address=address, log_to_driver=False) + if os.environ.get("RAY_DEBUG", "1") != "legacy": + print( + f"{colorama.Fore.YELLOW}NOTE: The distributed debugger " + "https://docs.ray.io/en/latest/ray-observability" + "/ray-distributed-debugger.html is now the default " + "due to better interactive debugging support. If you want " + "to keep using 'ray debug' please set RAY_DEBUG=legacy " + f"in your cluster (e.g. via runtime environment).{colorama.Fore.RESET}" + ) + while True: + # Used to filter out and clean up entries from dead jobs. + live_jobs = { + job["JobID"] for job in ray._private.state.jobs() if not job["IsDead"] + } + continue_debug_session(live_jobs) + + active_sessions = ray.experimental.internal_kv._internal_kv_list( + "RAY_PDB_", namespace=ray_constants.KV_NAMESPACE_PDB + ) + print("Active breakpoints:") + sessions_data = [] + for active_session in active_sessions: + data = json.loads( + ray.experimental.internal_kv._internal_kv_get( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + ) + # Check that the relevant job is alive, else clean up the entry. + if data["job_id"] in live_jobs: + sessions_data.append(data) + else: + ray.experimental.internal_kv._internal_kv_del( + active_session, namespace=ray_constants.KV_NAMESPACE_PDB + ) + sessions_data = sorted( + sessions_data, key=lambda data: data["timestamp"], reverse=True + ) + if verbose: + table = [ + [ + "index", + "timestamp", + "Ray task", + "filename:lineno", + "Task ID", + "Worker ID", + "Actor ID", + "Node ID", + ] + ] + for i, data in enumerate(sessions_data): + date = datetime.utcfromtimestamp(data["timestamp"]).strftime( + "%Y-%m-%d %H:%M:%S" + ) + table.append( + [ + str(i), + date, + data["proctitle"], + data["filename"] + ":" + str(data["lineno"]), + data["task_id"], + data["worker_id"], + none_to_empty(data["actor_id"]), + data["node_id"], + ] + ) + else: + # Non verbose mode: no IDs. + table = [["index", "timestamp", "Ray task", "filename:lineno"]] + for i, data in enumerate(sessions_data): + date = datetime.utcfromtimestamp(data["timestamp"]).strftime( + "%Y-%m-%d %H:%M:%S" + ) + table.append( + [ + str(i), + date, + data["proctitle"], + data["filename"] + ":" + str(data["lineno"]), + ] + ) + for i, line in enumerate(format_table(table)): + print(line) + if i >= 1 and not sessions_data[i - 1]["traceback"].startswith( + "NoneType: None" + ): + print(sessions_data[i - 1]["traceback"]) + inp = input("Enter breakpoint index or press enter to refresh: ") + if inp == "": + print() + continue + else: + index = int(inp) + session = json.loads( + ray.experimental.internal_kv._internal_kv_get( + active_sessions[index], namespace=ray_constants.KV_NAMESPACE_PDB + ) + ) + host, port = session["pdb_address"].split(":") + ray.util.rpdb._connect_pdb_client(host, int(port)) + + +@cli.command() +@click.option( + "--node-ip-address", required=False, type=str, help="the IP address of this node" +) +@click.option("--address", required=False, type=str, help="the address to use for Ray") +@click.option( + "--port", + type=int, + required=False, + help=f"the port of the head ray process. If not provided, defaults to " + f"{ray_constants.DEFAULT_PORT}; if port is set to 0, we will" + f" allocate an available port.", +) +@click.option( + "--node-name", + required=False, + hidden=True, + type=str, + help="the user-provided identifier or name for this node. " + "Defaults to the node's ip_address", +) +@click.option( + "--redis-username", + required=False, + hidden=True, + type=str, + default=ray_constants.REDIS_DEFAULT_USERNAME, + help="If provided, secure Redis ports with this username", +) +@click.option( + "--redis-password", + required=False, + hidden=True, + type=str, + default=ray_constants.REDIS_DEFAULT_PASSWORD, + help="If provided, secure Redis ports with this password", +) +@click.option( + "--redis-shard-ports", + required=False, + hidden=True, + type=str, + help="the port to use for the Redis shards other than the primary Redis shard", +) +@click.option( + "--object-manager-port", + required=False, + type=int, + help="the port to use for starting the object manager", +) +@click.option( + "--node-manager-port", + required=False, + type=int, + default=0, + help="the port to use for starting the node manager", +) +@click.option( + "--min-worker-port", + required=False, + type=int, + default=10002, + help="the lowest port number that workers will bind on. If not set, " + "random ports will be chosen.", +) +@click.option( + "--max-worker-port", + required=False, + type=int, + default=19999, + help="the highest port number that workers will bind on. If set, " + "'--min-worker-port' must also be set.", +) +@click.option( + "--worker-port-list", + required=False, + help="a comma-separated list of open ports for workers to bind on. " + "Overrides '--min-worker-port' and '--max-worker-port'.", +) +@click.option( + "--ray-client-server-port", + required=False, + type=int, + default=None, + help="the port number the ray client server binds on, default to 10001, " + "or None if ray[client] is not installed.", +) +@click.option( + "--memory", + required=False, + hidden=True, + type=int, + help="The amount of memory (in bytes) to make available to workers. " + "By default, this is set to the available memory on the node.", +) +@click.option( + "--object-store-memory", + required=False, + type=int, + help="The amount of memory (in bytes) to start the object store with. " + "By default, this is 30% of available system memory capped by " + "the shm size and 200G but can be set higher.", +) +@click.option( + "--num-cpus", required=False, type=int, help="the number of CPUs on this node" +) +@click.option( + "--num-gpus", required=False, type=int, help="the number of GPUs on this node" +) +@click.option( + "--resources", + required=False, + default="{}", + type=str, + help="A JSON serialized dictionary mapping resource name to resource quantity." + + ( + r""" + +Windows command prompt users must ensure to double quote command line arguments. Because +JSON requires the use of double quotes you must escape these arguments as well, for +example: + + ray start --head --resources="{\"special_hardware\":1, \"custom_label\":1}" + +Windows powershell users need additional escaping: + + ray start --head --resources="{\""special_hardware\"":1, \""custom_label\"":1}" +""" + if platform.system() == "Windows" + else "" + ), +) +@click.option( + "--head", + is_flag=True, + default=False, + help="provide this argument for the head node", +) +@click.option( + "--include-dashboard", + default=None, + type=bool, + help="provide this argument to start the Ray dashboard GUI", +) +@click.option( + "--dashboard-host", + required=False, + default=ray_constants.DEFAULT_DASHBOARD_IP, + help="the host to bind the dashboard server to, either localhost " + "(127.0.0.1) or 0.0.0.0 (available from all interfaces). By default, this " + "is 127.0.0.1", +) +@click.option( + "--dashboard-port", + required=False, + type=int, + default=ray_constants.DEFAULT_DASHBOARD_PORT, + help="the port to bind the dashboard server to--defaults to {}".format( + ray_constants.DEFAULT_DASHBOARD_PORT + ), +) +@click.option( + "--dashboard-agent-listen-port", + type=int, + default=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT, + help="the port for dashboard agents to listen for http on.", +) +@click.option( + "--dashboard-agent-grpc-port", + type=int, + default=None, + help="the port for dashboard agents to listen for grpc on.", +) +@click.option( + "--runtime-env-agent-port", + type=int, + default=None, + help="The port for the runtime environment agents to listen for http on.", +) +@click.option( + "--block", + is_flag=True, + default=False, + help="provide this argument to block forever in this command", +) +@click.option( + "--plasma-directory", + required=False, + type=str, + help="object store directory for memory mapped files", +) +@click.option( + "--object-spilling-directory", + required=False, + type=str, + help="The path to spill objects to. This path will also be used as the fallback directory when the object store is full of in-use objects and cannot spill.", +) +@click.option( + "--autoscaling-config", + required=False, + type=str, + help="the file that contains the autoscaling config", +) +@click.option( + "--no-redirect-output", + is_flag=True, + default=False, + help="do not redirect non-worker stdout and stderr to files", +) +@click.option( + "--temp-dir", + default=None, + help="manually specify the root temporary dir of the Ray process, only " + "works when --head is specified", +) +@click.option( + "--system-config", + default=None, + hidden=True, + type=json.loads, + help="Override system configuration defaults.", +) +@click.option( + "--enable-object-reconstruction", + is_flag=True, + default=False, + hidden=True, + help="Specify whether object reconstruction will be used for this cluster.", +) +@click.option( + "--metrics-export-port", + type=int, + default=None, + help="the port to use to expose Ray metrics through a Prometheus endpoint.", +) +@click.option( + "--no-monitor", + is_flag=True, + hidden=True, + default=False, + help="If True, the ray autoscaler monitor for this cluster will not be started.", +) +@click.option( + "--tracing-startup-hook", + type=str, + hidden=True, + default=None, + help="The function that sets up tracing with a tracing provider, remote " + "span processor, and additional instruments. See docs.ray.io/tracing.html " + "for more info.", +) +@click.option( + "--ray-debugger-external", + is_flag=True, + default=False, + help="Make the Ray debugger available externally to the node. This is only " + "safe to activate if the node is behind a firewall.", +) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@click.option( + "--labels", + required=False, + hidden=True, + default="", + type=str, + help="a string list of key-value pairs mapping label name to label value." + "These values take precedence over conflicting keys passed in from --labels-file." + 'Ex: --labels "key1=val1,key2=val2"', +) +@click.option( + "--labels-file", + required=False, + hidden=True, + default="", + type=str, + help="a path to a YAML file containing a dictionary mapping of label keys to values.", +) +@click.option( + "--include-log-monitor", + default=None, + type=bool, + help="If set to True or left unset, a log monitor will start monitoring " + "the log files of all processes on this node and push their contents to GCS. " + "Only one log monitor should be started per physical host to avoid log " + "duplication on the driver process.", +) +@click.option( + "--enable-resource-isolation", + required=False, + is_flag=True, + default=False, + help="Enable resource isolation through cgroupv2 by reserving memory and cpu " + "resources for ray system processes. To use, only cgroupv2 (not cgroupv1) must " + "be enabled with read and write permissions for the raylet. Cgroup memory and " + "cpu controllers must also be enabled.", +) +@click.option( + "--system-reserved-cpu", + required=False, + type=float, + help="The amount of cpu cores to reserve for ray system processes. Cores can be " + "fractional i.e. 0.5 means half a cpu core. " + "By default, the min of 20% and 1 core will be reserved." + "Must be >= 0.5 and < total number of available cores. " + "This option only works if --enable-resource-isolation is set.", +) +@click.option( + "--system-reserved-memory", + required=False, + type=int, + help="The amount of memory (in bytes) to reserve for ray system processes. " + "By default, the min of 10% and 25GB plus object_store_memory will be reserved. " + "Must be >= 100MB and system-reserved-memory + object-store-bytes < total available memory " + "This option only works if --enable-resource-isolation is set.", +) +@click.option( + "--cgroup-path", + required=False, + hidden=True, + type=str, + help="The path for the cgroup the raylet should use to enforce resource isolation. " + "By default, the cgroup used for resource isolation will be /sys/fs/cgroup. " + "The raylet must have read/write permissions to this path. " + "Cgroup memory and cpu controllers be enabled for this cgroup. " + "This option only works if --enable-resource-isolation is set.", +) +@add_click_logging_options +@PublicAPI +def start( + node_ip_address, + address, + port, + node_name, + redis_username, + redis_password, + redis_shard_ports, + object_manager_port, + node_manager_port, + min_worker_port, + max_worker_port, + worker_port_list, + ray_client_server_port, + memory, + object_store_memory, + num_cpus, + num_gpus, + resources, + head, + include_dashboard, + dashboard_host, + dashboard_port, + dashboard_agent_listen_port, + dashboard_agent_grpc_port, + runtime_env_agent_port, + block, + plasma_directory, + object_spilling_directory, + autoscaling_config, + no_redirect_output, + temp_dir, + system_config, + enable_object_reconstruction, + metrics_export_port, + no_monitor, + tracing_startup_hook, + ray_debugger_external, + disable_usage_stats, + labels, + labels_file, + include_log_monitor, + enable_resource_isolation, + system_reserved_cpu, + system_reserved_memory, + cgroup_path, +): + """Start Ray processes manually on the local machine.""" + + # Whether the original arguments include node_ip_address. + include_node_ip_address = False + if node_ip_address is not None: + include_node_ip_address = True + node_ip_address = services.resolve_ip_for_localhost(node_ip_address) + + resources = parse_resources_json(resources, cli_logger, cf) + + # Compose labels passed in with `--labels` and `--labels-file`. + # In the case of duplicate keys, the values from `--labels` take precedence. + try: + labels_from_file = parse_node_labels_from_yaml_file(labels_file) + except Exception as e: + cli_logger.abort( + "The file at `{}` is not a valid YAML file, detailed error: {} " + "Valid values look like this: `{}`", + cf.bold(f"--labels-file={labels_file}"), + str(e), + cf.bold("--labels-file='gpu_type: A100\nregion: us'"), + ) + try: + # Attempt to parse labels from new string format first. + labels_from_string = parse_node_labels_string(labels) + except Exception as e: + try: + # Fall back to JSON format if parsing from string fails. + labels_from_string = parse_node_labels_json(labels) + warnings.warn( + "passing node labels with `--labels` in JSON format is " + "deprecated and will be removed in a future version of Ray.", + DeprecationWarning, + stacklevel=2, + ) + except Exception: + # If parsing labels from both formats fails, return the original error message. + cli_logger.abort( + "`{}` is not a valid string of key-value pairs, detailed error: {} " + "Valid values look like this: `{}`", + cf.bold(f"--labels={labels}"), + str(e), + cf.bold('--labels="key1=val1,key2=val2"'), + ) + labels_dict = {**labels_from_file, **labels_from_string} + if temp_dir and not head: + cli_logger.warning( + f"`--temp-dir={temp_dir}` option will be ignored. " + "`--head` is a required flag to use `--temp-dir`. " + "temp_dir is only configurable from a head node. " + "All the worker nodes will use the same temp_dir as a head node. " + ) + temp_dir = None + + resource_isolation_config = ResourceIsolationConfig( + enable_resource_isolation=enable_resource_isolation, + cgroup_path=cgroup_path, + system_reserved_cpu=system_reserved_cpu, + system_reserved_memory=system_reserved_memory, + ) + + redirect_output = None if not no_redirect_output else True + + # no client, no port -> ok + # no port, has client -> default to 10001 + # has port, no client -> value error + # has port, has client -> ok, check port validity + has_ray_client = check_ray_client_dependencies_installed() + if has_ray_client and ray_client_server_port is None: + ray_client_server_port = 10001 + + ray_params = ray._private.parameter.RayParams( + node_ip_address=node_ip_address, + node_name=node_name if node_name else node_ip_address, + min_worker_port=min_worker_port, + max_worker_port=max_worker_port, + worker_port_list=worker_port_list, + ray_client_server_port=ray_client_server_port, + object_manager_port=object_manager_port, + node_manager_port=node_manager_port, + memory=memory, + object_store_memory=object_store_memory, + redis_username=redis_username, + redis_password=redis_password, + redirect_output=redirect_output, + num_cpus=num_cpus, + num_gpus=num_gpus, + resources=resources, + labels=labels_dict, + autoscaling_config=autoscaling_config, + plasma_directory=plasma_directory, + object_spilling_directory=object_spilling_directory, + huge_pages=False, + temp_dir=temp_dir, + include_dashboard=include_dashboard, + dashboard_host=dashboard_host, + dashboard_port=dashboard_port, + dashboard_agent_listen_port=dashboard_agent_listen_port, + metrics_agent_port=dashboard_agent_grpc_port, + runtime_env_agent_port=runtime_env_agent_port, + _system_config=system_config, + enable_object_reconstruction=enable_object_reconstruction, + metrics_export_port=metrics_export_port, + no_monitor=no_monitor, + tracing_startup_hook=tracing_startup_hook, + ray_debugger_external=ray_debugger_external, + include_log_monitor=include_log_monitor, + resource_isolation_config=resource_isolation_config, + ) + + if ray_constants.RAY_START_HOOK in os.environ: + load_class(os.environ[ray_constants.RAY_START_HOOK])(ray_params, head) + + if head: + # Start head node. + + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + usage_lib.show_usage_stats_prompt(cli=True) + cli_logger.newline() + + if port is None: + port = ray_constants.DEFAULT_PORT + + # Set bootstrap port. + assert ray_params.redis_port is None + assert ray_params.gcs_server_port is None + ray_params.gcs_server_port = port + + if os.environ.get("RAY_FAKE_CLUSTER"): + ray_params.env_vars = { + "RAY_OVERRIDE_NODE_ID_FOR_TESTING": FAKE_HEAD_NODE_ID + } + + if ( + no_monitor # KubeRay sets this flag when autoscaler is enabled. + and usage_constant.KUBERAY_ENV in os.environ # KubeRay exclusive. + and "RAY_CLOUD_INSTANCE_ID" in os.environ # required by autoscaler v2. + and "RAY_NODE_TYPE_NAME" in os.environ # required by autoscaler v2. + ): + # If this Ray cluster is managed by KubeRay and RAY_CLOUD_INSTANCE_ID and RAY_NODE_TYPE_NAME are set, + # we enable the v2 autoscaler by default if RAY_enable_autoscaler_v2 is not set. + os.environ.setdefault("RAY_enable_autoscaler_v2", "1") + + num_redis_shards = None + # Start Ray on the head node. + if redis_shard_ports is not None and address is None: + redis_shard_ports = redis_shard_ports.split(",") + # Infer the number of Redis shards from the ports if the number is + # not provided. + num_redis_shards = len(redis_shard_ports) + + # This logic is deprecated and will be removed later. + if address is not None: + cli_logger.warning( + "Specifying {} for external Redis address is deprecated. " + "Please specify environment variable {}={} instead.", + cf.bold("--address"), + cf.bold("RAY_REDIS_ADDRESS"), + address, + ) + external_addresses = address.split(",") + + # We reuse primary redis as sharding when there's only one + # instance provided. + if len(external_addresses) == 1: + external_addresses.append(external_addresses[0]) + + ray_params.update_if_absent(external_addresses=external_addresses) + num_redis_shards = len(external_addresses) - 1 + if redis_username == ray_constants.REDIS_DEFAULT_USERNAME: + cli_logger.warning( + "`{}` should not be specified as empty string if " + "external Redis server(s) `{}` points to requires " + "username.", + cf.bold("--redis-username"), + cf.bold("--address"), + ) + if redis_password == ray_constants.REDIS_DEFAULT_PASSWORD: + cli_logger.warning( + "`{}` should not be specified as empty string if " + "external redis server(s) `{}` points to requires " + "password.", + cf.bold("--redis-password"), + cf.bold("--address"), + ) + + # Get the node IP address if one is not provided. + ray_params.update_if_absent(node_ip_address=services.get_node_ip_address()) + cli_logger.labeled_value("Local node IP", ray_params.node_ip_address) + + # Initialize Redis settings. + ray_params.update_if_absent( + redis_shard_ports=redis_shard_ports, + num_redis_shards=num_redis_shards, + redis_max_clients=None, + ) + + # Fail early when starting a new cluster when one is already running + if address is None: + default_address = f"{ray_params.node_ip_address}:{port}" + bootstrap_address = services.find_bootstrap_address(temp_dir) + if ( + default_address == bootstrap_address + and bootstrap_address in services.find_gcs_addresses() + ): + # The default address is already in use by a local running GCS + # instance. + raise ConnectionError( + f"Ray is trying to start at {default_address}, " + f"but is already running at {bootstrap_address}. " + "Please specify a different port using the `--port`" + " flag of `ray start` command." + ) + + node = ray._private.node.Node( + ray_params, head=True, shutdown_at_exit=block, spawn_reaper=block + ) + + bootstrap_address = node.address + + # this is a noop if new-style is not set, so the old logger calls + # are still in place + cli_logger.newline() + startup_msg = "Ray runtime started." + cli_logger.success("-" * len(startup_msg)) + cli_logger.success(startup_msg) + cli_logger.success("-" * len(startup_msg)) + cli_logger.newline() + with cli_logger.group("Next steps"): + dashboard_url = node.address_info["webui_url"] + if ray_constants.ENABLE_RAY_CLUSTER: + cli_logger.print("To add another node to this Ray cluster, run") + # NOTE(kfstorm): Java driver rely on this line to get the address + # of the cluster. Please be careful when updating this line. + cli_logger.print( + cf.bold(" {} ray start --address='{}'"), + f" {ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR}=1" + if ray_constants.IS_WINDOWS_OR_OSX + else "", + bootstrap_address, + ) + + cli_logger.newline() + cli_logger.print("To connect to this Ray cluster:") + with cli_logger.indented(): + cli_logger.print("{} ray", cf.magenta("import")) + cli_logger.print( + "ray{}init({})", + cf.magenta("."), + "_node_ip_address{}{}".format( + cf.magenta("="), cf.yellow("'" + node_ip_address + "'") + ) + if include_node_ip_address + else "", + ) + + if dashboard_url: + cli_logger.newline() + cli_logger.print("To submit a Ray job using the Ray Jobs CLI:") + cli_logger.print( + cf.bold( + " RAY_ADDRESS='http://{}' ray job submit " + "--working-dir . " + "-- python my_script.py" + ), + dashboard_url, + ) + cli_logger.newline() + cli_logger.print( + "See https://docs.ray.io/en/latest/cluster/running-applications" + "/job-submission/index.html " + ) + cli_logger.print( + "for more information on submitting Ray jobs to the Ray cluster." + ) + + cli_logger.newline() + cli_logger.print("To terminate the Ray runtime, run") + cli_logger.print(cf.bold(" ray stop")) + + cli_logger.newline() + cli_logger.print("To view the status of the cluster, use") + cli_logger.print(" {}".format(cf.bold("ray status"))) + + if dashboard_url: + cli_logger.newline() + cli_logger.print("To monitor and debug Ray, view the dashboard at ") + cli_logger.print( + " {}".format( + cf.bold(dashboard_url), + ) + ) + + cli_logger.newline() + cli_logger.print( + cf.underlined( + "If connection to the dashboard fails, check your " + "firewall settings and " + "network configuration." + ) + ) + ray_params.gcs_address = bootstrap_address + else: + # Start worker node. + if not ray_constants.ENABLE_RAY_CLUSTER: + cli_logger.abort( + "Multi-node Ray clusters are not supported on Windows and OSX. " + "Restart the Ray cluster with the environment variable `{}=1` " + "to proceed anyway.", + cf.bold(ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR), + ) + raise Exception( + "Multi-node Ray clusters are not supported on Windows and OSX. " + "Restart the Ray cluster with the environment variable " + f"`{ray_constants.ENABLE_RAY_CLUSTERS_ENV_VAR}=1` to proceed " + "anyway.", + ) + + # Ensure `--address` flag is specified. + if address is None: + cli_logger.abort( + "`{}` is a required flag unless starting a head node with `{}`.", + cf.bold("--address"), + cf.bold("--head"), + ) + raise Exception( + "`--address` is a required flag unless starting a " + "head node with `--head`." + ) + + # Raise error if any head-only flag are specified. + head_only_flags = { + "--port": port, + "--redis-shard-ports": redis_shard_ports, + "--include-dashboard": include_dashboard, + } + for flag, val in head_only_flags.items(): + if val is None: + continue + cli_logger.abort( + "`{}` should only be specified when starting head node with `{}`.", + cf.bold(flag), + cf.bold("--head"), + ) + raise ValueError( + f"{flag} should only be specified when starting head node " + "with `--head`." + ) + + # Start Ray on a non-head node. + bootstrap_address = services.canonicalize_bootstrap_address( + address, temp_dir=temp_dir + ) + + if bootstrap_address is None: + cli_logger.abort( + "Cannot canonicalize address `{}={}`.", + cf.bold("--address"), + cf.bold(address), + ) + raise Exception("Cannot canonicalize address " f"`--address={address}`.") + + ray_params.gcs_address = bootstrap_address + + # Get the node IP address if one is not provided. + ray_params.update_if_absent( + node_ip_address=services.get_node_ip_address(bootstrap_address) + ) + + cli_logger.labeled_value("Local node IP", ray_params.node_ip_address) + + node = ray._private.node.Node( + ray_params, head=False, shutdown_at_exit=block, spawn_reaper=block + ) + temp_dir = node.get_temp_dir_path() + + # TODO(hjiang): Validate whether specified resource is true for physical + # resource. + + # Ray and Python versions should probably be checked before + # initializing Node. + node.check_version_info() + + cli_logger.newline() + startup_msg = "Ray runtime started." + cli_logger.success("-" * len(startup_msg)) + cli_logger.success(startup_msg) + cli_logger.success("-" * len(startup_msg)) + cli_logger.newline() + cli_logger.print("To terminate the Ray runtime, run") + cli_logger.print(cf.bold(" ray stop")) + cli_logger.flush() + + assert ray_params.gcs_address is not None + ray._private.utils.write_ray_address(ray_params.gcs_address, temp_dir) + + if block: + cli_logger.newline() + with cli_logger.group(cf.bold("--block")): + cli_logger.print( + "This command will now block forever until terminated by a signal." + ) + cli_logger.print( + "Running subprocesses are monitored and a message will be " + "printed if any of them terminate unexpectedly. Subprocesses " + "exit with SIGTERM will be treated as graceful, thus NOT reported." + ) + cli_logger.flush() + + while True: + time.sleep(1) + deceased = node.dead_processes() + + # Report unexpected exits of subprocesses with unexpected return codes. + # We are explicitly expecting SIGTERM because this is how `ray stop` sends + # shutdown signal to subprocesses, i.e. log_monitor, raylet... + # NOTE(rickyyx): We are treating 128+15 as an expected return code since + # this is what autoscaler/_private/monitor.py does upon SIGTERM + # handling. + expected_return_codes = [ + 0, + signal.SIGTERM, + -1 * signal.SIGTERM, + 128 + signal.SIGTERM, + ] + unexpected_deceased = [ + (process_type, process) + for process_type, process in deceased + if process.returncode not in expected_return_codes + ] + if len(unexpected_deceased) > 0: + cli_logger.newline() + cli_logger.error("Some Ray subprocesses exited unexpectedly:") + + with cli_logger.indented(): + for process_type, process in unexpected_deceased: + cli_logger.error( + "{}", + cf.bold(str(process_type)), + _tags={"exit code": str(process.returncode)}, + ) + + cli_logger.newline() + cli_logger.error("Remaining processes will be killed.") + # explicitly kill all processes since atexit handlers + # will not exit with errors. + node.kill_all_processes(check_alive=False, allow_graceful=False) + os._exit(1) + # not-reachable + + +@cli.command() +@click.option( + "-f", + "--force", + is_flag=True, + help="If set, ray will send SIGKILL instead of SIGTERM.", +) +@click.option( + "-g", + "--grace-period", + default=16, + help=( + "The time in seconds ray waits for processes to be properly terminated. " + "If processes are not terminated within the grace period, " + "they are forcefully terminated after the grace period. " + ), +) +@add_click_logging_options +@PublicAPI +def stop(force: bool, grace_period: int): + """Stop Ray processes manually on the local machine.""" + is_linux = sys.platform.startswith("linux") + total_procs_found = 0 + total_procs_stopped = 0 + procs_not_gracefully_killed = [] + + def kill_procs( + force: bool, grace_period: int, processes_to_kill: List[str] + ) -> Tuple[int, int, List[psutil.Process]]: + """Find all processes from `processes_to_kill` and terminate them. + + Unless `force` is specified, it gracefully kills processes. If + processes are not cleaned within `grace_period`, it force kill all + remaining processes. + + Returns: + total_procs_found: Total number of processes found from + `processes_to_kill` is added. + total_procs_stopped: Total number of processes gracefully + stopped from `processes_to_kill` is added. + procs_not_gracefully_killed: If processes are not killed + gracefully, they are added here. + """ + process_infos = [] + for proc in psutil.process_iter(["name", "cmdline"]): + try: + process_infos.append((proc, proc.name(), proc.cmdline())) + except psutil.Error: + pass + + stopped = [] + for keyword, filter_by_cmd in processes_to_kill: + if filter_by_cmd and is_linux and len(keyword) > 15: + # getting here is an internal bug, so we do not use cli_logger + msg = ( + "The filter string should not be more than {} " + "characters. Actual length: {}. Filter: {}" + ).format(15, len(keyword), keyword) + raise ValueError(msg) + + found = [] + for candidate in process_infos: + proc, proc_cmd, proc_args = candidate + corpus = ( + proc_cmd if filter_by_cmd else subprocess.list2cmdline(proc_args) + ) + if keyword in corpus: + found.append(candidate) + for proc, proc_cmd, proc_args in found: + proc_string = str(subprocess.list2cmdline(proc_args)) + try: + if force: + proc.kill() + else: + # TODO(mehrdadn): On Windows, this is forceful termination. + # We don't want CTRL_BREAK_EVENT, because that would + # terminate the entire process group. What to do? + proc.terminate() + + if force: + cli_logger.verbose( + "Killed `{}` {} ", + cf.bold(proc_string), + cf.dimmed("(via SIGKILL)"), + ) + else: + cli_logger.verbose( + "Send termination request to `{}` {}", + cf.bold(proc_string), + cf.dimmed("(via SIGTERM)"), + ) + + stopped.append(proc) + except psutil.NoSuchProcess: + cli_logger.verbose( + "Attempted to stop `{}`, but process was already dead.", + cf.bold(proc_string), + ) + except (psutil.Error, OSError) as ex: + cli_logger.error( + "Could not terminate `{}` due to {}", + cf.bold(proc_string), + str(ex), + ) + + # Wait for the processes to actually stop. + # Dedup processes. + stopped, alive = psutil.wait_procs(stopped, timeout=0) + procs_to_kill = stopped + alive + total_found = len(procs_to_kill) + + # Wait for grace period to terminate processes. + gone_procs = set() + + def on_terminate(proc): + gone_procs.add(proc) + cli_logger.print(f"{len(gone_procs)}/{total_found} stopped.", end="\r") + + stopped, alive = psutil.wait_procs( + procs_to_kill, timeout=grace_period, callback=on_terminate + ) + total_stopped = len(stopped) + + # For processes that are not killed within the grace period, + # we send force termination signals. + for proc in alive: + proc.kill() + # Wait a little bit to make sure processes are killed forcefully. + psutil.wait_procs(alive, timeout=2) + return total_found, total_stopped, alive + + # Process killing procedure: we put processes into 3 buckets. + # Bucket 1: raylet + # Bucket 2: all other processes, e.g. dashboard, runtime env agents + # Bucket 3: gcs_server. + # + # For each bucket, we send sigterm to all processes, then wait for 30s, then if + # they are still alive, send sigkill. + processes_to_kill = RAY_PROCESSES + # Raylet should exit before all other processes exit. + # Otherwise, fate-sharing agents will complain and exit. + assert processes_to_kill[0][0] == "raylet" + + # GCS should exit after all other processes exit. + # Otherwise, some of processes may exit with an unexpected + # exit code which breaks ray start --block. + assert processes_to_kill[-1][0] == "gcs_server" + + buckets = [[processes_to_kill[0]], processes_to_kill[1:-1], [processes_to_kill[-1]]] + + for bucket in buckets: + found, stopped, alive = kill_procs(force, grace_period / len(buckets), bucket) + total_procs_found += found + total_procs_stopped += stopped + procs_not_gracefully_killed.extend(alive) + + # Print the termination result. + if total_procs_found == 0: + cli_logger.print("Did not find any active Ray processes.") + else: + if total_procs_stopped == total_procs_found: + cli_logger.success("Stopped all {} Ray processes.", total_procs_stopped) + else: + cli_logger.warning( + f"Stopped only {total_procs_stopped} out of {total_procs_found} " + f"Ray processes within the grace period {grace_period} seconds. " + f"Set `{cf.bold('-v')}` to see more details. " + f"Remaining processes {procs_not_gracefully_killed} " + "will be forcefully terminated.", + ) + cli_logger.warning( + f"You can also use `{cf.bold('--force')}` to forcefully terminate " + "processes or set higher `--grace-period` to wait longer time for " + "proper termination." + ) + + # NOTE(swang): This will not reset the cluster address for a user-defined + # temp_dir. This is fine since it will get overwritten the next time we + # call `ray start`. + ray._common.utils.reset_ray_address() + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--min-workers", + required=False, + type=int, + help="Override the configured min worker node count for the cluster.", +) +@click.option( + "--max-workers", + required=False, + type=int, + help="Override the configured max worker node count for the cluster.", +) +@click.option( + "--no-restart", + is_flag=True, + default=False, + help=( + "Whether to skip restarting Ray services during the update. " + "This avoids interrupting running jobs." + ), +) +@click.option( + "--restart-only", + is_flag=True, + default=False, + help=( + "Whether to skip running setup commands and only restart Ray. " + "This cannot be used with 'no-restart'." + ), +) +@click.option( + "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation." +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option( + "--redirect-command-output", + is_flag=True, + default=False, + help="Whether to redirect command output to a file.", +) +@click.option( + "--use-login-shells/--use-normal-shells", + is_flag=True, + default=True, + help=( + "Ray uses login shells (bash --login -i) to run cluster commands " + "by default. If your workflow is compatible with normal shells, " + "this can be disabled for a better user experience." + ), +) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@add_click_logging_options +@PublicAPI +def up( + cluster_config_file, + min_workers, + max_workers, + no_restart, + restart_only, + yes, + cluster_name, + no_config_cache, + redirect_command_output, + use_login_shells, + disable_usage_stats, +): + """Create or update a Ray cluster.""" + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + + if restart_only or no_restart: + cli_logger.doassert( + restart_only != no_restart, + "`{}` is incompatible with `{}`.", + cf.bold("--restart-only"), + cf.bold("--no-restart"), + ) + assert ( + restart_only != no_restart + ), "Cannot set both 'restart_only' and 'no_restart' at the same time!" + + if urllib.parse.urlparse(cluster_config_file).scheme in ("http", "https"): + try: + response = urllib.request.urlopen(cluster_config_file, timeout=5) + content = response.read() + file_name = cluster_config_file.split("/")[-1] + with open(file_name, "wb") as f: + f.write(content) + cluster_config_file = file_name + except urllib.error.HTTPError as e: + cli_logger.warning("{}", str(e)) + cli_logger.warning("Could not download remote cluster configuration file.") + create_or_update_cluster( + config_file=cluster_config_file, + override_min_workers=min_workers, + override_max_workers=max_workers, + no_restart=no_restart, + restart_only=restart_only, + yes=yes, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + redirect_command_output=redirect_command_output, + use_login_shells=use_login_shells, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation." +) +@click.option( + "--workers-only", is_flag=True, default=False, help="Only destroy the workers." +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--keep-min-workers", + is_flag=True, + default=False, + help="Retain the minimal amount of workers specified in the config.", +) +@add_click_logging_options +@PublicAPI +def down(cluster_config_file, yes, workers_only, cluster_name, keep_min_workers): + """Tear down a Ray cluster.""" + teardown_cluster( + cluster_config_file, yes, workers_only, cluster_name, keep_min_workers + ) + + +@cli.command(hidden=True) +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation." +) +@click.option( + "--hard", + is_flag=True, + default=False, + help="Terminates the node via node provider (defaults to a 'soft kill'" + " which terminates Ray but does not actually delete the instances).", +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +def kill_random_node(cluster_config_file, yes, hard, cluster_name): + """Kills a random Ray node. For testing purposes only.""" + click.echo( + "Killed node with IP " + kill_node(cluster_config_file, yes, hard, cluster_name) + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--lines", required=False, default=100, type=int, help="Number of lines to tail." +) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@add_click_logging_options +def monitor(cluster_config_file, lines, cluster_name): + """Tails the autoscaler logs of a Ray cluster.""" + monitor_cluster(cluster_config_file, lines, cluster_name) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--start", is_flag=True, default=False, help="Start the cluster if needed." +) +@click.option( + "--screen", is_flag=True, default=False, help="Run the command in screen." +) +@click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.") +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option("--new", "-N", is_flag=True, help="Force creation of a new screen.") +@click.option( + "--port-forward", + "-p", + required=False, + multiple=True, + type=int, + help="Port to forward. Use this multiple times to forward multiple ports.", +) +@add_click_logging_options +@PublicAPI +def attach( + cluster_config_file, + start, + screen, + tmux, + cluster_name, + no_config_cache, + new, + port_forward, +): + """Create or attach to a SSH session to a Ray cluster.""" + port_forward = [(port, port) for port in list(port_forward)] + attach_cluster( + cluster_config_file, + start, + screen, + tmux, + cluster_name, + no_config_cache=no_config_cache, + new=new, + port_forward=port_forward, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.argument("source", required=False, type=str) +@click.argument("target", required=False, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@add_click_logging_options +def rsync_down(cluster_config_file, source, target, cluster_name): + """Download specific files from a Ray cluster.""" + rsync(cluster_config_file, source, target, cluster_name, down=True) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.argument("source", required=False, type=str) +@click.argument("target", required=False, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--all-nodes", + "-A", + is_flag=True, + required=False, + help="Upload to all nodes (workers and head).", +) +@add_click_logging_options +def rsync_up(cluster_config_file, source, target, cluster_name, all_nodes): + """Upload specific files to a Ray cluster.""" + if all_nodes: + cli_logger.warning( + "WARNING: the `all_nodes` option is deprecated and will be " + "removed in the future. " + "Rsync to worker nodes is not reliable since workers may be " + "added during autoscaling. Please use the `file_mounts` " + "feature instead for consistent file sync in autoscaling clusters" + ) + + rsync( + cluster_config_file, + source, + target, + cluster_name, + down=False, + all_nodes=all_nodes, + ) + + +@cli.command(context_settings={"ignore_unknown_options": True}) +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--stop", + is_flag=True, + default=False, + help="Stop the cluster after the command finishes running.", +) +@click.option( + "--start", is_flag=True, default=False, help="Start the cluster if needed." +) +@click.option( + "--screen", is_flag=True, default=False, help="Run the command in a screen." +) +@click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.") +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option( + "--port-forward", + "-p", + required=False, + multiple=True, + type=int, + help="Port to forward. Use this multiple times to forward multiple ports.", +) +@click.argument("script", required=True, type=str) +@click.option( + "--args", + required=False, + type=str, + help="(deprecated) Use '-- --arg1 --arg2' for script args.", +) +@click.argument("script_args", nargs=-1) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@click.option( + "--extra-screen-args", + default=None, + help="if screen is enabled, add the provided args to it. A useful example " + "usage scenario is passing --extra-screen-args='-Logfile /full/path/blah_log.txt'" + " as it redirects screen output also to a custom file", +) +@add_click_logging_options +def submit( + cluster_config_file, + screen, + tmux, + stop, + start, + cluster_name, + no_config_cache, + port_forward, + script, + args, + script_args, + disable_usage_stats, + extra_screen_args: Optional[str] = None, +): + """Uploads and runs a script on the specified cluster. + + The script is automatically synced to the following location: + + os.path.join("~", os.path.basename(script)) + + Example: + ray submit [CLUSTER.YAML] experiment.py -- --smoke-test + """ + cli_logger.doassert( + not (screen and tmux), + "`{}` and `{}` are incompatible.", + cf.bold("--screen"), + cf.bold("--tmux"), + ) + cli_logger.doassert( + not (script_args and args), + "`{0}` and `{1}` are incompatible. Use only `{1}`.\nExample: `{2}`", + cf.bold("--args"), + cf.bold("-- "), + cf.bold("ray submit script.py -- --arg=123 --flag"), + ) + + assert not (screen and tmux), "Can specify only one of `screen` or `tmux`." + assert not (script_args and args), "Use -- --arg1 --arg2 for script args." + + if (extra_screen_args is not None) and (not screen): + cli_logger.abort( + "To use extra_screen_args, it is required to use the --screen flag" + ) + + if args: + cli_logger.warning( + "`{}` is deprecated and will be removed in the future.", cf.bold("--args") + ) + cli_logger.warning( + "Use `{}` instead. Example: `{}`.", + cf.bold("-- "), + cf.bold("ray submit script.py -- --arg=123 --flag"), + ) + cli_logger.newline() + + if start: + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + + create_or_update_cluster( + config_file=cluster_config_file, + override_min_workers=None, + override_max_workers=None, + no_restart=False, + restart_only=False, + yes=True, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + redirect_command_output=False, + use_login_shells=True, + ) + target = os.path.basename(script) + target = os.path.join("~", target) + rsync( + cluster_config_file, + script, + target, + cluster_name, + no_config_cache=no_config_cache, + down=False, + ) + + command_parts = ["python", target] + if script_args: + command_parts += list(script_args) + elif args is not None: + command_parts += [args] + + port_forward = [(port, port) for port in list(port_forward)] + cmd = " ".join(command_parts) + exec_cluster( + cluster_config_file, + cmd=cmd, + run_env="docker", + screen=screen, + tmux=tmux, + stop=stop, + start=False, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + port_forward=port_forward, + extra_screen_args=extra_screen_args, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.argument("cmd", required=True, type=str) +@click.option( + "--run-env", + required=False, + type=click.Choice(RUN_ENV_TYPES), + default="auto", + help="Choose whether to execute this command in a container or directly on" + " the cluster head. Only applies when docker is configured in the YAML.", +) +@click.option( + "--stop", + is_flag=True, + default=False, + help="Stop the cluster after the command finishes running.", +) +@click.option( + "--start", is_flag=True, default=False, help="Start the cluster if needed." +) +@click.option( + "--screen", is_flag=True, default=False, help="Run the command in a screen." +) +@click.option("--tmux", is_flag=True, default=False, help="Run the command in tmux.") +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +@click.option( + "--no-config-cache", + is_flag=True, + default=False, + help="Disable the local cluster config cache.", +) +@click.option( + "--port-forward", + "-p", + required=False, + multiple=True, + type=int, + help="Port to forward. Use this multiple times to forward multiple ports.", +) +@click.option( + "--disable-usage-stats", + is_flag=True, + default=False, + help="If True, the usage stats collection will be disabled.", +) +@add_click_logging_options +def exec( + cluster_config_file, + cmd, + run_env, + screen, + tmux, + stop, + start, + cluster_name, + no_config_cache, + port_forward, + disable_usage_stats, +): + """Execute a command via SSH on a Ray cluster.""" + port_forward = [(port, port) for port in list(port_forward)] + + if start: + if disable_usage_stats: + usage_lib.set_usage_stats_enabled_via_env_var(False) + + exec_cluster( + cluster_config_file, + cmd=cmd, + run_env=run_env, + screen=screen, + tmux=tmux, + stop=stop, + start=start, + override_cluster_name=cluster_name, + no_config_cache=no_config_cache, + port_forward=port_forward, + _allow_uninitialized_state=True, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +def get_head_ip(cluster_config_file, cluster_name): + """Return the head node IP of a Ray cluster.""" + click.echo(get_head_node_ip(cluster_config_file, cluster_name)) + + +@cli.command() +@click.argument("cluster_config_file", required=True, type=str) +@click.option( + "--cluster-name", + "-n", + required=False, + type=str, + help="Override the configured cluster name.", +) +def get_worker_ips(cluster_config_file, cluster_name): + """Return the list of worker IPs of a Ray cluster.""" + worker_ips = get_worker_node_ips(cluster_config_file, cluster_name) + click.echo("\n".join(worker_ips)) + + +@cli.command() +def disable_usage_stats(): + """Disable usage stats collection. + + This will not affect the current running clusters + but clusters launched in the future. + """ + usage_lib.set_usage_stats_enabled_via_config(enabled=False) + print( + "Usage stats disabled for future clusters. " + "Restart any current running clusters for this to take effect." + ) + + +@cli.command() +def enable_usage_stats(): + """Enable usage stats collection. + + This will not affect the current running clusters + but clusters launched in the future. + """ + usage_lib.set_usage_stats_enabled_via_config(enabled=True) + print( + "Usage stats enabled for future clusters. " + "Restart any current running clusters for this to take effect." + ) + + +@cli.command() +def stack(): + """Take a stack dump of all Python workers on the local machine.""" + COMMAND = """ +pyspy=`which py-spy` +if [ ! -e "$pyspy" ]; then + echo "ERROR: Please 'pip install py-spy'" \ + "or 'pip install ray[default]' first." + exit 1 +fi +# Set IFS to iterate over lines instead of over words. +export IFS=" +" +# Call sudo to prompt for password before anything has been printed. +sudo true +workers=$( + ps aux | grep -E ' ray::|default_worker.py' | grep -v raylet | grep -v grep +) +for worker in $workers; do + echo "Stack dump for $worker"; + pid=`echo $worker | awk '{print $2}'`; + case "$(uname -s)" in + Linux*) native=--native;; + *) native=;; + esac + sudo $pyspy dump --pid $pid $native; + echo; +done + """ + subprocess.call(COMMAND, shell=True) + + +@cli.command() +def microbenchmark(): + """Run a local Ray microbenchmark on the current machine.""" + from ray._private.ray_perf import main + + main() + + +@cli.command() +@click.option( + "--address", + required=False, + type=str, + help="Override the Ray address to connect to.", +) +def timeline(address): + """Take a Chrome tracing timeline for a Ray cluster.""" + address = services.canonicalize_bootstrap_address_or_die(address) + logger.info(f"Connecting to Ray instance at {address}.") + ray.init(address=address) + time = datetime.today().strftime("%Y-%m-%d_%H-%M-%S") + filename = os.path.join( + ray._common.utils.get_user_temp_dir(), f"ray-timeline-{time}.json" + ) + ray.timeline(filename=filename) + size = os.path.getsize(filename) + logger.info(f"Trace file written to {filename} ({size} bytes).") + logger.info("You can open this with chrome://tracing in the Chrome browser.") + + +@cli.command() +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "--group-by", + type=click.Choice(["NODE_ADDRESS", "STACK_TRACE"]), + default="NODE_ADDRESS", + help="Group object references by a GroupByType \ +(e.g. NODE_ADDRESS or STACK_TRACE).", +) +@click.option( + "--sort-by", + type=click.Choice(["PID", "OBJECT_SIZE", "REFERENCE_TYPE"]), + default="OBJECT_SIZE", + help="Sort object references in ascending order by a SortingType \ +(e.g. PID, OBJECT_SIZE, or REFERENCE_TYPE).", +) +@click.option( + "--units", + type=click.Choice(["B", "KB", "MB", "GB"]), + default="B", + help="Specify unit metrics for displaying object sizes \ +(e.g. B, KB, MB, GB).", +) +@click.option( + "--no-format", + is_flag=True, + type=bool, + default=True, + help="Display unformatted results. Defaults to true when \ +terminal width is less than 137 characters.", +) +@click.option( + "--stats-only", is_flag=True, default=False, help="Display plasma store stats only." +) +@click.option( + "--num-entries", + "--n", + type=int, + default=None, + help="Specify number of sorted entries per group.", +) +def memory( + address, + group_by, + sort_by, + units, + no_format, + stats_only, + num_entries, +): + """Print object references held in a Ray cluster.""" + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = ray._raylet.GcsClient(address=address) + _check_ray_version(gcs_client) + time = datetime.now() + header = "=" * 8 + f" Object references status: {time} " + "=" * 8 + mem_stats = memory_summary( + address, + group_by, + sort_by, + units, + no_format, + stats_only, + num_entries, + ) + print(f"{header}\n{mem_stats}") + + +@cli.command() +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "-v", + "--verbose", + required=False, + is_flag=True, + hidden=True, + help="Experimental: Display additional debuggging information.", +) +@PublicAPI +def status(address: str, verbose: bool): + """Print cluster status, including autoscaling info.""" + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = ray._raylet.GcsClient(address=address) + _check_ray_version(gcs_client) + ray.experimental.internal_kv._initialize_internal_kv(gcs_client) + status = gcs_client.internal_kv_get(ray_constants.DEBUG_AUTOSCALING_STATUS.encode()) + error = gcs_client.internal_kv_get(ray_constants.DEBUG_AUTOSCALING_ERROR.encode()) + print(debug_status(status, error, verbose=verbose, address=address)) + + +@cli.command(hidden=True) +@click.option( + "--stream", + "-S", + required=False, + type=bool, + is_flag=True, + default=False, + help="If True, will stream the binary archive contents to stdout", +) +@click.option( + "--output", "-o", required=False, type=str, default=None, help="Output file." +) +@click.option( + "--logs/--no-logs", + is_flag=True, + default=True, + help="Collect logs from ray session dir", +) +@click.option( + "--debug-state/--no-debug-state", + is_flag=True, + default=True, + help="Collect debug_state.txt from ray session dir", +) +@click.option( + "--pip/--no-pip", is_flag=True, default=True, help="Collect installed pip packages" +) +@click.option( + "--processes/--no-processes", + is_flag=True, + default=True, + help="Collect info on running processes", +) +@click.option( + "--processes-verbose/--no-processes-verbose", + is_flag=True, + default=True, + help="Increase process information verbosity", +) +@click.option( + "--tempfile", + "-T", + required=False, + type=str, + default=None, + help="Temporary file to use", +) +def local_dump( + stream: bool = False, + output: Optional[str] = None, + logs: bool = True, + debug_state: bool = True, + pip: bool = True, + processes: bool = True, + processes_verbose: bool = False, + tempfile: Optional[str] = None, +): + """Collect local data and package into an archive. + + Usage: + + ray local-dump [--stream/--output file] + + This script is called on remote nodes to fetch their data. + """ + # This may stream data to stdout, so no printing here + get_local_dump_archive( + stream=stream, + output=output, + logs=logs, + debug_state=debug_state, + pip=pip, + processes=processes, + processes_verbose=processes_verbose, + tempfile=tempfile, + ) + + +@cli.command() +@click.argument("cluster_config_file", required=False, type=str) +@click.option( + "--host", + "-h", + required=False, + type=str, + help="Single or list of hosts, separated by comma.", +) +@click.option( + "--ssh-user", + "-U", + required=False, + type=str, + default=None, + help="Username of the SSH user.", +) +@click.option( + "--ssh-key", + "-K", + required=False, + type=str, + default=None, + help="Path to the SSH key file.", +) +@click.option( + "--docker", + "-d", + required=False, + type=str, + default=None, + help="Name of the docker container, if applicable.", +) +@click.option( + "--local", + "-L", + required=False, + type=bool, + is_flag=True, + default=None, + help="Also include information about the local node.", +) +@click.option( + "--output", "-o", required=False, type=str, default=None, help="Output file." +) +@click.option( + "--logs/--no-logs", + is_flag=True, + default=True, + help="Collect logs from ray session dir", +) +@click.option( + "--debug-state/--no-debug-state", + is_flag=True, + default=True, + help="Collect debug_state.txt from ray log dir", +) +@click.option( + "--pip/--no-pip", is_flag=True, default=True, help="Collect installed pip packages" +) +@click.option( + "--processes/--no-processes", + is_flag=True, + default=True, + help="Collect info on running processes", +) +@click.option( + "--processes-verbose/--no-processes-verbose", + is_flag=True, + default=True, + help="Increase process information verbosity", +) +@click.option( + "--tempfile", + "-T", + required=False, + type=str, + default=None, + help="Temporary file to use", +) +def cluster_dump( + cluster_config_file: Optional[str] = None, + host: Optional[str] = None, + ssh_user: Optional[str] = None, + ssh_key: Optional[str] = None, + docker: Optional[str] = None, + local: Optional[bool] = None, + output: Optional[str] = None, + logs: bool = True, + debug_state: bool = True, + pip: bool = True, + processes: bool = True, + processes_verbose: bool = False, + tempfile: Optional[str] = None, +): + """Get log data from one or more nodes. + + Best used with Ray cluster configs: + + ray cluster-dump [cluster.yaml] + + Include the --local flag to also collect and include data from the + local node. + + Missing fields will be tried to be auto-filled. + + You can also manually specify a list of hosts using the + ``--host `` parameter. + """ + archive_path = get_cluster_dump_archive( + cluster_config_file=cluster_config_file, + host=host, + ssh_user=ssh_user, + ssh_key=ssh_key, + docker=docker, + local=local, + output=output, + logs=logs, + debug_state=debug_state, + pip=pip, + processes=processes, + processes_verbose=processes_verbose, + tempfile=tempfile, + ) + if archive_path: + click.echo(f"Created archive: {archive_path}") + else: + click.echo("Could not create archive.") + + +@cli.command(hidden=True) +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +def global_gc(address): + """Trigger Python garbage collection on all cluster workers.""" + ray.init(address=address) + ray._private.internal_api.global_gc() + print("Triggered gc.collect() on all workers.") + + +@cli.command(hidden=True) +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "--node-id", + required=False, + type=str, + help="Hex ID of the worker node to be drained. Will default to current node if not provided.", +) +@click.option( + "--reason", + required=True, + type=click.Choice( + [ + item[0] + for item in autoscaler_pb2.DrainNodeReason.items() + if item[1] != autoscaler_pb2.DRAIN_NODE_REASON_UNSPECIFIED + ] + ), + help="The reason why the node will be drained.", +) +@click.option( + "--reason-message", + required=True, + type=str, + help="The detailed drain reason message.", +) +@click.option( + "--deadline-remaining-seconds", + required=False, + type=int, + default=None, + help="Inform GCS that the node to be drained will be force killed " + "after this many of seconds. " + "Default is None which means there is no deadline. " + "Note: This command doesn't actually force kill the node after the deadline, " + "it's the caller's responsibility to do that.", +) +def drain_node( + address: str, + node_id: str, + reason: str, + reason_message: str, + deadline_remaining_seconds: int, +): + """ + This is NOT a public API. + + Manually drain a worker node. + """ + # This should be before get_runtime_context() so get_runtime_context() + # doesn't start a new worker here. + address = services.canonicalize_bootstrap_address_or_die(address) + + if node_id is None: + node_id = ray.get_runtime_context().get_node_id() + deadline_timestamp_ms = 0 + if deadline_remaining_seconds is not None: + if deadline_remaining_seconds < 0: + raise click.BadParameter( + "--deadline-remaining-seconds cannot be negative, " + f"got {deadline_remaining_seconds}" + ) + deadline_timestamp_ms = (time.time_ns() // 1000000) + ( + deadline_remaining_seconds * 1000 + ) + + if ray.NodeID.from_hex(node_id) == ray.NodeID.nil(): + raise click.BadParameter(f"Invalid hex ID of a Ray node, got {node_id}") + + gcs_client = ray._raylet.GcsClient(address=address) + _check_ray_version(gcs_client) + is_accepted, rejection_error_message = gcs_client.drain_node( + node_id, + autoscaler_pb2.DrainNodeReason.Value(reason), + reason_message, + deadline_timestamp_ms, + ) + + if not is_accepted: + raise click.ClickException( + f"The drain request is not accepted: {rejection_error_message}" + ) + + +@cli.command(name="kuberay-autoscaler", hidden=True) +@click.option( + "--cluster-name", + required=True, + type=str, + help="The name of the Ray Cluster.\n" + "Should coincide with the `metadata.name` of the RayCluster CR.", +) +@click.option( + "--cluster-namespace", + required=True, + type=str, + help="The Kubernetes namespace the Ray Cluster lives in.\n" + "Should coincide with the `metadata.namespace` of the RayCluster CR.", +) +def kuberay_autoscaler(cluster_name: str, cluster_namespace: str) -> None: + """Runs the autoscaler for a Ray cluster managed by the KubeRay operator. + + `ray kuberay-autoscaler` is meant to be used as an entry point in + KubeRay cluster configs. + `ray kuberay-autoscaler` is NOT a public CLI. + """ + # Delay import to avoid introducing Ray core dependency on the Python Kubernetes + # client. + from ray.autoscaler._private.kuberay.run_autoscaler import run_kuberay_autoscaler + + run_kuberay_autoscaler(cluster_name, cluster_namespace) + + +@cli.command(name="health-check", hidden=True) +@click.option( + "--address", required=False, type=str, help="Override the address to connect to." +) +@click.option( + "--component", + required=False, + type=str, + help="Health check for a specific component. Currently supports: " + "[ray_client_server]", +) +@click.option( + "--skip-version-check", + is_flag=True, + default=False, + help="Skip comparison of GCS version with local Ray version.", +) +def healthcheck(address, component, skip_version_check): + """ + This is NOT a public API. + + Health check a Ray or a specific component. Exit code 0 is healthy. + """ + + address = services.canonicalize_bootstrap_address_or_die(address) + gcs_client = ray._raylet.GcsClient(address=address) + if not skip_version_check: + _check_ray_version(gcs_client) + + if not component: + sys.exit(0) + + report_str = gcs_client.internal_kv_get( + component.encode(), namespace=ray_constants.KV_NAMESPACE_HEALTHCHECK + ) + if not report_str: + # Status was never updated + sys.exit(1) + + report = json.loads(report_str) + + # TODO (Alex): We probably shouldn't rely on time here, but cloud providers + # have very well synchronized NTP servers, so this should be fine in + # practice. + cur_time = time.time() + report_time = float(report["time"]) + + # If the status is too old, the service has probably already died. + delta = cur_time - report_time + time_ok = delta < ray._private.ray_constants.HEALTHCHECK_EXPIRATION_S + + if time_ok: + sys.exit(0) + else: + sys.exit(1) + + +@cli.command() +@click.option("-v", "--verbose", is_flag=True) +@click.option( + "--dryrun", + is_flag=True, + help="Identifies the wheel but does not execute the installation.", +) +def install_nightly(verbose, dryrun): + """Install the latest wheels for Ray. + + This uses the same python environment as the one that Ray is currently + installed in. Make sure that there is no Ray processes on this + machine (ray stop) when running this command. + """ + raydir = os.path.abspath(os.path.dirname(ray.__file__)) + all_wheels_path = os.path.join(raydir, "nightly-wheels.yaml") + + wheels = None + if os.path.exists(all_wheels_path): + with open(all_wheels_path) as f: + wheels = yaml.safe_load(f) + + if not wheels: + raise click.ClickException( + f"Wheels not found in '{all_wheels_path}'! " + "Please visit https://docs.ray.io/en/master/installation.html to " + "obtain the latest wheels." + ) + + platform = sys.platform + py_version = "{0}.{1}".format(*sys.version_info[:2]) + + matching_wheel = None + for target_platform, wheel_map in wheels.items(): + if verbose: + print(f"Evaluating os={target_platform}, python={list(wheel_map)}") + if platform.startswith(target_platform): + if py_version in wheel_map: + matching_wheel = wheel_map[py_version] + break + if verbose: + print("Not matched.") + + if matching_wheel is None: + raise click.ClickException( + "Unable to identify a matching platform. " + "Please visit https://docs.ray.io/en/master/installation.html to " + "obtain the latest wheels." + ) + if dryrun: + print(f"Found wheel: {matching_wheel}") + else: + cmd = [sys.executable, "-m", "pip", "install", "-U", matching_wheel] + print(f"Running: {' '.join(cmd)}.") + subprocess.check_call(cmd) + + +@cli.command() +@click.option( + "--show-library-path", + "-show", + required=False, + is_flag=True, + help="Show the cpp include path and library path, if provided.", +) +@click.option( + "--generate-bazel-project-template-to", + "-gen", + required=False, + type=str, + help="The directory to generate the bazel project template to, if provided.", +) +@add_click_logging_options +def cpp(show_library_path, generate_bazel_project_template_to): + """Show the cpp library path and generate the bazel project template.""" + if sys.platform == "win32": + cli_logger.error("Ray C++ API is not supported on Windows currently.") + sys.exit(1) + if not show_library_path and not generate_bazel_project_template_to: + raise ValueError( + "Please input at least one option of '--show-library-path'" + " and '--generate-bazel-project-template-to'." + ) + raydir = os.path.abspath(os.path.dirname(ray.__file__)) + cpp_dir = os.path.join(raydir, "cpp") + cpp_templete_dir = os.path.join(cpp_dir, "example") + include_dir = os.path.join(cpp_dir, "include") + lib_dir = os.path.join(cpp_dir, "lib") + if not os.path.isdir(cpp_dir): + raise ValueError('Please install ray with C++ API by "pip install ray[cpp]".') + if show_library_path: + cli_logger.print("Ray C++ include path {} ", cf.bold(f"{include_dir}")) + cli_logger.print("Ray C++ library path {} ", cf.bold(f"{lib_dir}")) + if generate_bazel_project_template_to: + # copytree expects that the dst dir doesn't exist + # so we manually delete it if it exists. + if os.path.exists(generate_bazel_project_template_to): + shutil.rmtree(generate_bazel_project_template_to) + shutil.copytree(cpp_templete_dir, generate_bazel_project_template_to) + out_include_dir = os.path.join( + generate_bazel_project_template_to, "thirdparty/include" + ) + if os.path.exists(out_include_dir): + shutil.rmtree(out_include_dir) + shutil.copytree(include_dir, out_include_dir) + out_lib_dir = os.path.join(generate_bazel_project_template_to, "thirdparty/lib") + if os.path.exists(out_lib_dir): + shutil.rmtree(out_lib_dir) + shutil.copytree(lib_dir, out_lib_dir) + + cli_logger.print( + "Project template generated to {}", + cf.bold(f"{os.path.abspath(generate_bazel_project_template_to)}"), + ) + cli_logger.print("To build and run this template, run") + cli_logger.print( + cf.bold( + f" cd {os.path.abspath(generate_bazel_project_template_to)}" + " && bash run.sh" + ) + ) + + +@click.group(name="metrics") +def metrics_group(): + pass + + +@metrics_group.command(name="launch-prometheus") +def launch_prometheus(): + install_and_start_prometheus.main() + + +@metrics_group.command(name="shutdown-prometheus") +def shutdown_prometheus(): + try: + requests.post("http://localhost:9090/-/quit") + except requests.exceptions.RequestException as e: + print(f"An error occurred: {e}") + sys.exit(1) + + +def add_command_alias(command, name, hidden): + new_command = copy.deepcopy(command) + new_command.hidden = hidden + cli.add_command(new_command, name=name) + + +cli.add_command(dashboard) +cli.add_command(debug) +cli.add_command(start) +cli.add_command(stop) +cli.add_command(up) +add_command_alias(up, name="create_or_update", hidden=True) +cli.add_command(attach) +cli.add_command(exec) +add_command_alias(exec, name="exec_cmd", hidden=True) +add_command_alias(rsync_down, name="rsync_down", hidden=True) +add_command_alias(rsync_up, name="rsync_up", hidden=True) +cli.add_command(submit) +cli.add_command(down) +add_command_alias(down, name="teardown", hidden=True) +cli.add_command(kill_random_node) +add_command_alias(get_head_ip, name="get_head_ip", hidden=True) +cli.add_command(get_worker_ips) +cli.add_command(microbenchmark) +cli.add_command(stack) +cli.add_command(status) +cli.add_command(memory) +cli.add_command(local_dump) +cli.add_command(cluster_dump) +cli.add_command(global_gc) +cli.add_command(timeline) +cli.add_command(install_nightly) +cli.add_command(cpp) +cli.add_command(disable_usage_stats) +cli.add_command(enable_usage_stats) +cli.add_command(metrics_group) +cli.add_command(drain_node) +cli.add_command(check_open_ports) + +try: + from ray.util.state.state_cli import ( + ray_get, + ray_list, + logs_state_cli_group, + summary_state_cli_group, + ) + + cli.add_command(ray_list, name="list") + cli.add_command(ray_get, name="get") + add_command_alias(summary_state_cli_group, name="summary", hidden=False) + add_command_alias(logs_state_cli_group, name="logs", hidden=False) +except ImportError as e: + logger.debug(f"Integrating ray state command line tool failed: {e}") + + +try: + from ray.dashboard.modules.job.cli import job_cli_group + + add_command_alias(job_cli_group, name="job", hidden=False) +except Exception as e: + logger.debug(f"Integrating ray jobs command line tool failed with {e}") + + +try: + from ray.serve.scripts import serve_cli + + cli.add_command(serve_cli) +except Exception as e: + logger.debug(f"Integrating ray serve command line tool failed with {e}") + + +def main(): + return cli() + + +if __name__ == "__main__": + main() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0d5b38cf84feb7b5fd1a89577345a6481cffff31 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/__init__.py @@ -0,0 +1,63 @@ +import ray._private.worker + +try: + from ray.serve._private.logging_utils import configure_default_serve_logger + from ray.serve.api import ( + Application, + Deployment, + RunTarget, + _run, + _run_many, + delete, + deployment, + get_app_handle, + get_deployment_handle, + get_multiplexed_model_id, + get_replica_context, + ingress, + multiplexed, + run, + run_many, + shutdown, + start, + status, + ) + from ray.serve.batching import batch + from ray.serve.config import HTTPOptions + +except ModuleNotFoundError as e: + e.msg += ( + '. You can run `pip install "ray[serve]"` to install all Ray Serve' + " dependencies." + ) + raise e + +# Setup default ray.serve logger to ensure all serve module logs are captured. +configure_default_serve_logger() + +# Mute the warning because Serve sometimes intentionally calls +# ray.get inside async actors. +ray._private.worker.blocking_get_inside_async_warned = True + +__all__ = [ + "_run", + "_run_many", + "batch", + "start", + "HTTPOptions", + "get_replica_context", + "shutdown", + "ingress", + "deployment", + "run", + "run_many", + "RunTarget", + "delete", + "Application", + "Deployment", + "multiplexed", + "get_multiplexed_model_id", + "status", + "get_app_handle", + "get_deployment_handle", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a6d3799d169d53bcc1bd4f8922319f015f801a6a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/_private/__pycache__/deployment_state.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:409f71e11a076cf4d81d3a618df9392d767c2c05a57c17eb207b108b5e3edc18 +size 129940 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/api.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/api.py new file mode 100644 index 0000000000000000000000000000000000000000..865d5cedbba1b5aedce1225a517958ad5c18cbb8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/api.py @@ -0,0 +1,1057 @@ +import collections +import inspect +import logging +from functools import wraps +from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union + +from attr import dataclass +from fastapi import APIRouter, FastAPI +from starlette.types import ASGIApp + +import ray +from ray import cloudpickle +from ray._private.serialization import pickle_dumps +from ray.serve._private.build_app import build_app +from ray.serve._private.config import ( + DeploymentConfig, + ReplicaConfig, + handle_num_replicas_auto, +) +from ray.serve._private.constants import ( + RAY_SERVE_FORCE_LOCAL_TESTING_MODE, + SERVE_DEFAULT_APP_NAME, + SERVE_LOGGER_NAME, +) +from ray.serve._private.http_util import ( + ASGIAppReplicaWrapper, + make_fastapi_class_based_view, +) +from ray.serve._private.local_testing_mode import make_local_deployment_handle +from ray.serve._private.logging_utils import configure_component_logger +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + DEFAULT, + Default, + ensure_serialization_context, + extract_self_if_method_call, + validate_route_prefix, + wait_for_interrupt, +) +from ray.serve.config import ( + AutoscalingConfig, + DeploymentMode, + HTTPOptions, + ProxyLocation, + RequestRouterConfig, + gRPCOptions, +) +from ray.serve.context import ( + ReplicaContext, + _get_global_client, + _get_internal_replica_context, + _set_global_client, +) +from ray.serve.deployment import Application, Deployment +from ray.serve.exceptions import RayServeException +from ray.serve.handle import DeploymentHandle +from ray.serve.multiplex import _ModelMultiplexWrapper +from ray.serve.schema import LoggingConfig, ServeInstanceDetails, ServeStatus +from ray.util.annotations import DeveloperAPI, PublicAPI + +from ray.serve._private import api as _private_api # isort:skip + + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="stable") +def start( + proxy_location: Union[None, str, ProxyLocation] = None, + http_options: Union[None, dict, HTTPOptions] = None, + grpc_options: Union[None, dict, gRPCOptions] = None, + logging_config: Union[None, dict, LoggingConfig] = None, + **kwargs, +): + """Start Serve on the cluster. + + Used to set cluster-scoped configurations such as HTTP options. In most cases, this + does not need to be called manually and Serve will be started when an application is + first deployed to the cluster. + + These cluster-scoped options cannot be updated dynamically. To update them, start a + new cluster or shut down Serve on the cluster and start it again. + + These options can also be set in the config file deployed via REST API. + + Args: + proxy_location: Where to run proxies that handle ingress traffic to the + cluster (defaults to every node in the cluster with at least one replica on + it). See `ProxyLocation` for supported options. + http_options: HTTP config options for the proxies. These can be passed as an + unstructured dictionary or the structured `HTTPOptions` class. See + `HTTPOptions` for supported options. + grpc_options: [EXPERIMENTAL] gRPC config options for the proxies. These can + be passed as an unstructured dictionary or the structured `gRPCOptions` + class See `gRPCOptions` for supported options. + logging_config: logging config options for the serve component ( + controller & proxy). + """ + if proxy_location is None: + if http_options is None: + http_options = HTTPOptions(location=DeploymentMode.EveryNode) + else: + if http_options is None: + http_options = HTTPOptions() + elif isinstance(http_options, dict): + http_options = HTTPOptions(**http_options) + + if isinstance(proxy_location, str): + proxy_location = ProxyLocation(proxy_location) + + http_options.location = ProxyLocation._to_deployment_mode(proxy_location) + + _private_api.serve_start( + http_options=http_options, + grpc_options=grpc_options, + global_logging_config=logging_config, + **kwargs, + ) + + +@PublicAPI(stability="stable") +def shutdown(): + """Completely shut down Serve on the cluster. + + Deletes all applications and shuts down Serve system actors. + """ + + try: + client = _get_global_client() + except RayServeException: + logger.info( + "Nothing to shut down. There's no Serve application " + "running on this Ray cluster." + ) + return + + client.shutdown() + _set_global_client(None) + + +@DeveloperAPI +def get_replica_context() -> ReplicaContext: + """Returns the deployment and replica tag from within a replica at runtime. + + A replica tag uniquely identifies a single replica for a Ray Serve + deployment. + + Raises: + RayServeException: if not called from within a Ray Serve deployment. + + Example: + + .. code-block:: python + + from ray import serve + @serve.deployment + class MyDeployment: + def __init__(self): + # Prints "MyDeployment" + print(serve.get_replica_context().deployment) + + """ + internal_replica_context = _get_internal_replica_context() + if internal_replica_context is None: + raise RayServeException( + "`serve.get_replica_context()` " + "may only be called from within a " + "Ray Serve deployment." + ) + return internal_replica_context + + +@PublicAPI(stability="stable") +def ingress(app: Union[ASGIApp, Callable]) -> Callable: + """Wrap a deployment class with an ASGI application for HTTP request parsing. + There are a few different ways to use this functionality. + + Example: + + FastAPI app routes are defined inside the deployment class. + + .. code-block:: python + + from ray import serve + from fastapi import FastAPI + + app = FastAPI() + + @serve.deployment + @serve.ingress(app) + class MyFastAPIDeployment: + @app.get("/hi") + def say_hi(self) -> str: + return "Hello world!" + + app = MyFastAPIDeployment.bind() + + You can also use a standalone FastAPI app without registering + routes inside the deployment. + + .. code-block:: python + + from ray import serve + from fastapi import FastAPI + + app = FastAPI() + + @app.get("/hi") + def say_hi(): + return "Hello world!" + + deployment = serve.deployment(serve.ingress(app)()) + app = deployment.bind() + + You can also pass in a builder function that returns an ASGI app. + The builder function is evaluated when the deployment is initialized on + replicas. This example shows how to use a sub-deployment inside the routes + defined outside the deployment class. + + .. code-block:: python + + from ray import serve + + @serve.deployment + class SubDeployment: + def __call__(self): + return "Hello world!" + + def build_asgi_app(): + from fastapi import FastAPI + + app = FastAPI() + + def get_sub_deployment_handle(): + return serve.get_deployment_handle(SubDeployment.name, app_name="my_app") + + @app.get("/hi") + async def say_hi(handle: Depends(get_sub_deployment_handle)): + return await handle.remote() + + return app + + deployment = serve.deployment(serve.ingress(build_asgi_app)()) + app = deployment.bind(SubDeployment.bind(), name="my_app", route_prefix="/") + + Args: + app: the FastAPI app to wrap this class with. + Can be any ASGI-compatible callable. + You can also pass in a builder function that returns an ASGI app. + """ + + def decorator(cls: Optional[Type[Any]] = None) -> Callable: + if cls is None: + + class ASGIIngressDeployment: + def __init__(self, *args, **kwargs): + self.args = args + self.kwargs = kwargs + + cls = ASGIIngressDeployment + + if not inspect.isclass(cls): + raise ValueError("@serve.ingress must be used with a class.") + if issubclass(cls, collections.abc.Callable): + raise ValueError( + "Classes passed to @serve.ingress may not have __call__ method." + ) + + # Sometimes there are decorators on the methods. We want to fix + # the fast api routes here. + if isinstance(app, (FastAPI, APIRouter)): + make_fastapi_class_based_view(app, cls) + + frozen_app_or_func: Union[ASGIApp, Callable] = None + + if inspect.isfunction(app): + frozen_app_or_func = app + else: + # Free the state of the app so subsequent modification won't affect + # this ingress deployment. We don't use copy.copy here to avoid + # recursion issue. + ensure_serialization_context() + frozen_app_or_func = cloudpickle.loads( + pickle_dumps(app, error_msg="Failed to serialize the ASGI app.") + ) + + class ASGIIngressWrapper(cls, ASGIAppReplicaWrapper): + def __init__(self, *args, **kwargs): + # Call user-defined constructor. + cls.__init__(self, *args, **kwargs) + + ServeUsageTag.FASTAPI_USED.record("1") + ASGIAppReplicaWrapper.__init__(self, frozen_app_or_func) + + async def __del__(self): + await ASGIAppReplicaWrapper.__del__(self) + + # Call user-defined destructor if defined. + if hasattr(cls, "__del__"): + if inspect.iscoroutinefunction(cls.__del__): + await cls.__del__(self) + else: + cls.__del__(self) + + ASGIIngressWrapper.__name__ = cls.__name__ + if hasattr(frozen_app_or_func, "docs_url"): + # TODO (abrar): fastapi apps instantiated by builder function will set + # the docs path on application state via the replica. + # This split in logic is not desirable, we should consolidate the two. + ASGIIngressWrapper.__fastapi_docs_path__ = frozen_app_or_func.docs_url + + return ASGIIngressWrapper + + return decorator + + +@PublicAPI(stability="stable") +def deployment( + _func_or_class: Optional[Callable] = None, + name: Default[str] = DEFAULT.VALUE, + version: Default[str] = DEFAULT.VALUE, + num_replicas: Default[Optional[Union[int, str]]] = DEFAULT.VALUE, + route_prefix: Default[Union[str, None]] = DEFAULT.VALUE, + ray_actor_options: Default[Dict] = DEFAULT.VALUE, + placement_group_bundles: Default[List[Dict[str, float]]] = DEFAULT.VALUE, + placement_group_strategy: Default[str] = DEFAULT.VALUE, + max_replicas_per_node: Default[int] = DEFAULT.VALUE, + user_config: Default[Optional[Any]] = DEFAULT.VALUE, + max_ongoing_requests: Default[int] = DEFAULT.VALUE, + max_queued_requests: Default[int] = DEFAULT.VALUE, + autoscaling_config: Default[Union[Dict, AutoscalingConfig, None]] = DEFAULT.VALUE, + graceful_shutdown_wait_loop_s: Default[float] = DEFAULT.VALUE, + graceful_shutdown_timeout_s: Default[float] = DEFAULT.VALUE, + health_check_period_s: Default[float] = DEFAULT.VALUE, + health_check_timeout_s: Default[float] = DEFAULT.VALUE, + logging_config: Default[Union[Dict, LoggingConfig, None]] = DEFAULT.VALUE, + request_router_config: Default[ + Union[Dict, RequestRouterConfig, None] + ] = DEFAULT.VALUE, +) -> Callable[[Callable], Deployment]: + """Decorator that converts a Python class to a `Deployment`. + + Example: + + .. code-block:: python + + from ray import serve + + @serve.deployment(num_replicas=2) + class MyDeployment: + pass + + app = MyDeployment.bind() + + Args: + _func_or_class: The class or function to be decorated. + name: Name uniquely identifying this deployment within the application. + If not provided, the name of the class or function is used. + version: Version of the deployment. Deprecated. + num_replicas: Number of replicas to run that handle requests to + this deployment. Defaults to 1. + route_prefix: Route prefix for HTTP requests. Defaults to '/'. Deprecated. + ray_actor_options: Options to pass to the Ray Actor decorator, such as + resource requirements. Valid options are: `accelerator_type`, `memory`, + `num_cpus`, `num_gpus`, `resources`, and `runtime_env`. + placement_group_bundles: Defines a set of placement group bundles to be + scheduled *for each replica* of this deployment. The replica actor will + be scheduled in the first bundle provided, so the resources specified in + `ray_actor_options` must be a subset of the first bundle's resources. All + actors and tasks created by the replica actor will be scheduled in the + placement group by default (`placement_group_capture_child_tasks` is set + to True). + This cannot be set together with max_replicas_per_node. + placement_group_strategy: Strategy to use for the replica placement group + specified via `placement_group_bundles`. Defaults to `PACK`. + max_replicas_per_node: The max number of replicas of this deployment that can + run on a single node. Valid values are None (default, no limit) + or an integer in the range of [1, 100]. + This cannot be set together with placement_group_bundles. + user_config: Config to pass to the reconfigure method of the deployment. This + can be updated dynamically without restarting the replicas of the + deployment. The user_config must be fully JSON-serializable. + max_ongoing_requests: Maximum number of requests that are sent to a + replica of this deployment without receiving a response. Defaults to 5. + max_queued_requests: [EXPERIMENTAL] Maximum number of requests to this + deployment that will be queued at each *caller* (proxy or DeploymentHandle). + Once this limit is reached, subsequent requests will raise a + BackPressureError (for handles) or return an HTTP 503 status code (for HTTP + requests). Defaults to -1 (no limit). + autoscaling_config: Parameters to configure autoscaling behavior. If this + is set, `num_replicas` should be "auto" or not set. + graceful_shutdown_wait_loop_s: Duration that replicas wait until there is + no more work to be done before shutting down. Defaults to 2s. + graceful_shutdown_timeout_s: Duration to wait for a replica to gracefully + shut down before being forcefully killed. Defaults to 20s. + health_check_period_s: Duration between health check calls for the replica. + Defaults to 10s. The health check is by default a no-op Actor call to the + replica, but you can define your own health check using the "check_health" + method in your deployment that raises an exception when unhealthy. + health_check_timeout_s: Duration in seconds, that replicas wait for a health + check method to return before considering it as failed. Defaults to 30s. + logging_config: Logging config options for the deployment. If provided, + the config will be used to set up the Serve logger on the deployment. + request_router_config: Config for the request router used for this deployment. + Returns: + `Deployment` + """ + if route_prefix is not DEFAULT.VALUE: + raise ValueError( + "`route_prefix` can no longer be specified at the deployment level. " + "Pass it to `serve.run` or in the application config instead." + ) + + if max_ongoing_requests is None: + raise ValueError("`max_ongoing_requests` must be non-null, got None.") + + if num_replicas == "auto": + num_replicas = None + max_ongoing_requests, autoscaling_config = handle_num_replicas_auto( + max_ongoing_requests, autoscaling_config + ) + + ServeUsageTag.AUTO_NUM_REPLICAS_USED.record("1") + + # NOTE: The user_configured_option_names should be the first thing that's + # defined in this function. It depends on the locals() dictionary storing + # only the function args/kwargs. + # Create list of all user-configured options from keyword args + user_configured_option_names = [ + option + for option, value in locals().items() + if option != "_func_or_class" and value is not DEFAULT.VALUE + ] + + # Num of replicas should not be 0. + # TODO(Sihan) separate num_replicas attribute from internal and api + if num_replicas == 0: + raise ValueError("num_replicas is expected to larger than 0") + + if num_replicas not in [DEFAULT.VALUE, None, "auto"] and autoscaling_config not in [ + DEFAULT.VALUE, + None, + ]: + raise ValueError( + "Manually setting num_replicas is not allowed when " + "autoscaling_config is provided." + ) + + if version is not DEFAULT.VALUE: + logger.warning( + "DeprecationWarning: `version` in `@serve.deployment` has been deprecated. " + "Explicitly specifying version will raise an error in the future!" + ) + + if isinstance(logging_config, LoggingConfig): + logging_config = logging_config.dict() + + deployment_config = DeploymentConfig.from_default( + num_replicas=num_replicas if num_replicas is not None else 1, + user_config=user_config, + max_ongoing_requests=max_ongoing_requests, + max_queued_requests=max_queued_requests, + autoscaling_config=autoscaling_config, + graceful_shutdown_wait_loop_s=graceful_shutdown_wait_loop_s, + graceful_shutdown_timeout_s=graceful_shutdown_timeout_s, + health_check_period_s=health_check_period_s, + health_check_timeout_s=health_check_timeout_s, + logging_config=logging_config, + request_router_config=request_router_config, + ) + deployment_config.user_configured_option_names = set(user_configured_option_names) + + def decorator(_func_or_class): + replica_config = ReplicaConfig.create( + _func_or_class, + init_args=None, + init_kwargs=None, + ray_actor_options=( + ray_actor_options if ray_actor_options is not DEFAULT.VALUE else None + ), + placement_group_bundles=( + placement_group_bundles + if placement_group_bundles is not DEFAULT.VALUE + else None + ), + placement_group_strategy=( + placement_group_strategy + if placement_group_strategy is not DEFAULT.VALUE + else None + ), + max_replicas_per_node=( + max_replicas_per_node + if max_replicas_per_node is not DEFAULT.VALUE + else None + ), + ) + + return Deployment( + name if name is not DEFAULT.VALUE else _func_or_class.__name__, + deployment_config, + replica_config, + version=(version if version is not DEFAULT.VALUE else None), + _internal=True, + ) + + # This handles both parametrized and non-parametrized usage of the + # decorator. See the @serve.batch code for more details. + return decorator(_func_or_class) if callable(_func_or_class) else decorator + + +@DeveloperAPI +@dataclass(frozen=True) +class RunTarget: + """Represents a Serve application to run for `serve.run_many`.""" + + target: Application + name: str = SERVE_DEFAULT_APP_NAME + route_prefix: Optional[str] = "/" + logging_config: Optional[Union[Dict, LoggingConfig]] = None + + +@DeveloperAPI +def _run_many( + targets: Sequence[RunTarget], + wait_for_ingress_deployment_creation: bool = True, + wait_for_applications_running: bool = True, + _local_testing_mode: bool = False, +) -> List[DeploymentHandle]: + """Run many applications and return the handles to their ingress deployments. + + This is only used internally with the _blocking not totally blocking the following + code indefinitely until Ctrl-C'd. + """ + if not targets: + raise ValueError("No applications provided.") + + if RAY_SERVE_FORCE_LOCAL_TESTING_MODE: + if not _local_testing_mode: + logger.info("Overriding local_testing_mode=True from environment variable.") + + _local_testing_mode = True + + built_apps = [] + for t in targets: + if len(t.name) == 0: + raise RayServeException("Application name must a non-empty string.") + + if not isinstance(t.target, Application): + raise TypeError( + "`serve.run` expects an `Application` returned by `Deployment.bind()`." + ) + + validate_route_prefix(t.route_prefix) + + built_apps.append( + build_app( + t.target, + name=t.name, + route_prefix=t.route_prefix, + logging_config=t.logging_config, + make_deployment_handle=make_local_deployment_handle + if _local_testing_mode + else None, + default_runtime_env=ray.get_runtime_context().runtime_env + if not _local_testing_mode + else None, + ) + ) + + if _local_testing_mode: + # implicitly use the last target's logging config (if provided) in local testing mode + logging_config = t.logging_config or LoggingConfig() + if not isinstance(logging_config, LoggingConfig): + logging_config = LoggingConfig(**(logging_config or {})) + + configure_component_logger( + component_name="local_test", + component_id="-", + logging_config=logging_config, + stream_handler_only=True, + ) + return [b.deployment_handles[b.ingress_deployment_name] for b in built_apps] + else: + client = _private_api.serve_start( + http_options={"location": "EveryNode"}, + global_logging_config=None, + ) + + # Record after Ray has been started. + ServeUsageTag.API_VERSION.record("v2") + + return client.deploy_applications( + built_apps, + wait_for_ingress_deployment_creation=wait_for_ingress_deployment_creation, + wait_for_applications_running=wait_for_applications_running, + ) + + +@PublicAPI(stability="stable") +def _run( + target: Application, + *, + _blocking: bool = True, + name: str = SERVE_DEFAULT_APP_NAME, + route_prefix: Optional[str] = "/", + logging_config: Optional[Union[Dict, LoggingConfig]] = None, + _local_testing_mode: bool = False, +) -> DeploymentHandle: + """Run an application and return a handle to its ingress deployment. + + This is only used internally with the _blocking not totally blocking the following + code indefinitely until Ctrl-C'd. + """ + return _run_many( + [ + RunTarget( + target=target, + name=name, + route_prefix=route_prefix, + logging_config=logging_config, + ) + ], + wait_for_applications_running=_blocking, + _local_testing_mode=_local_testing_mode, + )[0] + + +@DeveloperAPI +def run_many( + targets: Sequence[RunTarget], + blocking: bool = False, + wait_for_ingress_deployment_creation: bool = True, + wait_for_applications_running: bool = True, + _local_testing_mode: bool = False, +) -> List[DeploymentHandle]: + """Run many applications and return the handles to their ingress deployments. + + Args: + targets: + A sequence of `RunTarget`, + each containing information about an application to deploy. + blocking: Whether this call should be blocking. If True, it + will loop and log status until Ctrl-C'd. + wait_for_ingress_deployment_creation: Whether to wait for the ingress + deployments to be created. + wait_for_applications_running: Whether to wait for the applications to be + running. Note that this effectively implies + `wait_for_ingress_deployment_creation=True`, + because the ingress deployments must be created + before the applications can be running. + + Returns: + List[DeploymentHandle]: A list of handles that can be used + to call the applications. + """ + handles = _run_many( + targets, + wait_for_ingress_deployment_creation=wait_for_ingress_deployment_creation, + wait_for_applications_running=wait_for_applications_running, + _local_testing_mode=_local_testing_mode, + ) + + if blocking: + wait_for_interrupt() + + return handles + + +@PublicAPI(stability="stable") +def run( + target: Application, + blocking: bool = False, + name: str = SERVE_DEFAULT_APP_NAME, + route_prefix: Optional[str] = "/", + logging_config: Optional[Union[Dict, LoggingConfig]] = None, + _local_testing_mode: bool = False, +) -> DeploymentHandle: + """Run an application and return a handle to its ingress deployment. + + The application is returned by `Deployment.bind()`. Example: + + .. code-block:: python + + handle = serve.run(MyDeployment.bind()) + ray.get(handle.remote()) + + Args: + target: + A Serve application returned by `Deployment.bind()`. + blocking: Whether this call should be blocking. If True, it + will loop and log status until Ctrl-C'd. + name: Application name. If not provided, this will be the only + application running on the cluster (it will delete all others). + route_prefix: Route prefix for HTTP requests. Defaults to '/'. + If `None` is passed, the application will not be exposed over HTTP + (this may be useful if you only want the application to be exposed via + gRPC or a `DeploymentHandle`). + logging_config: Application logging config. If provided, the config will + be applied to all deployments which doesn't have logging config. + + Returns: + DeploymentHandle: A handle that can be used to call the application. + """ + handle = _run( + target=target, + name=name, + route_prefix=route_prefix, + logging_config=logging_config, + _local_testing_mode=_local_testing_mode, + ) + + if blocking: + wait_for_interrupt() + + return handle + + +@PublicAPI(stability="stable") +def delete(name: str, _blocking: bool = True): + """Delete an application by its name. + + Deletes the app with all corresponding deployments. + """ + client = _get_global_client() + client.delete_apps([name], blocking=_blocking) + + +@PublicAPI(stability="beta") +def multiplexed( + func: Optional[Callable[..., Any]] = None, max_num_models_per_replica: int = 3 +): + """Wrap a callable or method used to load multiplexed models in a replica. + + The function can be standalone function or a method of a class. The + function must have exactly one argument, the model id of type `str` for the + model to be loaded. + + It is required to define the function with `async def` and the function must be + an async function. It is recommended to define coroutines for long running + IO tasks in the function to avoid blocking the event loop. + + The multiplexed function is called to load a model with the given model ID when + necessary. + + When the number of models in one replica is larger than max_num_models_per_replica, + the models will be unloaded using an LRU policy. + + If you want to release resources after the model is loaded, you can define + a `__del__` method in your model class. The `__del__` method will be called when + the model is unloaded. + + Example: + + .. code-block:: python + + from ray import serve + + @serve.deployment + class MultiplexedDeployment: + + def __init__(self): + # Define s3 base path to load models. + self.s3_base_path = "s3://my_bucket/my_models" + + @serve.multiplexed(max_num_models_per_replica=5) + async def load_model(self, model_id: str) -> Any: + # Load model with the given tag + # You can use any model loading library here + # and return the loaded model. load_from_s3 is + # a placeholder function. + return load_from_s3(model_id) + + async def __call__(self, request): + # Get the model_id from the request context. + model_id = serve.get_multiplexed_model_id() + # Load the model for the requested model_id. + # If the model is already cached locally, + # this will just be a dictionary lookup. + model = await self.load_model(model_id) + return model(request) + + + Args: + max_num_models_per_replica: the maximum number of models + to be loaded on each replica. By default, it is 3, which + means that each replica can cache up to 3 models. You can + set it to a larger number if you have enough memory on + the node resource, in opposite, you can set it to a smaller + number if you want to save memory on the node resource. + """ + + if func is not None: + if not callable(func): + raise TypeError( + "The `multiplexed` decorator must be used with a function or method." + ) + + # TODO(Sihan): Make the API accept the sync function as well. + # https://github.com/ray-project/ray/issues/35356 + if not inspect.iscoroutinefunction(func): + raise TypeError( + "@serve.multiplexed can only be used to decorate async " + "functions or methods." + ) + signature = inspect.signature(func) + if len(signature.parameters) == 0 or len(signature.parameters) > 2: + raise TypeError( + "@serve.multiplexed can only be used to decorate functions or methods " + "with at least one 'model_id: str' argument." + ) + + if not isinstance(max_num_models_per_replica, int): + raise TypeError("max_num_models_per_replica must be an integer.") + + if max_num_models_per_replica != -1 and max_num_models_per_replica <= 0: + raise ValueError("max_num_models_per_replica must be positive.") + + def _multiplex_decorator(func: Callable): + @wraps(func) + async def _multiplex_wrapper(*args): + args_check_error_msg = ( + "Functions decorated with `@serve.multiplexed` must take exactly one" + "the multiplexed model ID (str), but got {}" + ) + if not args: + raise TypeError( + args_check_error_msg.format("no arguments are provided.") + ) + self = extract_self_if_method_call(args, func) + + # User defined multiplexed function can be a standalone function or a + # method of a class. If it is a method of a class, the first argument + # is self. + if self is None: + if len(args) != 1: + raise TypeError( + args_check_error_msg.format("more than one arguments.") + ) + multiplex_object = func + model_id = args[0] + else: + # count self as an argument + if len(args) != 2: + raise TypeError( + args_check_error_msg.format("more than one arguments.") + ) + multiplex_object = self + model_id = args[1] + multiplex_attr = "__serve_multiplex_wrapper" + # If the multiplexed function is called for the first time, + # create a model multiplex wrapper and cache it in the multiplex object. + if not hasattr(multiplex_object, multiplex_attr): + model_multiplex_wrapper = _ModelMultiplexWrapper( + func, self, max_num_models_per_replica + ) + setattr(multiplex_object, multiplex_attr, model_multiplex_wrapper) + else: + model_multiplex_wrapper = getattr(multiplex_object, multiplex_attr) + return await model_multiplex_wrapper.load_model(model_id) + + return _multiplex_wrapper + + return _multiplex_decorator(func) if callable(func) else _multiplex_decorator + + +@PublicAPI(stability="beta") +def get_multiplexed_model_id() -> str: + """Get the multiplexed model ID for the current request. + + This is used with a function decorated with `@serve.multiplexed` + to retrieve the model ID for the current request. + + .. code-block:: python + + import ray + from ray import serve + import requests + + # Set the multiplexed model id with the key + # "ray_serve_multiplexed_model_id" in the request + # headers when sending requests to the http proxy. + requests.get("http://localhost:8000", + headers={"ray_serve_multiplexed_model_id": "model_1"}) + + # This can also be set when using `DeploymentHandle`. + handle.options(multiplexed_model_id="model_1").remote("blablabla") + + # In your deployment code, you can retrieve the model id from + # `get_multiplexed_model_id()`. + @serve.deployment + def my_deployment_function(request): + assert serve.get_multiplexed_model_id() == "model_1" + """ + _request_context = ray.serve.context._get_serve_request_context() + return _request_context.multiplexed_model_id + + +@PublicAPI(stability="alpha") +def status() -> ServeStatus: + """Get the status of Serve on the cluster. + + Includes status of all HTTP Proxies, all active applications, and + their deployments. + + .. code-block:: python + + @serve.deployment(num_replicas=2) + class MyDeployment: + pass + + serve.run(MyDeployment.bind()) + status = serve.status() + assert status.applications["default"].status == "RUNNING" + """ + + client = _get_global_client(raise_if_no_controller_running=False) + if client is None: + # Serve has not started yet + return ServeStatus() + + ServeUsageTag.SERVE_STATUS_API_USED.record("1") + details = ServeInstanceDetails(**client.get_serve_details()) + return details._get_status() + + +@PublicAPI(stability="alpha") +def get_app_handle(name: str) -> DeploymentHandle: + """Get a handle to the application's ingress deployment by name. + + Args: + name: Name of application to get a handle to. + + Raises: + RayServeException: If no Serve controller is running, or if the + application does not exist. + + .. code-block:: python + + import ray + from ray import serve + + @serve.deployment + def f(val: int) -> int: + return val * 2 + + serve.run(f.bind(), name="my_app") + handle = serve.get_app_handle("my_app") + assert handle.remote(3).result() == 6 + """ + + client = _get_global_client() + ingress = ray.get(client._controller.get_ingress_deployment_name.remote(name)) + if ingress is None: + raise RayServeException(f"Application '{name}' does not exist.") + + ServeUsageTag.SERVE_GET_APP_HANDLE_API_USED.record("1") + # There is no need to check if the deployment exists since the + # deployment name was just fetched from the controller + return client.get_handle(ingress, name, check_exists=False) + + +@DeveloperAPI +def get_deployment_handle( + deployment_name: str, + app_name: Optional[str] = None, + _check_exists: bool = True, + _record_telemetry: bool = True, +) -> DeploymentHandle: + """Get a handle to a deployment by name. + + This is a developer API and is for advanced Ray users and library developers. + + Args: + deployment_name: Name of deployment to get a handle to. + app_name: Application in which deployment resides. If calling + from inside a Serve application and `app_name` is not + specified, this will default to the application from which + this API is called. + + Raises: + RayServeException: If no Serve controller is running, or if + calling from outside a Serve application and no application + name is specified. + + The following example gets the handle to the ingress deployment of + an application, which is equivalent to using `serve.get_app_handle`. + + .. testcode:: + + import ray + from ray import serve + + @serve.deployment + def f(val: int) -> int: + return val * 2 + + serve.run(f.bind(), name="my_app") + handle = serve.get_deployment_handle("f", app_name="my_app") + assert handle.remote(3).result() == 6 + + serve.shutdown() + + The following example demonstrates how you can use this API to get + the handle to a non-ingress deployment in an application. + + .. testcode:: + + import ray + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Multiplier: + def __init__(self, multiple: int): + self._multiple = multiple + + def __call__(self, val: int) -> int: + return val * self._multiple + + @serve.deployment + class Adder: + def __init__(self, handle: DeploymentHandle, increment: int): + self._handle = handle + self._increment = increment + + async def __call__(self, val: int) -> int: + return await self._handle.remote(val) + self._increment + + + # The app calculates 2 * x + 3 + serve.run(Adder.bind(Multiplier.bind(2), 3), name="math_app") + handle = serve.get_app_handle("math_app") + assert handle.remote(5).result() == 13 + + # Get handle to Multiplier only + handle = serve.get_deployment_handle("Multiplier", app_name="math_app") + assert handle.remote(5).result() == 10 + + serve.shutdown() + """ + + client = _get_global_client() + + internal_replica_context = _get_internal_replica_context() + if app_name is None: + if internal_replica_context is None: + raise RayServeException( + "Please specify an application name when getting a deployment handle " + "outside of a Serve application." + ) + else: + app_name = internal_replica_context.app_name + + if _record_telemetry: + ServeUsageTag.SERVE_GET_DEPLOYMENT_HANDLE_API_USED.record("1") + + return client.get_handle(deployment_name, app_name, check_exists=_check_exists) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/autoscaling_policy.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/autoscaling_policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2cabe736a870ac23244f1fa028342bebf0935079 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/autoscaling_policy.py @@ -0,0 +1,159 @@ +import logging +import math +from typing import Any, Dict, Optional + +from ray.serve._private.constants import CONTROL_LOOP_INTERVAL_S, SERVE_LOGGER_NAME +from ray.serve.config import AutoscalingConfig +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +def _calculate_desired_num_replicas( + autoscaling_config: AutoscalingConfig, + total_num_requests: int, + num_running_replicas: int, + override_min_replicas: Optional[float] = None, + override_max_replicas: Optional[float] = None, +) -> int: + """Returns the number of replicas to scale to based on the given metrics. + + Args: + autoscaling_config: The autoscaling parameters to use for this + calculation. + current_num_ongoing_requests (List[float]): A list of the number of + ongoing requests for each replica. Assumes each entry has already + been time-averaged over the desired lookback window. + override_min_replicas: Overrides min_replicas from the config + when calculating the final number of replicas. + override_max_replicas: Overrides max_replicas from the config + when calculating the final number of replicas. + + Returns: + desired_num_replicas: The desired number of replicas to scale to, based + on the input metrics and the current number of replicas. + + """ + if num_running_replicas == 0: + raise ValueError("Number of replicas cannot be zero") + + # Example: if error_ratio == 2.0, we have two times too many ongoing + # requests per replica, so we desire twice as many replicas. + target_num_requests = ( + autoscaling_config.get_target_ongoing_requests() * num_running_replicas + ) + error_ratio: float = total_num_requests / target_num_requests + + # If error ratio >= 1, then the number of ongoing requests per + # replica exceeds the target and we will make an upscale decision, + # so we apply the upscale smoothing factor. Otherwise, the number of + # ongoing requests per replica is lower than the target and we will + # make a downscale decision, so we apply the downscale smoothing + # factor. + if error_ratio >= 1: + scaling_factor = autoscaling_config.get_upscaling_factor() + else: + scaling_factor = autoscaling_config.get_downscaling_factor() + + # Multiply the distance to 1 by the smoothing ("gain") factor (default=1). + smoothed_error_ratio = 1 + ((error_ratio - 1) * scaling_factor) + desired_num_replicas = math.ceil(num_running_replicas * smoothed_error_ratio) + + # If desired num replicas is "stuck" because of the smoothing factor + # (meaning the traffic is low enough for the replicas to downscale + # without the smoothing factor), decrease desired_num_replicas by 1. + if ( + math.ceil(num_running_replicas * error_ratio) < num_running_replicas + and desired_num_replicas == num_running_replicas + ): + desired_num_replicas -= 1 + + min_replicas = autoscaling_config.min_replicas + max_replicas = autoscaling_config.max_replicas + if override_min_replicas is not None: + min_replicas = override_min_replicas + if override_max_replicas is not None: + max_replicas = override_max_replicas + + # Ensure scaled_min_replicas <= desired_num_replicas <= scaled_max_replicas. + desired_num_replicas = max(min_replicas, min(max_replicas, desired_num_replicas)) + + return desired_num_replicas + + +@PublicAPI(stability="alpha") +def replica_queue_length_autoscaling_policy( + curr_target_num_replicas: int, + total_num_requests: int, + num_running_replicas: int, + config: Optional[AutoscalingConfig], + capacity_adjusted_min_replicas: int, + capacity_adjusted_max_replicas: int, + policy_state: Dict[str, Any], +) -> int: + """The default autoscaling policy based on basic thresholds for scaling. + There is a minimum threshold for the average queue length in the cluster + to scale up and a maximum threshold to scale down. Each period, a 'scale + up' or 'scale down' decision is made. This decision must be made for a + specified number of periods in a row before the number of replicas is + actually scaled. See config options for more details. Assumes + `get_decision_num_replicas` is called once every CONTROL_LOOP_PERIOD_S + seconds. + """ + decision_counter = policy_state.get("decision_counter", 0) + if num_running_replicas == 0: + # When 0 replicas and queries are queued, scale up the replicas + if total_num_requests > 0: + return max( + math.ceil(1 * config.get_upscaling_factor()), + curr_target_num_replicas, + ) + return curr_target_num_replicas + + decision_num_replicas = curr_target_num_replicas + + desired_num_replicas = _calculate_desired_num_replicas( + config, + total_num_requests, + num_running_replicas=num_running_replicas, + override_min_replicas=capacity_adjusted_min_replicas, + override_max_replicas=capacity_adjusted_max_replicas, + ) + # Scale up. + if desired_num_replicas > curr_target_num_replicas: + # If the previous decision was to scale down (the counter was + # negative), we reset it and then increment it (set to 1). + # Otherwise, just increment. + if decision_counter < 0: + decision_counter = 0 + decision_counter += 1 + + # Only actually scale the replicas if we've made this decision for + # 'scale_up_consecutive_periods' in a row. + if decision_counter > int(config.upscale_delay_s / CONTROL_LOOP_INTERVAL_S): + decision_counter = 0 + decision_num_replicas = desired_num_replicas + + # Scale down. + elif desired_num_replicas < curr_target_num_replicas: + # If the previous decision was to scale up (the counter was + # positive), reset it to zero before decrementing. + if decision_counter > 0: + decision_counter = 0 + decision_counter -= 1 + + # Only actually scale the replicas if we've made this decision for + # 'scale_down_consecutive_periods' in a row. + if decision_counter < -int(config.downscale_delay_s / CONTROL_LOOP_INTERVAL_S): + decision_counter = 0 + decision_num_replicas = desired_num_replicas + + # Do nothing. + else: + decision_counter = 0 + + policy_state["decision_counter"] = decision_counter + return decision_num_replicas + + +default_autoscaling_policy = replica_queue_length_autoscaling_policy diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/batching.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/batching.py new file mode 100644 index 0000000000000000000000000000000000000000..8be63765c43ea10d5912a0c6654e1d138a5af48c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/batching.py @@ -0,0 +1,756 @@ +import asyncio +import io +import logging +import time +from collections import deque +from dataclasses import dataclass +from functools import wraps +from inspect import isasyncgenfunction, iscoroutinefunction +from typing import ( + Any, + AsyncGenerator, + Callable, + Coroutine, + Dict, + Generic, + Iterable, + List, + Literal, + Optional, + Protocol, + Set, + Tuple, + TypeVar, + overload, +) + +from ray import serve +from ray._common.signature import extract_signature, flatten_args, recover_args +from ray._common.utils import get_or_create_event_loop +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.utils import extract_self_if_method_call +from ray.serve.exceptions import RayServeException +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +# The user can return these values in their streaming batch handler function to +# indicate that a request is finished, so Serve can terminate the request. +USER_CODE_STREAMING_SENTINELS = [StopIteration, StopAsyncIteration] + + +@dataclass +class _SingleRequest: + self_arg: Any + flattened_args: List[Any] + future: asyncio.Future + + +@dataclass +class _GeneratorResult: + result: Any + next_future: asyncio.Future + + +@dataclass +class _RuntimeSummaryStatistics: + start_times: List[float] + + @property + def min_start_time(self) -> Optional[float]: + return min(self.start_times) if self.start_times else None + + @property + def mean_start_time(self) -> Optional[float]: + return ( + sum(self.start_times) / len(self.start_times) if self.start_times else None + ) + + @property + def max_start_time(self) -> Optional[float]: + return max(self.start_times) if self.start_times else None + + @property + def num_requests(self) -> int: + return len(self.start_times) + + +def _batch_args_kwargs( + list_of_flattened_args: List[List[Any]], +) -> Tuple[Tuple[Any], Dict[Any, Any]]: + """Batch a list of flatten args and returns regular args and kwargs""" + # Ray's flatten arg format is a list with alternating key and values + # e.g. args=(1, 2), kwargs={"key": "val"} got turned into + # [None, 1, None, 2, "key", "val"] + arg_lengths = {len(args) for args in list_of_flattened_args} + assert ( + len(arg_lengths) == 1 + ), "All batch requests should have the same number of parameters." + arg_length = arg_lengths.pop() + + batched_flattened_args = [] + for idx in range(arg_length): + if idx % 2 == 0: + batched_flattened_args.append(list_of_flattened_args[0][idx]) + else: + batched_flattened_args.append( + [item[idx] for item in list_of_flattened_args] + ) + + return recover_args(batched_flattened_args) + + +class _BatchQueue: + def __init__( + self, + max_batch_size: int, + batch_wait_timeout_s: float, + max_concurrent_batches: int, + handle_batch_func: Optional[Callable] = None, + ) -> None: + """Async queue that accepts individual items and returns batches. + + Respects max_batch_size and batch_wait_timeout_s; a batch will be returned when + max_batch_size elements are available or the timeout has passed since + the previous get. + + If handle_batch_func is passed in, a background coroutine will run to + poll from the queue and call handle_batch_func on the results. + + Cannot be pickled. + + Arguments: + max_batch_size: max number of elements to return in a batch. + batch_wait_timeout_s: time to wait before returning an incomplete + batch. + max_concurrent_batches: max number of batches to run concurrently. + handle_batch_func(Optional[Callable]): callback to run in the + background to handle batches if provided. + """ + self.queue: asyncio.Queue[_SingleRequest] = asyncio.Queue() + self.max_batch_size = max_batch_size + self.batch_wait_timeout_s = batch_wait_timeout_s + self.max_concurrent_batches = max_concurrent_batches + self.semaphore = asyncio.Semaphore(max_concurrent_batches) + self.requests_available_event = asyncio.Event() + self.tasks: Set[asyncio.Task] = set() + + # Used for observability. + self.curr_iteration_start_times: Dict[asyncio.Task, float] = {} + + self._handle_batch_task = None + self._loop = get_or_create_event_loop() + if handle_batch_func is not None: + self._handle_batch_task = self._loop.create_task( + self._process_batches(handle_batch_func) + ) + self._warn_if_max_batch_size_exceeds_max_ongoing_requests() + + def _warn_if_max_batch_size_exceeds_max_ongoing_requests(self): + """Helper to check whether the max_batch_size is bounded. + + Log a warning to configure `max_ongoing_requests` if it's bounded. + """ + max_ongoing_requests = ( + serve.get_replica_context()._deployment_config.max_ongoing_requests + ) + if max_ongoing_requests < self.max_batch_size * self.max_concurrent_batches: + logger.warning( + f"`max_batch_size` ({self.max_batch_size}) * `max_concurrent_batches` " + f"({self.max_concurrent_batches}) is larger than `max_ongoing_requests` " + f"({max_ongoing_requests}). This means the replica will never achieve " + "the configured `max_batch_size` concurrently. Please update " + "`max_ongoing_requests` to be >= `max_batch_size` * `max_concurrent_batches`." + ) + + def set_max_batch_size(self, new_max_batch_size: int) -> None: + """Updates queue's max_batch_size.""" + self.max_batch_size = new_max_batch_size + self._warn_if_max_batch_size_exceeds_max_ongoing_requests() + + def put(self, request: Tuple[_SingleRequest, asyncio.Future]) -> None: + self.queue.put_nowait(request) + self.requests_available_event.set() + + async def wait_for_batch(self) -> List[_SingleRequest]: + """Wait for batch respecting self.max_batch_size and self.timeout_s. + + Returns a batch of up to self.max_batch_size items. Waits for up to + to self.timeout_s after receiving the first request that will be in + the next batch. After the timeout, returns as many items as are ready. + + Always returns a batch with at least one item - will block + indefinitely until an item comes in. + """ + + batch = [] + batch.append(await self.queue.get()) + + # Cache current max_batch_size and batch_wait_timeout_s for this batch. + max_batch_size = self.max_batch_size + batch_wait_timeout_s = self.batch_wait_timeout_s + + # Wait self.timeout_s seconds for new queue arrivals. + batch_start_time = time.time() + while True: + remaining_batch_time_s = max( + batch_wait_timeout_s - (time.time() - batch_start_time), 0 + ) + try: + # Wait for new arrivals. + await asyncio.wait_for( + self.requests_available_event.wait(), remaining_batch_time_s + ) + except asyncio.TimeoutError: + pass + + # Add all new arrivals to the batch. + while len(batch) < max_batch_size and not self.queue.empty(): + batch.append(self.queue.get_nowait()) + + # Only clear the put event if the queue is empty. If it's not empty + # we can start constructing a new batch immediately in the next loop. + # The code that puts items into the queue runs on the same event loop + # as this code, so there's no race condition between the time we + # get objects in the queue (and clear the event) and when objects + # get added to the queue. + if self.queue.empty(): + self.requests_available_event.clear() + + if ( + time.time() - batch_start_time >= batch_wait_timeout_s + or len(batch) >= max_batch_size + ): + break + + return batch + + def _validate_results( + self, results: Iterable[Any], input_batch_length: int + ) -> None: + if len(results) != input_batch_length: + raise RayServeException( + "Batched function doesn't preserve batch size. " + f"The input list has length {input_batch_length} but the " + f"returned list has length {len(results)}." + ) + + async def _consume_func_generator( + self, + func_generator: AsyncGenerator, + initial_futures: List[asyncio.Future], + input_batch_length: int, + ) -> None: + """Consumes batch function generator. + + This function only runs if the function decorated with @serve.batch + is a generator. + """ + + FINISHED_TOKEN = None + + try: + futures = deque(initial_futures) + assert len(futures) == input_batch_length + + async for results in func_generator: + self._validate_results(results, input_batch_length) + for idx in range(input_batch_length): + result, future = results[idx], futures[0] + + if future is FINISHED_TOKEN: + # This caller has already terminated. + futures.append(FINISHED_TOKEN) + elif result in USER_CODE_STREAMING_SENTINELS: + # User's code returned sentinel. No values left + # for caller. Terminate iteration for caller. + _set_exception_if_not_done(future, StopAsyncIteration) + futures.append(FINISHED_TOKEN) + else: + next_future = get_or_create_event_loop().create_future() + _set_result_if_not_done( + future, _GeneratorResult(result, next_future) + ) + futures.append(next_future) + + # Remove processed future. We remove the future at the very + # end of the loop to ensure that if an exception occurs, + # all pending futures will get set in the `except` block. + futures.popleft() + + for future in futures: + if future is not FINISHED_TOKEN: + _set_exception_if_not_done(future, StopAsyncIteration) + except Exception as e: + for future in futures: + if future is not FINISHED_TOKEN: + _set_exception_if_not_done(future, e) + + async def _assign_func_results( + self, + func_future: asyncio.Future, + futures: List[asyncio.Future], + input_batch_length: int, + ): + """Assigns func's results to the list of futures.""" + + try: + results = await func_future + self._validate_results(results, input_batch_length) + for result, future in zip(results, futures): + _set_result_if_not_done(future, result) + except Exception as e: + for future in futures: + _set_exception_if_not_done(future, e) + + async def _process_batches(self, func: Callable) -> None: + """Loops infinitely and processes queued request batches.""" + while not self._loop.is_closed(): + batch = await self.wait_for_batch() + promise = self._process_batch(func, batch) + task = asyncio.create_task(promise) + self.tasks.add(task) + self.curr_iteration_start_times[task] = time.time() + task.add_done_callback(self._handle_completed_task) + + async def _process_batch(self, func: Callable, batch: List[_SingleRequest]) -> None: + """Processes queued request batch.""" + # NOTE: this semaphore caps the number of concurrent batches specified by `max_concurrent_batches` + async with self.semaphore: + # Remove requests that have been cancelled from the batch. If + # all requests have been cancelled, simply return and wait for + # the next batch. + batch = [req for req in batch if not req.future.cancelled()] + if len(batch) == 0: + return + + futures = [item.future for item in batch] + + # Most of the logic in the function should be wrapped in this try- + # except block, so the futures' exceptions can be set if an exception + # occurs. Otherwise, the futures' requests may hang indefinitely. + try: + self_arg = batch[0].self_arg + args, kwargs = _batch_args_kwargs( + [item.flattened_args for item in batch] + ) + + # Method call. + if self_arg is not None: + func_future_or_generator = func(self_arg, *args, **kwargs) + # Normal function call. + else: + func_future_or_generator = func(*args, **kwargs) + + if isasyncgenfunction(func): + func_generator = func_future_or_generator + await self._consume_func_generator( + func_generator, futures, len(batch) + ) + else: + func_future = func_future_or_generator + await self._assign_func_results(func_future, futures, len(batch)) + + except Exception as e: + logger.exception("_process_batch ran into an unexpected exception.") + + for future in futures: + _set_exception_if_not_done(future, e) + + def _handle_completed_task(self, task: asyncio.Task) -> None: + self.tasks.remove(task) + del self.curr_iteration_start_times[task] + self._log_if_exception(task.exception()) + + @staticmethod + def _log_if_exception(exception_maybe: Optional[BaseException]) -> None: + if exception_maybe is not None: + if isinstance(exception_maybe, asyncio.CancelledError): + logger.debug("Task was cancelled") + else: + logger.exception("Task failed unexpectedly") + + def __del__(self): + if ( + self._handle_batch_task is None + or not get_or_create_event_loop().is_running() + ): + return + + # TODO(edoakes): although we try to gracefully shutdown here, it still + # causes some errors when the process exits due to the asyncio loop + # already being destroyed. + self._handle_batch_task.cancel() + + +class _LazyBatchQueueWrapper: + """Stores a _BatchQueue and updates its settings. + + _BatchQueue cannot be pickled, you must construct it lazily + at runtime inside a replica. This class initializes a queue only upon + first access. + """ + + def __init__( + self, + max_batch_size: int = 10, + batch_wait_timeout_s: float = 0.0, + max_concurrent_batches: int = 1, + handle_batch_func: Optional[Callable] = None, + ): + self._queue: Optional[_BatchQueue] = None + self.max_batch_size = max_batch_size + self.batch_wait_timeout_s = batch_wait_timeout_s + self.max_concurrent_batches = max_concurrent_batches + self.handle_batch_func = handle_batch_func + + @property + def queue(self) -> _BatchQueue: + """Returns _BatchQueue. + + Initializes queue when called for the first time. + """ + if self._queue is None: + self._queue = _BatchQueue( + self.max_batch_size, + self.batch_wait_timeout_s, + self.max_concurrent_batches, + self.handle_batch_func, + ) + return self._queue + + def set_max_batch_size(self, new_max_batch_size: int) -> None: + """Updates queue's max_batch_size.""" + + self.max_batch_size = new_max_batch_size + + if self._queue is not None: + self._queue.set_max_batch_size(new_max_batch_size) + + def set_batch_wait_timeout_s(self, new_batch_wait_timeout_s: float) -> None: + self.batch_wait_timeout_s = new_batch_wait_timeout_s + + if self._queue is not None: + self._queue.batch_wait_timeout_s = new_batch_wait_timeout_s + + def get_max_batch_size(self) -> int: + return self.max_batch_size + + def get_batch_wait_timeout_s(self) -> float: + return self.batch_wait_timeout_s + + def _get_curr_iteration_start_times(self) -> _RuntimeSummaryStatistics: + """Gets summary statistics of current iteration's start times.""" + return _RuntimeSummaryStatistics( + list(self.queue.curr_iteration_start_times.values()) + ) + + async def _is_batching_task_alive(self) -> bool: + """Gets whether default _BatchQueue's background task is alive. + + Returns False if the batch handler doesn't use a default _BatchQueue. + """ + + if hasattr(self.queue, "_handle_batch_task"): + return not self.queue._handle_batch_task.done() + else: + return False + + async def _get_handling_task_stack(self) -> Optional[str]: + """Gets the stack for the default _BatchQueue's background task. + + Returns empty string if the batch handler doesn't use a default _BatchQueue. + """ + + if hasattr(self.queue, "_handle_batch_task"): + str_buffer = io.StringIO() + self.queue._handle_batch_task.print_stack(file=str_buffer) + return str_buffer.getvalue() + else: + return None + + +def _validate_max_batch_size(max_batch_size): + if not isinstance(max_batch_size, int): + if isinstance(max_batch_size, float) and max_batch_size.is_integer(): + max_batch_size = int(max_batch_size) + else: + raise TypeError( + f"max_batch_size must be integer >= 1, got {max_batch_size}" + ) + + if max_batch_size < 1: + raise ValueError( + f"max_batch_size must be an integer >= 1, got {max_batch_size}" + ) + + +def _validate_batch_wait_timeout_s(batch_wait_timeout_s): + if not isinstance(batch_wait_timeout_s, (float, int)): + raise TypeError( + f"batch_wait_timeout_s must be a float >= 0, got {batch_wait_timeout_s}" + ) + + if batch_wait_timeout_s < 0: + raise ValueError( + f"batch_wait_timeout_s must be a float >= 0, got {batch_wait_timeout_s}" + ) + + +def _validate_max_concurrent_batches(max_concurrent_batches: int) -> None: + if not isinstance(max_concurrent_batches, int) or max_concurrent_batches < 1: + raise TypeError( + f"max_concurrent_batches must be an integer >= 1, got {max_concurrent_batches}" + ) + + +SelfType = TypeVar("SelfType", contravariant=True) +T = TypeVar("T") +R = TypeVar("R") + + +class _SyncBatchingMethod(Protocol, Generic[SelfType, T, R]): + def __call__(self, self_: SelfType, __batch: List[T], /) -> List[R]: + ... + + +class _AsyncBatchingMethod(Protocol, Generic[SelfType, T, R]): + async def __call__(self, self_: SelfType, __batch: List[T], /) -> List[R]: + ... + + +@overload # Sync function for `batch` called WITHOUT arguments +def batch(_sync_func: Callable[[List[T]], List[R]], /) -> Callable[[T], R]: + ... + + +@overload # Async function for `batch` called WITHOUT arguments +def batch( + _async_func: Callable[[List[T]], Coroutine[Any, Any, List[R]]], / +) -> Callable[[T], Coroutine[Any, Any, R]]: + ... + + +@overload # Sync method for `batch` called WITHOUT arguments +def batch( + _sync_meth: _SyncBatchingMethod[SelfType, T, R], / +) -> Callable[[SelfType, T], R]: + ... + + +@overload # Async method for `batch` called WITHOUT arguments +def batch( + _async_meth: _AsyncBatchingMethod[SelfType, T, R], / +) -> Callable[[SelfType, T], Coroutine[Any, Any, R]]: + ... + + +@overload # `batch` called WITH arguments +def batch( + _: Literal[None] = None, + /, + max_batch_size: int = 10, + batch_wait_timeout_s: float = 0.0, + max_concurrent_batches: int = 1, +) -> "_BatchDecorator": + ... + + +class _BatchDecorator(Protocol): + """Descibes behaviour of decorator produced by calling `batch` with arguments""" + + @overload # Sync function + def __call__(self, _sync_func: Callable[[List[T]], List[R]], /) -> Callable[[T], R]: + ... + + @overload # Async function + def __call__( + self, _async_func: Callable[[List[T]], Coroutine[Any, Any, List[R]]], / + ) -> Callable[[T], Coroutine[Any, Any, R]]: + ... + + @overload # Sync method + def __call__( + self, _sync_meth: _SyncBatchingMethod[SelfType, T, R], / + ) -> Callable[[SelfType, T], R]: + ... + + @overload # Async method + def __call__( + self, _async_meth: _AsyncBatchingMethod[SelfType, T, R], / + ) -> Callable[[SelfType, T], Coroutine[Any, Any, R]]: + ... + + +@PublicAPI(stability="stable") +def batch( + _func: Optional[Callable] = None, + /, + max_batch_size: int = 10, + batch_wait_timeout_s: float = 0.0, + max_concurrent_batches: int = 1, +) -> Callable: + """Converts a function to asynchronously handle batches. + + The function can be a standalone function or a class method. In both + cases, the function must be `async def` and take a list of objects as + its sole argument and return a list of the same length as a result. + + When invoked, the caller passes a single object. These will be batched + and executed asynchronously once there is a batch of `max_batch_size` + or `batch_wait_timeout_s` has elapsed, whichever occurs first. + + `max_batch_size` and `batch_wait_timeout_s` can be updated using setter + methods from the batch_handler (`set_max_batch_size` and + `set_batch_wait_timeout_s`). + + Example: + + .. code-block:: python + + from ray import serve + from starlette.requests import Request + + @serve.deployment + class BatchedDeployment: + @serve.batch(max_batch_size=10, batch_wait_timeout_s=0.1) + async def batch_handler(self, requests: List[Request]) -> List[str]: + response_batch = [] + for r in requests: + name = (await requests.json())["name"] + response_batch.append(f"Hello {name}!") + + return response_batch + + def update_batch_params(self, max_batch_size, batch_wait_timeout_s): + self.batch_handler.set_max_batch_size(max_batch_size) + self.batch_handler.set_batch_wait_timeout_s(batch_wait_timeout_s) + + async def __call__(self, request: Request): + return await self.batch_handler(request) + + app = BatchedDeployment.bind() + + Arguments: + max_batch_size: the maximum batch size that will be executed in + one call to the underlying function. + batch_wait_timeout_s: the maximum duration to wait for + `max_batch_size` elements before running the current batch. + max_concurrent_batches: the maximum number of batches that can be + executed concurrently. If the number of concurrent batches exceeds + this limit, the batch handler will wait for a batch to complete + before sending the next batch to the underlying function. + """ + # `_func` will be None in the case when the decorator is parametrized. + # See the comment at the end of this function for a detailed explanation. + if _func is not None: + if not callable(_func): + raise TypeError( + "@serve.batch can only be used to decorate functions or methods." + ) + + if not iscoroutinefunction(_func): + raise TypeError("Functions decorated with @serve.batch must be 'async def'") + + _validate_max_batch_size(max_batch_size) + _validate_batch_wait_timeout_s(batch_wait_timeout_s) + _validate_max_concurrent_batches(max_concurrent_batches) + + def _batch_decorator(_func): + lazy_batch_queue_wrapper = _LazyBatchQueueWrapper( + max_batch_size, + batch_wait_timeout_s, + max_concurrent_batches, + _func, + ) + + async def batch_handler_generator( + first_future: asyncio.Future, + ) -> AsyncGenerator: + """Generator that handles generator batch functions.""" + + future = first_future + while True: + try: + async_response: _GeneratorResult = await future + future = async_response.next_future + yield async_response.result + except StopAsyncIteration: + break + + def enqueue_request(args, kwargs) -> asyncio.Future: + flattened_args: List = flatten_args(extract_signature(_func), args, kwargs) + + # If the function is a method, remove self as an argument. + self = extract_self_if_method_call(args, _func) + if self is not None: + flattened_args = flattened_args[2:] + + batch_queue = lazy_batch_queue_wrapper.queue + + future = get_or_create_event_loop().create_future() + batch_queue.put(_SingleRequest(self, flattened_args, future)) + return future + + @wraps(_func) + def generator_batch_wrapper(*args, **kwargs): + first_future = enqueue_request(args, kwargs) + return batch_handler_generator(first_future) + + @wraps(_func) + async def batch_wrapper(*args, **kwargs): + # This will raise if the underlying call raised an exception. + return await enqueue_request(args, kwargs) + + if isasyncgenfunction(_func): + wrapper = generator_batch_wrapper + else: + wrapper = batch_wrapper + + # We store the lazy_batch_queue_wrapper's getters and setters as + # batch_wrapper attributes, so they can be accessed in user code. + wrapper._get_max_batch_size = lazy_batch_queue_wrapper.get_max_batch_size + wrapper._get_batch_wait_timeout_s = ( + lazy_batch_queue_wrapper.get_batch_wait_timeout_s + ) + wrapper.set_max_batch_size = lazy_batch_queue_wrapper.set_max_batch_size + wrapper.set_batch_wait_timeout_s = ( + lazy_batch_queue_wrapper.set_batch_wait_timeout_s + ) + + # Store debugging methods in the lazy_batch_queue wrapper + wrapper._get_curr_iteration_start_times = ( + lazy_batch_queue_wrapper._get_curr_iteration_start_times + ) + wrapper._is_batching_task_alive = ( + lazy_batch_queue_wrapper._is_batching_task_alive + ) + wrapper._get_handling_task_stack = ( + lazy_batch_queue_wrapper._get_handling_task_stack + ) + + return wrapper + + # Unfortunately, this is required to handle both non-parametrized + # (@serve.batch) and parametrized (@serve.batch(**kwargs)) usage. + # In the former case, `serve.batch` will be called with the underlying + # function as the sole argument. In the latter case, it will first be + # called with **kwargs, then the result of that call will be called + # with the underlying function as the sole argument (i.e., it must be a + # "decorator factory."). + return _batch_decorator(_func) if callable(_func) else _batch_decorator + + +def _set_result_if_not_done(future: asyncio.Future, result: Any): + """Sets the future's result if the future is not done.""" + + if not future.done(): + future.set_result(result) + + +def _set_exception_if_not_done(future: asyncio.Future, exception: Any): + """Sets the future's exception if the future is not done.""" + + if not future.done(): + future.set_exception(exception) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/config.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1386a99b48f4edb670bc17c79be9cad840d42504 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/config.py @@ -0,0 +1,482 @@ +import json +import logging +import warnings +from enum import Enum +from typing import Any, Callable, Dict, List, Optional, Union + +from ray import cloudpickle +from ray._common.pydantic_compat import ( + BaseModel, + Field, + NonNegativeFloat, + NonNegativeInt, + PositiveFloat, + PositiveInt, + PrivateAttr, + validator, +) +from ray._common.utils import import_attr +from ray.serve._private.constants import ( + DEFAULT_AUTOSCALING_POLICY, + DEFAULT_GRPC_PORT, + DEFAULT_HTTP_HOST, + DEFAULT_HTTP_PORT, + DEFAULT_REQUEST_ROUTER_PATH, + DEFAULT_REQUEST_ROUTING_STATS_PERIOD_S, + DEFAULT_REQUEST_ROUTING_STATS_TIMEOUT_S, + DEFAULT_TARGET_ONGOING_REQUESTS, + DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S, + SERVE_LOGGER_NAME, +) +from ray.util.annotations import Deprecated, PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="alpha") +class RequestRouterConfig(BaseModel): + """Config for the Serve request router. + + This class configures how Ray Serve routes requests to deployment replicas. The router is + responsible for selecting which replica should handle each incoming request based on the + configured routing policy. You can customize the routing behavior by specifying a custom + request router class and providing configuration parameters. + + The router also manages periodic health checks and scheduling statistics collection from + replicas to make informed routing decisions. + + Example: + .. code-block:: python + + from ray.serve.config import RequestRouterConfig, DeploymentConfig + from ray import serve + + # Use default router with custom stats collection interval + request_router_config = RequestRouterConfig( + request_routing_stats_period_s=5.0, + request_routing_stats_timeout_s=15.0 + ) + + # Use custom router class + request_router_config = RequestRouterConfig( + request_router_class="ray.llm._internal.serve.request_router.prefix_aware.prefix_aware_router.PrefixAwarePow2ReplicaRouter", + request_router_kwargs={"imbalanced_threshold": 20} + ) + deployment_config = DeploymentConfig( + request_router_config=request_router_config + ) + deployment = serve.deploy( + "my_deployment", + deployment_config=deployment_config + ) + """ + + _serialized_request_router_cls: bytes = PrivateAttr(default=b"") + + request_router_class: Union[str, Callable] = Field( + default=DEFAULT_REQUEST_ROUTER_PATH, + description=( + "The class of the request router that Ray Serve uses for this deployment. This value can be " + "a string or a class. All the deployment handles that you create for this " + "deployment use the routing policy defined by the request router. " + "Default to Serve's PowerOfTwoChoicesRequestRouter." + ), + ) + request_router_kwargs: Dict[str, Any] = Field( + default_factory=dict, + description=( + "Keyword arguments that Ray Serve passes to the request router class " + "initialize_state method." + ), + ) + + request_routing_stats_period_s: PositiveFloat = Field( + default=DEFAULT_REQUEST_ROUTING_STATS_PERIOD_S, + description=( + "Duration between record scheduling stats calls for the replica. " + "Defaults to 10s. The health check is by default a no-op Actor call " + "to the replica, but you can define your own request scheduling stats " + "using the 'record_scheduling_stats' method in your deployment." + ), + ) + + request_routing_stats_timeout_s: PositiveFloat = Field( + default=DEFAULT_REQUEST_ROUTING_STATS_TIMEOUT_S, + description=( + "Duration in seconds, that replicas wait for a request scheduling " + "stats method to return before considering it as failed. Defaults to 30s." + ), + ) + + @validator("request_router_kwargs", always=True) + def request_router_kwargs_json_serializable(cls, v): + if isinstance(v, bytes): + return v + if v is not None: + try: + json.dumps(v) + except TypeError as e: + raise ValueError( + f"request_router_kwargs is not JSON-serializable: {str(e)}." + ) + + return v + + def __init__(self, **kwargs: dict[str, Any]): + """Initialize RequestRouterConfig with the given parameters. + + Needed to serialize the request router class since validators are not called + for attributes that begin with an underscore. + + Args: + **kwargs: Keyword arguments to pass to BaseModel. + """ + super().__init__(**kwargs) + self._serialize_request_router_cls() + + def _serialize_request_router_cls(self) -> None: + """Import and serialize request router class with cloudpickle. + + Import the request router if you pass it in as a string import path. + Then cloudpickle the request router and set to + `_serialized_request_router_cls`. + """ + request_router_class = self.request_router_class + if isinstance(request_router_class, Callable): + request_router_class = ( + f"{request_router_class.__module__}.{request_router_class.__name__}" + ) + + request_router_path = request_router_class or DEFAULT_REQUEST_ROUTER_PATH + request_router_class = import_attr(request_router_path) + + self._serialized_request_router_cls = cloudpickle.dumps(request_router_class) + # Update the request_router_class field to be the string path + self.request_router_class = request_router_path + + def get_request_router_class(self) -> Callable: + """Deserialize the request router from cloudpickled bytes.""" + return cloudpickle.loads(self._serialized_request_router_cls) + + +@PublicAPI(stability="stable") +class AutoscalingConfig(BaseModel): + """Config for the Serve Autoscaler.""" + + # Please keep these options in sync with those in + # `src/ray/protobuf/serve.proto`. + + # Publicly exposed options + min_replicas: NonNegativeInt = 1 + initial_replicas: Optional[NonNegativeInt] = None + max_replicas: PositiveInt = 1 + + target_ongoing_requests: PositiveFloat = DEFAULT_TARGET_ONGOING_REQUESTS + + metrics_interval_s: PositiveFloat = Field( + default=10.0, description="How often to scrape for metrics." + ) + look_back_period_s: PositiveFloat = Field( + default=30.0, description="Time window to average over for metrics." + ) + + smoothing_factor: PositiveFloat = Field( + default=1.0, + description="[DEPRECATED] Smoothing factor for autoscaling decisions.", + ) + # DEPRECATED: replaced by `downscaling_factor` + upscale_smoothing_factor: Optional[PositiveFloat] = Field( + default=None, description="[DEPRECATED] Please use `upscaling_factor` instead." + ) + # DEPRECATED: replaced by `upscaling_factor` + downscale_smoothing_factor: Optional[PositiveFloat] = Field( + default=None, + description="[DEPRECATED] Please use `downscaling_factor` instead.", + ) + + upscaling_factor: Optional[PositiveFloat] = Field( + default=None, + description='Multiplicative "gain" factor to limit upscaling decisions.', + ) + downscaling_factor: Optional[PositiveFloat] = Field( + default=None, + description='Multiplicative "gain" factor to limit downscaling decisions.', + ) + + # How frequently to make autoscaling decisions + # loop_period_s: float = CONTROL_LOOP_PERIOD_S + downscale_delay_s: NonNegativeFloat = Field( + default=600.0, description="How long to wait before scaling down replicas." + ) + upscale_delay_s: NonNegativeFloat = Field( + default=30.0, description="How long to wait before scaling up replicas." + ) + + # Cloudpickled policy definition. + _serialized_policy_def: bytes = PrivateAttr(default=b"") + + # Custom autoscaling config. Defaults to the request-based autoscaler. + _policy: Union[str, Callable] = PrivateAttr(default=DEFAULT_AUTOSCALING_POLICY) + + @validator("max_replicas", always=True) + def replicas_settings_valid(cls, max_replicas, values): + min_replicas = values.get("min_replicas") + initial_replicas = values.get("initial_replicas") + if min_replicas is not None and max_replicas < min_replicas: + raise ValueError( + f"max_replicas ({max_replicas}) must be greater than " + f"or equal to min_replicas ({min_replicas})!" + ) + + if initial_replicas is not None: + if initial_replicas < min_replicas: + raise ValueError( + f"min_replicas ({min_replicas}) must be less than " + f"or equal to initial_replicas ({initial_replicas})!" + ) + elif initial_replicas > max_replicas: + raise ValueError( + f"max_replicas ({max_replicas}) must be greater than " + f"or equal to initial_replicas ({initial_replicas})!" + ) + + return max_replicas + + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.serialize_policy() + + def serialize_policy(self) -> None: + """Serialize policy with cloudpickle. + + Import the policy if it's passed in as a string import path. Then cloudpickle + the policy and set `serialized_policy_def` if it's empty. + """ + values = self.dict() + policy = values.get("_policy") + if isinstance(policy, Callable): + policy = f"{policy.__module__}.{policy.__name__}" + + if not policy: + policy = DEFAULT_AUTOSCALING_POLICY + + policy_path = policy + policy = import_attr(policy) + + if not values.get("_serialized_policy_def"): + self._serialized_policy_def = cloudpickle.dumps(policy) + self._policy = policy_path + + @classmethod + def default(cls): + return cls( + target_ongoing_requests=DEFAULT_TARGET_ONGOING_REQUESTS, + min_replicas=1, + max_replicas=100, + ) + + def get_policy(self) -> Callable: + """Deserialize policy from cloudpickled bytes.""" + return cloudpickle.loads(self._serialized_policy_def) + + def get_upscaling_factor(self) -> PositiveFloat: + if self.upscaling_factor: + return self.upscaling_factor + + return self.upscale_smoothing_factor or self.smoothing_factor + + def get_downscaling_factor(self) -> PositiveFloat: + if self.downscaling_factor: + return self.downscaling_factor + + return self.downscale_smoothing_factor or self.smoothing_factor + + def get_target_ongoing_requests(self) -> PositiveFloat: + return self.target_ongoing_requests + + +# Keep in sync with ServeDeploymentMode in dashboard/client/src/type/serve.ts +@Deprecated +class DeploymentMode(str, Enum): + NoServer = "NoServer" + HeadOnly = "HeadOnly" + EveryNode = "EveryNode" + + +@PublicAPI(stability="stable") +class ProxyLocation(str, Enum): + """Config for where to run proxies to receive ingress traffic to the cluster. + + Options: + + - Disabled: don't run proxies at all. This should be used if you are only + making calls to your applications via deployment handles. + - HeadOnly: only run a single proxy on the head node. + - EveryNode: run a proxy on every node in the cluster that has at least one + replica actor. This is the default. + """ + + Disabled = "Disabled" + HeadOnly = "HeadOnly" + EveryNode = "EveryNode" + + @classmethod + def _to_deployment_mode( + cls, proxy_location: Union["ProxyLocation", str] + ) -> DeploymentMode: + if isinstance(proxy_location, str): + proxy_location = ProxyLocation(proxy_location) + elif not isinstance(proxy_location, ProxyLocation): + raise TypeError( + f"Must be a `ProxyLocation` or str, got: {type(proxy_location)}." + ) + + if proxy_location == ProxyLocation.Disabled: + return DeploymentMode.NoServer + else: + return DeploymentMode(proxy_location.value) + + @classmethod + def _from_deployment_mode( + cls, deployment_mode: Optional[Union[DeploymentMode, str]] + ) -> Optional["ProxyLocation"]: + """Converts DeploymentMode enum into ProxyLocation enum. + + DeploymentMode is a deprecated version of ProxyLocation that's still + used internally throughout Serve. + """ + + if deployment_mode is None: + return None + elif isinstance(deployment_mode, str): + deployment_mode = DeploymentMode(deployment_mode) + elif not isinstance(deployment_mode, DeploymentMode): + raise TypeError( + f"Must be a `DeploymentMode` or str, got: {type(deployment_mode)}." + ) + + if deployment_mode == DeploymentMode.NoServer: + return ProxyLocation.Disabled + else: + return ProxyLocation(deployment_mode.value) + + +@PublicAPI(stability="stable") +class HTTPOptions(BaseModel): + """HTTP options for the proxies. Supported fields: + + - host: Host that the proxies listens for HTTP on. Defaults to + "127.0.0.1". To expose Serve publicly, you probably want to set + this to "0.0.0.0". + - port: Port that the proxies listen for HTTP on. Defaults to 8000. + - root_path: An optional root path to mount the serve application + (for example, "/prefix"). All deployment routes are prefixed + with this path. + - request_timeout_s: End-to-end timeout for HTTP requests. + - keep_alive_timeout_s: Duration to keep idle connections alive when no + requests are ongoing. + + - location: [DEPRECATED: use `proxy_location` field instead] The deployment + location of HTTP servers: + + - "HeadOnly": start one HTTP server on the head node. Serve + assumes the head node is the node you executed serve.start + on. This is the default. + - "EveryNode": start one HTTP server per node. + - "NoServer": disable HTTP server. + + - num_cpus: [DEPRECATED] The number of CPU cores to reserve for each + internal Serve HTTP proxy actor. + """ + + host: Optional[str] = DEFAULT_HTTP_HOST + port: int = DEFAULT_HTTP_PORT + middlewares: List[Any] = [] + location: Optional[DeploymentMode] = DeploymentMode.HeadOnly + num_cpus: int = 0 + root_url: str = "" + root_path: str = "" + request_timeout_s: Optional[float] = None + keep_alive_timeout_s: int = DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S + + @validator("location", always=True) + def location_backfill_no_server(cls, v, values): + if values["host"] is None or v is None: + return DeploymentMode.NoServer + + return v + + @validator("middlewares", always=True) + def warn_for_middlewares(cls, v, values): + if v: + warnings.warn( + "Passing `middlewares` to HTTPOptions is deprecated and will be " + "removed in a future version. Consider using the FastAPI integration " + "to configure middlewares on your deployments: " + "https://docs.ray.io/en/latest/serve/http-guide.html#fastapi-http-deployments" # noqa 501 + ) + return v + + @validator("num_cpus", always=True) + def warn_for_num_cpus(cls, v, values): + if v: + warnings.warn( + "Passing `num_cpus` to HTTPOptions is deprecated and will be " + "removed in a future version." + ) + return v + + class Config: + validate_assignment = True + arbitrary_types_allowed = True + + +@PublicAPI(stability="alpha") +class gRPCOptions(BaseModel): + """gRPC options for the proxies. Supported fields: + + Args: + port (int): + Port for gRPC server if started. Default to 9000. Cannot be + updated once Serve has started running. Serve must be shut down and + restarted with the new port instead. + grpc_servicer_functions (List[str]): + List of import paths for gRPC `add_servicer_to_server` functions to add to + Serve's gRPC proxy. Default to empty list, which means no gRPC methods will + be added and no gRPC server will be started. The servicer functions need to + be importable from the context of where Serve is running. + request_timeout_s: End-to-end timeout for gRPC requests. + """ + + port: int = DEFAULT_GRPC_PORT + grpc_servicer_functions: List[str] = [] + request_timeout_s: Optional[float] = None + + @property + def grpc_servicer_func_callable(self) -> List[Callable]: + """Return a list of callable functions from the grpc_servicer_functions. + + If the function is not callable or not found, it will be ignored and a warning + will be logged. + """ + callables = [] + for func in self.grpc_servicer_functions: + try: + imported_func = import_attr(func) + if callable(imported_func): + callables.append(imported_func) + else: + message = ( + f"{func} is not a callable function! Please make sure " + "the function is imported correctly." + ) + raise ValueError(message) + except ModuleNotFoundError as e: + message = ( + f"{func} can't be imported! Please make sure there are no typo " + "in those functions. Or you might want to rebuild service " + "definitions if .proto file is changed." + ) + raise ModuleNotFoundError(message) from e + + return callables diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/context.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/context.py new file mode 100644 index 0000000000000000000000000000000000000000..ecb412aab37b4379428d6efcdd95d2e683ad3d73 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/context.py @@ -0,0 +1,298 @@ +""" +This file stores global state for a Serve application. Deployment replicas +can use this state to access metadata or the Serve controller. +""" + +import asyncio +import contextvars +import logging +from collections import defaultdict +from dataclasses import dataclass +from typing import Callable, Dict, Optional + +import ray +from ray.exceptions import RayActorError +from ray.serve._private.client import ServeControllerClient +from ray.serve._private.common import ReplicaID +from ray.serve._private.config import DeploymentConfig +from ray.serve._private.constants import ( + SERVE_CONTROLLER_NAME, + SERVE_LOGGER_NAME, + SERVE_NAMESPACE, +) +from ray.serve._private.replica_result import ReplicaResult +from ray.serve.exceptions import RayServeException +from ray.serve.grpc_util import RayServegRPCContext +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + +_INTERNAL_REPLICA_CONTEXT: "ReplicaContext" = None +_global_client: ServeControllerClient = None + + +@DeveloperAPI +@dataclass +class ReplicaContext: + """Stores runtime context info for replicas. + + Fields: + - app_name: name of the application the replica is a part of. + - deployment: name of the deployment the replica is a part of. + - replica_tag: unique ID for the replica. + - servable_object: instance of the user class/function this replica is running. + """ + + replica_id: ReplicaID + servable_object: Callable + _deployment_config: DeploymentConfig + + @property + def app_name(self) -> str: + return self.replica_id.deployment_id.app_name + + @property + def deployment(self) -> str: + return self.replica_id.deployment_id.name + + @property + def replica_tag(self) -> str: + return self.replica_id.unique_id + + +def _get_global_client( + _health_check_controller: bool = False, raise_if_no_controller_running: bool = True +) -> Optional[ServeControllerClient]: + """Gets the global client, which stores the controller's handle. + + Args: + _health_check_controller: If True, run a health check on the + cached controller if it exists. If the check fails, try reconnecting + to the controller. + raise_if_no_controller_running: Whether to raise an exception if + there is no currently running Serve controller. + + Returns: + ServeControllerClient to the running Serve controller. If there + is no running controller and raise_if_no_controller_running is + set to False, returns None. + + Raises: + RayServeException: If there is no running Serve controller actor + and raise_if_no_controller_running is set to True. + """ + + try: + if _global_client is not None: + if _health_check_controller: + ray.get(_global_client._controller.check_alive.remote()) + return _global_client + except RayActorError: + logger.info("The cached controller has died. Reconnecting.") + _set_global_client(None) + + return _connect(raise_if_no_controller_running) + + +def _set_global_client(client): + global _global_client + _global_client = client + + +def _get_internal_replica_context(): + return _INTERNAL_REPLICA_CONTEXT + + +def _set_internal_replica_context( + *, + replica_id: ReplicaID, + servable_object: Callable, + _deployment_config: DeploymentConfig, +): + global _INTERNAL_REPLICA_CONTEXT + _INTERNAL_REPLICA_CONTEXT = ReplicaContext( + replica_id=replica_id, + servable_object=servable_object, + _deployment_config=_deployment_config, + ) + + +def _connect(raise_if_no_controller_running: bool = True) -> ServeControllerClient: + """Connect to an existing Serve application on this Ray cluster. + + If called from within a replica, this will connect to the same Serve + app that the replica is running in. + + Returns: + ServeControllerClient that encapsulates a Ray actor handle to the + existing Serve application's Serve Controller. None if there is + no running Serve controller actor and raise_if_no_controller_running + is set to False. + + Raises: + RayServeException: If there is no running Serve controller actor + and raise_if_no_controller_running is set to True. + """ + + # Initialize ray if needed. + ray._private.worker.global_worker._filter_logs_by_job = False + if not ray.is_initialized(): + ray.init(namespace=SERVE_NAMESPACE) + + # Try to get serve controller if it exists + try: + controller = ray.get_actor(SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE) + except ValueError: + if raise_if_no_controller_running: + raise RayServeException( + "There is no Serve instance running on this Ray cluster." + ) + return + + client = ServeControllerClient( + controller, + ) + _set_global_client(client) + return client + + +# Serve request context var which is used for storing the internal +# request context information. +# route_prefix: http url route path, e.g. http://127.0.0.1:/app +# the route is "/app". When you send requests by handle, +# the route is empty. +# request_id: the request id is generated from http proxy, the value +# shouldn't be changed when the variable is set. +# This can be from the client and is used for logging. +# _internal_request_id: the request id is generated from the proxy. Used to track the +# request objects in the system. +# note: +# The request context is readonly to avoid potential +# async task conflicts when using it concurrently. + + +@dataclass(frozen=True) +class _RequestContext: + route: str = "" + request_id: str = "" + _internal_request_id: str = "" + app_name: str = "" + multiplexed_model_id: str = "" + grpc_context: Optional[RayServegRPCContext] = None + is_http_request: bool = False + cancel_on_parent_request_cancel: bool = False + + +_serve_request_context = contextvars.ContextVar( + "Serve internal request context variable", default=None +) + + +def _get_serve_request_context(): + """Get the current request context. + + Returns: + The current request context + """ + + if _serve_request_context.get() is None: + _serve_request_context.set(_RequestContext()) + return _serve_request_context.get() + + +def _set_request_context( + route: str = "", + request_id: str = "", + _internal_request_id: str = "", + app_name: str = "", + multiplexed_model_id: str = "", +): + """Set the request context. If the value is not set, + the current context value will be used.""" + + current_request_context = _get_serve_request_context() + + _serve_request_context.set( + _RequestContext( + route=route or current_request_context.route, + request_id=request_id or current_request_context.request_id, + _internal_request_id=_internal_request_id + or current_request_context._internal_request_id, + app_name=app_name or current_request_context.app_name, + multiplexed_model_id=multiplexed_model_id + or current_request_context.multiplexed_model_id, + ) + ) + + +# `_requests_pending_assignment` is a map from request ID to a +# dictionary of asyncio tasks. +# The request ID points to an ongoing request that is executing on the +# current replica, and the asyncio tasks are ongoing tasks started on +# the router to assign child requests to downstream replicas. + +# A dictionary is used over a set to track the asyncio tasks for more +# efficient addition and deletion time complexity. A uniquely generated +# `response_id` is used to identify each task. + +_requests_pending_assignment: Dict[str, Dict[str, asyncio.Task]] = defaultdict(dict) + + +# Note that the functions below that manipulate +# `_requests_pending_assignment` are NOT thread-safe. They are only +# expected to be called from the same thread/asyncio event-loop. + + +def _get_requests_pending_assignment(parent_request_id: str) -> Dict[str, asyncio.Task]: + if parent_request_id in _requests_pending_assignment: + return _requests_pending_assignment[parent_request_id] + + return {} + + +def _add_request_pending_assignment(parent_request_id: str, response_id: str, task): + # NOTE: `parent_request_id` is the `internal_request_id` corresponding + # to an ongoing Serve request, so it is always non-empty. + _requests_pending_assignment[parent_request_id][response_id] = task + + +def _remove_request_pending_assignment(parent_request_id: str, response_id: str): + if response_id in _requests_pending_assignment[parent_request_id]: + del _requests_pending_assignment[parent_request_id][response_id] + + if len(_requests_pending_assignment[parent_request_id]) == 0: + del _requests_pending_assignment[parent_request_id] + + +# `_in_flight_requests` is a map from request ID to a dictionary of replica results. +# The request ID points to an ongoing Serve request, and the replica results are +# in-flight child requests that have been assigned to a downstream replica. + +# A dictionary is used over a set to track the replica results for more +# efficient addition and deletion time complexity. A uniquely generated +# `response_id` is used to identify each replica result. + +_in_flight_requests: Dict[str, Dict[str, ReplicaResult]] = defaultdict(dict) + +# Note that the functions below that manipulate `_in_flight_requests` +# are NOT thread-safe. They are only expected to be called from the +# same thread/asyncio event-loop. + + +def _get_in_flight_requests(parent_request_id): + if parent_request_id in _in_flight_requests: + return _in_flight_requests[parent_request_id] + + return {} + + +def _add_in_flight_request(parent_request_id, response_id, replica_result): + _in_flight_requests[parent_request_id][response_id] = replica_result + + +def _remove_in_flight_request(parent_request_id, response_id): + if response_id in _in_flight_requests[parent_request_id]: + del _in_flight_requests[parent_request_id][response_id] + + if len(_in_flight_requests[parent_request_id]) == 0: + del _in_flight_requests[parent_request_id] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/dag.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/dag.py new file mode 100644 index 0000000000000000000000000000000000000000..aee604744557d18c88245fff723480562dbfae67 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/dag.py @@ -0,0 +1,5 @@ +from ray.dag.input_node import InputNode + +__all__ = [ + "InputNode", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/deployment.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/deployment.py new file mode 100644 index 0000000000000000000000000000000000000000..5487ad4d0afccd44c9d4b44f4225ab091634a389 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/deployment.py @@ -0,0 +1,528 @@ +import inspect +import logging +import warnings +from copy import deepcopy +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +from ray.serve._private.config import ( + DeploymentConfig, + ReplicaConfig, + RequestRouterConfig, + handle_num_replicas_auto, +) +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import DEFAULT, Default +from ray.serve.config import AutoscalingConfig +from ray.serve.schema import DeploymentSchema, LoggingConfig, RayActorOptionsSchema +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="stable") +class Application: + """One or more deployments bound with arguments that can be deployed together. + + Can be passed into another `Deployment.bind()` to compose multiple deployments in a + single application, passed to `serve.run`, or deployed via a Serve config file. + + For example, to define an Application and run it in Python: + + .. code-block:: python + + from ray import serve + from ray.serve import Application + + @serve.deployment + class MyDeployment: + pass + + app: Application = MyDeployment.bind(OtherDeployment.bind()) + serve.run(app) + + To run the same app using the command line interface (CLI): + + .. code-block:: bash + + serve run python_file:app + + To deploy the same app via a config file: + + .. code-block:: yaml + + applications: + my_app: + import_path: python_file:app + + """ + + def __init__(self, bound_deployment: "Deployment"): + # This is used by `build_app`, but made private so users don't use it. + self._bound_deployment = bound_deployment + + +@PublicAPI(stability="stable") +class Deployment: + """Class (or function) decorated with the `@serve.deployment` decorator. + + This is run on a number of replica actors. Requests to those replicas call + this class. + + One or more deployments can be composed together into an `Application` which is + then run via `serve.run` or a config file. + + Example: + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self, name: str): + self._name = name + + def __call__(self, request): + return "Hello world!" + + app = MyDeployment.bind() + # Run via `serve.run` or the `serve run` CLI command. + serve.run(app) + + """ + + def __init__( + self, + name: str, + deployment_config: DeploymentConfig, + replica_config: ReplicaConfig, + version: Optional[str] = None, + _internal=False, + ) -> None: + if not _internal: + raise RuntimeError( + "The Deployment constructor should not be called " + "directly. Use `@serve.deployment` instead." + ) + self._validate_name(name) + if not (version is None or isinstance(version, str)): + raise TypeError("version must be a string.") + docs_path = None + if ( + inspect.isclass(replica_config.deployment_def) + and hasattr(replica_config.deployment_def, "__module__") + and replica_config.deployment_def.__module__ == "ray.serve.api" + and hasattr(replica_config.deployment_def, "__fastapi_docs_path__") + ): + docs_path = replica_config.deployment_def.__fastapi_docs_path__ + + self._name = name + self._version = version + self._deployment_config = deployment_config + self._replica_config = replica_config + self._docs_path = docs_path + + def _validate_name(self, name: str): + if not isinstance(name, str): + raise TypeError("name must be a string.") + + # name does not contain # + if "#" in name: + warnings.warn( + f"Deployment names should not contain the '#' character, this will raise an error starting in Ray 2.46.0. " + f"Current name: {name}." + ) + + @property + def name(self) -> str: + """Unique name of this deployment.""" + return self._name + + @property + def version(self) -> Optional[str]: + return self._version + + @property + def func_or_class(self) -> Union[Callable, str]: + """Underlying class or function that this deployment wraps.""" + return self._replica_config.deployment_def + + @property + def num_replicas(self) -> int: + """Target number of replicas.""" + return self._deployment_config.num_replicas + + @property + def user_config(self) -> Any: + """Dynamic user-provided config options.""" + return self._deployment_config.user_config + + @property + def max_ongoing_requests(self) -> int: + """Max number of requests a replica can handle at once.""" + return self._deployment_config.max_ongoing_requests + + @property + def max_queued_requests(self) -> int: + """Max number of requests that can be queued in each deployment handle.""" + return self._deployment_config.max_queued_requests + + @property + def route_prefix(self): + raise ValueError( + "`route_prefix` can no longer be specified at the deployment level. " + "Pass it to `serve.run` or in the application config instead." + ) + + @property + def ray_actor_options(self) -> Optional[Dict]: + """Actor options such as resources required for each replica.""" + return self._replica_config.ray_actor_options + + @property + def init_args(self) -> Tuple[Any]: + return self._replica_config.init_args + + @property + def init_kwargs(self) -> Tuple[Any]: + return self._replica_config.init_kwargs + + @property + def url(self) -> Optional[str]: + logger.warning( + "DeprecationWarning: `Deployment.url` is deprecated " + "and will be removed in the future." + ) + return None + + @property + def logging_config(self) -> Dict: + return self._deployment_config.logging_config + + def set_logging_config(self, logging_config: Dict): + self._deployment_config.logging_config = logging_config + + def __call__(self): + raise RuntimeError( + "Deployments cannot be constructed directly. " + "Use `deployment.deploy() instead.`" + ) + + def bind(self, *args, **kwargs) -> Application: + """Bind the arguments to the deployment and return an Application. + + The returned Application can be deployed using `serve.run` (or via + config file) or bound to another deployment for composition. + """ + return Application(self.options(_init_args=args, _init_kwargs=kwargs)) + + def options( + self, + func_or_class: Optional[Callable] = None, + name: Default[str] = DEFAULT.VALUE, + version: Default[str] = DEFAULT.VALUE, + num_replicas: Default[Optional[Union[int, str]]] = DEFAULT.VALUE, + route_prefix: Default[Union[str, None]] = DEFAULT.VALUE, + ray_actor_options: Default[Optional[Dict]] = DEFAULT.VALUE, + placement_group_bundles: Default[List[Dict[str, float]]] = DEFAULT.VALUE, + placement_group_strategy: Default[str] = DEFAULT.VALUE, + max_replicas_per_node: Default[int] = DEFAULT.VALUE, + user_config: Default[Optional[Any]] = DEFAULT.VALUE, + max_ongoing_requests: Default[int] = DEFAULT.VALUE, + max_queued_requests: Default[int] = DEFAULT.VALUE, + autoscaling_config: Default[ + Union[Dict, AutoscalingConfig, None] + ] = DEFAULT.VALUE, + graceful_shutdown_wait_loop_s: Default[float] = DEFAULT.VALUE, + graceful_shutdown_timeout_s: Default[float] = DEFAULT.VALUE, + health_check_period_s: Default[float] = DEFAULT.VALUE, + health_check_timeout_s: Default[float] = DEFAULT.VALUE, + logging_config: Default[Union[Dict, LoggingConfig, None]] = DEFAULT.VALUE, + request_router_config: Default[ + Union[Dict, RequestRouterConfig, None] + ] = DEFAULT.VALUE, + _init_args: Default[Tuple[Any]] = DEFAULT.VALUE, + _init_kwargs: Default[Dict[Any, Any]] = DEFAULT.VALUE, + _internal: bool = False, + ) -> "Deployment": + """Return a copy of this deployment with updated options. + + Only those options passed in will be updated, all others will remain + unchanged from the existing deployment. + + Refer to the `@serve.deployment` decorator docs for available arguments. + """ + if route_prefix is not DEFAULT.VALUE: + raise ValueError( + "`route_prefix` can no longer be specified at the deployment level. " + "Pass it to `serve.run` or in the application config instead." + ) + + # Modify max_ongoing_requests and autoscaling_config if + # `num_replicas="auto"` + if max_ongoing_requests is None: + raise ValueError("`max_ongoing_requests` must be non-null, got None.") + if num_replicas == "auto": + num_replicas = None + max_ongoing_requests, autoscaling_config = handle_num_replicas_auto( + max_ongoing_requests, autoscaling_config + ) + + ServeUsageTag.AUTO_NUM_REPLICAS_USED.record("1") + + # NOTE: The user_configured_option_names should be the first thing that's + # defined in this method. It depends on the locals() dictionary storing + # only the function args/kwargs. + # Create list of all user-configured options from keyword args + user_configured_option_names = [ + option + for option, value in locals().items() + if option not in {"self", "func_or_class", "_internal"} + and value is not DEFAULT.VALUE + ] + + new_deployment_config = deepcopy(self._deployment_config) + if not _internal: + new_deployment_config.user_configured_option_names.update( + user_configured_option_names + ) + + if num_replicas not in [ + DEFAULT.VALUE, + None, + "auto", + ] and autoscaling_config not in [ + DEFAULT.VALUE, + None, + ]: + raise ValueError( + "Manually setting num_replicas is not allowed when " + "autoscaling_config is provided." + ) + + if num_replicas == 0: + raise ValueError("num_replicas is expected to larger than 0") + + if not _internal and version is not DEFAULT.VALUE: + logger.warning( + "DeprecationWarning: `version` in `Deployment.options()` has been " + "deprecated. Explicitly specifying version will raise an error in the " + "future!" + ) + + elif num_replicas not in [DEFAULT.VALUE, None]: + new_deployment_config.num_replicas = num_replicas + + if user_config is not DEFAULT.VALUE: + new_deployment_config.user_config = user_config + + if max_ongoing_requests is not DEFAULT.VALUE: + new_deployment_config.max_ongoing_requests = max_ongoing_requests + + if max_queued_requests is not DEFAULT.VALUE: + new_deployment_config.max_queued_requests = max_queued_requests + + if func_or_class is None: + func_or_class = self._replica_config.deployment_def + + if name is DEFAULT.VALUE: + name = self._name + + if version is DEFAULT.VALUE: + version = self._version + + if _init_args is DEFAULT.VALUE: + _init_args = self._replica_config.init_args + + if _init_kwargs is DEFAULT.VALUE: + _init_kwargs = self._replica_config.init_kwargs + + if ray_actor_options is DEFAULT.VALUE: + ray_actor_options = self._replica_config.ray_actor_options + + if placement_group_bundles is DEFAULT.VALUE: + placement_group_bundles = self._replica_config.placement_group_bundles + + if placement_group_strategy is DEFAULT.VALUE: + placement_group_strategy = self._replica_config.placement_group_strategy + + if max_replicas_per_node is DEFAULT.VALUE: + max_replicas_per_node = self._replica_config.max_replicas_per_node + + if autoscaling_config is not DEFAULT.VALUE: + new_deployment_config.autoscaling_config = autoscaling_config + + if request_router_config is not DEFAULT.VALUE: + new_deployment_config.request_router_config = request_router_config + + if graceful_shutdown_wait_loop_s is not DEFAULT.VALUE: + new_deployment_config.graceful_shutdown_wait_loop_s = ( + graceful_shutdown_wait_loop_s + ) + + if graceful_shutdown_timeout_s is not DEFAULT.VALUE: + new_deployment_config.graceful_shutdown_timeout_s = ( + graceful_shutdown_timeout_s + ) + + if health_check_period_s is not DEFAULT.VALUE: + new_deployment_config.health_check_period_s = health_check_period_s + + if health_check_timeout_s is not DEFAULT.VALUE: + new_deployment_config.health_check_timeout_s = health_check_timeout_s + + if logging_config is not DEFAULT.VALUE: + if isinstance(logging_config, LoggingConfig): + logging_config = logging_config.dict() + new_deployment_config.logging_config = logging_config + + new_replica_config = ReplicaConfig.create( + func_or_class, + init_args=_init_args, + init_kwargs=_init_kwargs, + ray_actor_options=ray_actor_options, + placement_group_bundles=placement_group_bundles, + placement_group_strategy=placement_group_strategy, + max_replicas_per_node=max_replicas_per_node, + ) + + return Deployment( + name, + new_deployment_config, + new_replica_config, + version=version, + _internal=True, + ) + + def __eq__(self, other): + return all( + [ + self._name == other._name, + self._version == other._version, + self._deployment_config == other._deployment_config, + self._replica_config.init_args == other._replica_config.init_args, + self._replica_config.init_kwargs == other._replica_config.init_kwargs, + self._replica_config.ray_actor_options + == other._replica_config.ray_actor_options, + ] + ) + + def __str__(self): + return f"Deployment(name={self._name})" + + def __repr__(self): + return str(self) + + +def deployment_to_schema(d: Deployment) -> DeploymentSchema: + """Converts a live deployment object to a corresponding structured schema. + + Args: + d: Deployment object to convert + """ + + if d.ray_actor_options is not None: + ray_actor_options_schema = RayActorOptionsSchema.parse_obj(d.ray_actor_options) + else: + ray_actor_options_schema = None + + deployment_options = { + "name": d.name, + "num_replicas": None + if d._deployment_config.autoscaling_config + else d.num_replicas, + "max_ongoing_requests": d.max_ongoing_requests, + "max_queued_requests": d.max_queued_requests, + "user_config": d.user_config, + "autoscaling_config": d._deployment_config.autoscaling_config, + "graceful_shutdown_wait_loop_s": d._deployment_config.graceful_shutdown_wait_loop_s, # noqa: E501 + "graceful_shutdown_timeout_s": d._deployment_config.graceful_shutdown_timeout_s, + "health_check_period_s": d._deployment_config.health_check_period_s, + "health_check_timeout_s": d._deployment_config.health_check_timeout_s, + "ray_actor_options": ray_actor_options_schema, + "placement_group_strategy": d._replica_config.placement_group_strategy, + "placement_group_bundles": d._replica_config.placement_group_bundles, + "max_replicas_per_node": d._replica_config.max_replicas_per_node, + "logging_config": d._deployment_config.logging_config, + "request_router_config": d._deployment_config.request_router_config, + } + + # Let non-user-configured options be set to defaults. If the schema + # is converted back to a deployment, this lets Serve continue tracking + # which options were set by the user. Name is a required field in the + # schema, so it should be passed in explicitly. + for option in list(deployment_options.keys()): + if ( + option != "name" + and option not in d._deployment_config.user_configured_option_names + ): + del deployment_options[option] + + # TODO(Sihan) DeploymentConfig num_replicas and auto_config can be set together + # because internally we use these two field for autoscale and deploy. + # We can improve the code after we separate the user faced deployment config and + # internal deployment config. + return DeploymentSchema(**deployment_options) + + +def schema_to_deployment(s: DeploymentSchema) -> Deployment: + """Creates a deployment with parameters specified in schema. + + The returned deployment CANNOT be deployed immediately. It's func_or_class + value is an empty string (""), which is not a valid import path. The + func_or_class value must be overwritten with a valid function or class + before the deployment can be deployed. + """ + + if s.ray_actor_options is DEFAULT.VALUE: + ray_actor_options = None + else: + ray_actor_options = s.ray_actor_options.dict(exclude_unset=True) + + if s.placement_group_bundles is DEFAULT.VALUE: + placement_group_bundles = None + else: + placement_group_bundles = s.placement_group_bundles + + if s.placement_group_strategy is DEFAULT.VALUE: + placement_group_strategy = None + else: + placement_group_strategy = s.placement_group_strategy + + if s.max_replicas_per_node is DEFAULT.VALUE: + max_replicas_per_node = None + else: + max_replicas_per_node = s.max_replicas_per_node + + deployment_config = DeploymentConfig.from_default( + num_replicas=s.num_replicas, + user_config=s.user_config, + max_ongoing_requests=s.max_ongoing_requests, + max_queued_requests=s.max_queued_requests, + autoscaling_config=s.autoscaling_config, + graceful_shutdown_wait_loop_s=s.graceful_shutdown_wait_loop_s, + graceful_shutdown_timeout_s=s.graceful_shutdown_timeout_s, + health_check_period_s=s.health_check_period_s, + health_check_timeout_s=s.health_check_timeout_s, + logging_config=s.logging_config, + request_router_config=s.request_router_config, + ) + deployment_config.user_configured_option_names = ( + s._get_user_configured_option_names() + ) + + replica_config = ReplicaConfig.create( + deployment_def="", + init_args=(), + init_kwargs={}, + ray_actor_options=ray_actor_options, + placement_group_bundles=placement_group_bundles, + placement_group_strategy=placement_group_strategy, + max_replicas_per_node=max_replicas_per_node, + ) + + return Deployment( + name=s.name, + deployment_config=deployment_config, + replica_config=replica_config, + _internal=True, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/exceptions.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..10033b28f9cd366fbe27fc78383a46340d71fb34 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/exceptions.py @@ -0,0 +1,59 @@ +from typing import Optional + +from ray.exceptions import TaskCancelledError +from ray.serve._private.common import DeploymentID +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="stable") +class RayServeException(Exception): + pass + + +@PublicAPI(stability="alpha") +class BackPressureError(RayServeException): + """Raised when max_queued_requests is exceeded on a DeploymentHandle.""" + + def __init__(self, num_queued_requests: int, max_queued_requests: int): + super().__init__(num_queued_requests, max_queued_requests) + self._message = ( + f"Request dropped due to backpressure " + f"(num_queued_requests={num_queued_requests}, " + f"max_queued_requests={max_queued_requests})." + ) + + def __str__(self) -> str: + return self._message + + @property + def message(self) -> str: + return self._message + + +@PublicAPI(stability="alpha") +class RequestCancelledError(RayServeException, TaskCancelledError): + """Raise when a Serve request is cancelled.""" + + def __init__(self, request_id: Optional[str] = None): + self._request_id: Optional[str] = request_id + + def __str__(self): + if self._request_id: + return f"Request {self._request_id} was cancelled." + else: + return "Request was cancelled." + + +@PublicAPI(stability="alpha") +class DeploymentUnavailableError(RayServeException): + """Raised when a Serve deployment is unavailable to receive requests. + + Currently this happens because the deployment failed to deploy. + """ + + def __init__(self, deployment_id: DeploymentID): + self._deployment_id = deployment_id + + @property + def message(self) -> str: + return f"{self._deployment_id} is unavailable because it failed to deploy." diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/gradio_integrations.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/gradio_integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8960d78c8b41da612a2e35e41310d729e53350 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/gradio_integrations.py @@ -0,0 +1,32 @@ +import logging +from typing import Callable + +from ray import serve +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.http_util import ASGIAppReplicaWrapper +from ray.util.annotations import PublicAPI + +try: + from gradio import Blocks, routes +except ModuleNotFoundError: + print("Gradio isn't installed. Run `pip install gradio` to install Gradio.") + raise + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +@PublicAPI(stability="alpha") +class GradioIngress(ASGIAppReplicaWrapper): + """User-facing class that wraps a Gradio App in a Serve Deployment.""" + + def __init__(self, builder: Callable[[], Blocks]): + """Builds and wraps an ASGI app from the provided builder. + + The builder should take no arguments and return a Gradio App (of type Interface + or Blocks). + """ + io: Blocks = builder() + super().__init__(routes.App.create_app(io)) + + +GradioServer = serve.deployment(GradioIngress) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/grpc_util.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/grpc_util.py new file mode 100644 index 0000000000000000000000000000000000000000..2b258c5a261437041f98afcd2089b51b2e4a48fb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/grpc_util.py @@ -0,0 +1,169 @@ +from typing import Any, Dict, List, Optional, Tuple + +import grpc + +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +class RayServegRPCContext: + """Context manager to set and get gRPC context. + + This class implements most of the methods from ServicerContext + (see: https://grpc.github.io/grpc/python/grpc.html#grpc.ServicerContext). It's + serializable and can be passed with the request to be used on the deployment. + """ + + def __init__(self, grpc_context: grpc._cython.cygrpc._ServicerContext): + self._auth_context = grpc_context.auth_context() + self._code = grpc_context.code() + self._details = grpc_context.details() + self._invocation_metadata = [ # noqa: C416 + (key, value) for key, value in grpc_context.invocation_metadata() + ] + self._peer = grpc_context.peer() + self._peer_identities = grpc_context.peer_identities() + self._peer_identity_key = grpc_context.peer_identity_key() + self._trailing_metadata = [ # noqa: C416 + (key, value) for key, value in grpc_context.trailing_metadata() + ] + self._compression = None + + def auth_context(self) -> Dict[str, Any]: + """Gets the auth context for the call. + + Returns: + A map of strings to an iterable of bytes for each auth property. + """ + return self._auth_context + + def code(self) -> grpc.StatusCode: + """Accesses the value to be used as status code upon RPC completion. + + Returns: + The StatusCode value for the RPC. + """ + return self._code + + def details(self) -> str: + """Accesses the value to be used as detail string upon RPC completion. + + Returns: + The details string of the RPC. + """ + return self._details + + def invocation_metadata(self) -> List[Tuple[str, str]]: + """Accesses the metadata sent by the client. + + Returns: + The invocation :term:`metadata`. + """ + return self._invocation_metadata + + def peer(self) -> str: + """Identifies the peer that invoked the RPC being serviced. + + Returns: + A string identifying the peer that invoked the RPC being serviced. + The string format is determined by gRPC runtime. + """ + return self._peer + + def peer_identities(self) -> Optional[bytes]: + """Gets one or more peer identity(s). + + Equivalent to + servicer_context.auth_context().get(servicer_context.peer_identity_key()) + + Returns: + An iterable of the identities, or None if the call is not + authenticated. Each identity is returned as a raw bytes type. + """ + return self._peer_identities + + def peer_identity_key(self) -> Optional[str]: + """The auth property used to identify the peer. + + For example, "x509_common_name" or "x509_subject_alternative_name" are + used to identify an SSL peer. + + Returns: + The auth property (string) that indicates the + peer identity, or None if the call is not authenticated. + """ + return self._peer_identity_key + + def trailing_metadata(self) -> List[Tuple[str, str]]: + return self._trailing_metadata + + def set_code(self, code: grpc.StatusCode): + """Sets the value to be used as status code upon RPC completion. + + This method need not be called by method implementations if they wish + the gRPC runtime to determine the status code of the RPC. + + Args: + code: A StatusCode object to be sent to the client. + """ + self._code = code + + def set_compression(self, compression: grpc.Compression): + """Set the compression algorithm to be used for the entire call. + + Args: + compression: An element of grpc.compression, e.g. + grpc.compression.Gzip. + """ + self._compression = compression + + def set_details(self, details: str): + """Sets the value to be used as detail string upon RPC completion. + + Calling this method is only needed if method implementations have + details to transmit. + + Args: + details: A UTF-8-encodable string to be sent to the client upon + termination of the RPC. + """ + self._details = details + + def _request_id_metadata(self) -> List[Tuple[str, str]]: + # Request id metadata should be carried over to the trailing metadata and passed + # back to the request client. This function helps pick it out if it exists. + for key, value in self._trailing_metadata: + if key == "request_id": + return [(key, value)] + return [] + + def set_trailing_metadata(self, trailing_metadata: List[Tuple[str, str]]): + """Sets the trailing metadata for the RPC. + + Sets the trailing metadata to be sent upon completion of the RPC. + + If this method is invoked multiple times throughout the lifetime of an + RPC, the value supplied in the final invocation + request id will be the value + sent over the wire. + + This method need not be called by implementations if they have no + metadata to add to what the gRPC runtime will transmit. + + Args: + trailing_metadata: The trailing :term:`metadata`. + """ + self._trailing_metadata = self._request_id_metadata() + trailing_metadata + + def _set_on_grpc_context(self, grpc_context: grpc._cython.cygrpc._ServicerContext): + """Serve's internal method to set attributes on the gRPC context.""" + if self._code: + grpc_context.set_code(self._code) + + if self._compression: + grpc_context.set_compression(self._compression) + + if self._details: + grpc_context.set_details(self._details) + + if self._trailing_metadata: + grpc_context.set_trailing_metadata(self._trailing_metadata) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/handle.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/handle.py new file mode 100644 index 0000000000000000000000000000000000000000..a3c686553f99cbcb0de75d22ec8ba5accc06e986 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/handle.py @@ -0,0 +1,752 @@ +import asyncio +import concurrent.futures +import logging +import time +import warnings +from typing import Any, AsyncIterator, Dict, Iterator, Optional, Tuple, Union + +import ray +from ray import serve +from ray._raylet import ObjectRefGenerator +from ray.serve._private.common import ( + DeploymentHandleSource, + DeploymentID, + RequestMetadata, +) +from ray.serve._private.constants import SERVE_LOGGER_NAME +from ray.serve._private.default_impl import ( + CreateRouterCallable, + create_dynamic_handle_options, + create_init_handle_options, + create_router, +) +from ray.serve._private.handle_options import ( + DynamicHandleOptionsBase, + InitHandleOptionsBase, +) +from ray.serve._private.replica_result import ReplicaResult +from ray.serve._private.router import Router +from ray.serve._private.usage import ServeUsageTag +from ray.serve._private.utils import ( + DEFAULT, + calculate_remaining_timeout, + get_random_string, + inside_ray_client_context, + is_running_in_asyncio_loop, +) +from ray.serve.exceptions import RayServeException, RequestCancelledError +from ray.util import metrics +from ray.util.annotations import DeveloperAPI, PublicAPI + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class _DeploymentHandleBase: + def __init__( + self, + deployment_name: str, + app_name: str, + *, + init_options: Optional[InitHandleOptionsBase] = None, + handle_options: Optional[DynamicHandleOptionsBase] = None, + _router: Optional[Router] = None, + _create_router: Optional[CreateRouterCallable] = None, + _request_counter: Optional[metrics.Counter] = None, + _handle_id: Optional[str] = None, + ): + self.deployment_id = DeploymentID(name=deployment_name, app_name=app_name) + self.init_options: Optional[InitHandleOptionsBase] = init_options + self.handle_options: DynamicHandleOptionsBase = ( + handle_options or create_dynamic_handle_options() + ) + + # Handle ID is shared among handles that are returned by + # `handle.options` or `handle.method` + self.handle_id = _handle_id or get_random_string() + self.request_counter = _request_counter or self._create_request_counter( + app_name, deployment_name, self.handle_id + ) + + self._router: Optional[Router] = _router + if _create_router is None: + self._create_router = create_router + else: + self._create_router = _create_router + + @staticmethod + def _gen_handle_tag(app_name: str, deployment_name: str, handle_id: str): + if app_name: + return f"{app_name}#{deployment_name}#{handle_id}" + else: + return f"{deployment_name}#{handle_id}" + + @classmethod + def _create_request_counter( + cls, app_name: str, deployment_name: str, handle_id: str + ): + return metrics.Counter( + "serve_handle_request_counter", + description=( + "The number of handle.remote() calls that have been " + "made on this handle." + ), + tag_keys=("handle", "deployment", "route", "application"), + ).set_default_tags( + { + "handle": cls._gen_handle_tag( + app_name, deployment_name, handle_id=handle_id + ), + "deployment": deployment_name, + "application": app_name, + } + ) + + def running_replicas_populated(self) -> bool: + if self._router is None: + return False + + return self._router.running_replicas_populated() + + @property + def deployment_name(self) -> str: + return self.deployment_id.name + + @property + def app_name(self) -> str: + return self.deployment_id.app_name + + @property + def is_initialized(self) -> bool: + return self._router is not None + + def _init(self, **kwargs): + """Initialize this handle with arguments. + + A handle can only be initialized once. A handle is implicitly + initialized when `.options()` or `.remote()` is called. Therefore + to initialize a handle with custom init options, you must do it + before calling `.options()` or `.remote()`. + """ + if self._router is not None: + raise RuntimeError( + "Handle has already been initialized. Note that a handle is implicitly " + "initialized when you call `.options()` or `.remote()`. You either " + "tried to call `._init()` twice or called `._init()` after calling " + "`.options()` or `.remote()`. If you want to modify the init options, " + "please do so before calling `.options()` or `.remote()`. This handle " + f"was initialized with {self.init_options}." + ) + + init_options = create_init_handle_options(**kwargs) + self._router = self._create_router( + handle_id=self.handle_id, + deployment_id=self.deployment_id, + handle_options=init_options, + ) + self.init_options = init_options + + logger.info( + f"Initialized DeploymentHandle {self.handle_id} for {self.deployment_id}.", + extra={"log_to_stderr": False}, + ) + + # Record handle api telemetry when not in the proxy + if ( + self.init_options._source != DeploymentHandleSource.PROXY + and self.__class__ == DeploymentHandle + ): + ServeUsageTag.DEPLOYMENT_HANDLE_API_USED.record("1") + + def _options(self, _prefer_local_routing=DEFAULT.VALUE, **kwargs): + if kwargs.get("stream") is True and inside_ray_client_context(): + raise RuntimeError( + "Streaming DeploymentHandles are not currently supported when " + "connected to a remote Ray cluster using Ray Client." + ) + + new_handle_options = self.handle_options.copy_and_update(**kwargs) + + # TODO(zcin): remove when _prefer_local_routing is removed from options() path + if _prefer_local_routing != DEFAULT.VALUE: + self._init(_prefer_local_routing=_prefer_local_routing) + + if not self.is_initialized: + self._init() + + return DeploymentHandle( + self.deployment_name, + self.app_name, + init_options=self.init_options, + handle_options=new_handle_options, + _router=self._router, + _create_router=self._create_router, + _request_counter=self.request_counter, + _handle_id=self.handle_id, + ) + + def _remote( + self, + args: Tuple[Any], + kwargs: Dict[str, Any], + ) -> Tuple[concurrent.futures.Future, RequestMetadata]: + if not self.is_initialized: + self._init() + + metadata = serve._private.default_impl.get_request_metadata( + self.init_options, self.handle_options + ) + + self.request_counter.inc( + tags={ + "route": metadata.route, + "application": metadata.app_name, + } + ) + + return self._router.assign_request(metadata, *args, **kwargs), metadata + + def __getattr__(self, name): + return self.options(method_name=name) + + def shutdown(self): + if self._router: + shutdown_future = self._router.shutdown() + shutdown_future.result() + + async def shutdown_async(self): + if self._router: + shutdown_future = self._router.shutdown() + await asyncio.wrap_future(shutdown_future) + + def __repr__(self): + return f"{self.__class__.__name__}" f"(deployment='{self.deployment_name}')" + + @classmethod + def _deserialize(cls, kwargs): + """Required for this class's __reduce__ method to be picklable.""" + return cls(**kwargs) + + def __reduce__(self): + serialized_constructor_args = { + "deployment_name": self.deployment_name, + "app_name": self.app_name, + "handle_options": self.handle_options, + } + return self.__class__._deserialize, (serialized_constructor_args,) + + +class _DeploymentResponseBase: + def __init__( + self, + replica_result_future: concurrent.futures.Future[ReplicaResult], + request_metadata: RequestMetadata, + ): + self._cancelled = False + self._replica_result_future = replica_result_future + self._replica_result: Optional[ReplicaResult] = None + self._request_metadata: RequestMetadata = request_metadata + + @property + def request_id(self) -> str: + return self._request_metadata.request_id + + def _fetch_future_result_sync( + self, _timeout_s: Optional[float] = None + ) -> ReplicaResult: + """Synchronously fetch the replica result. + + The result is cached in `self._replica_result`. + """ + + if self._replica_result is None: + try: + self._replica_result = self._replica_result_future.result( + timeout=_timeout_s + ) + except concurrent.futures.TimeoutError: + raise TimeoutError("Timed out resolving to ObjectRef.") from None + except concurrent.futures.CancelledError: + raise RequestCancelledError(self.request_id) from None + + return self._replica_result + + async def _fetch_future_result_async(self) -> ReplicaResult: + """Asynchronously fetch replica result. + + The result is cached in `self._replica_result`.. + """ + + if self._replica_result is None: + # Use `asyncio.wrap_future` so `self._replica_result_future` can be awaited + # safely from any asyncio loop. + self._replica_result = await asyncio.wrap_future( + self._replica_result_future + ) + + return self._replica_result + + def cancel(self): + """Attempt to cancel the `DeploymentHandle` call. + + This is best effort. + + - If the request hasn't been assigned to a replica, the assignment will be + cancelled. + - If the request has been assigned to a replica, `ray.cancel` will be + called on the object ref, attempting to cancel the request and any downstream + requests it makes. + + If the request is successfully cancelled, subsequent operations on the ref will + raise an exception: + + - If the request was cancelled before assignment, they'll raise + `asyncio.CancelledError` (or a `concurrent.futures.CancelledError` for + synchronous methods like `.result()`.). + - If the request was cancelled after assignment, they'll raise + `ray.exceptions.TaskCancelledError`. + """ + if self._cancelled: + return + + self._cancelled = True + self._replica_result_future.cancel() + try: + # try to fetch the results synchronously. if it succeeds, + # we will explicitly cancel the replica result. if it fails, + # the request is already cancelled and we can return early. + self._fetch_future_result_sync() + except RequestCancelledError: + # request is already cancelled nothing to do here + return + self._replica_result.cancel() + + @DeveloperAPI + def cancelled(self) -> bool: + """Whether or not the request has been cancelled. + + This is `True` if `.cancel()` is called, but the request may actually have run + to completion. + """ + return self._cancelled + + +@PublicAPI(stability="stable") +class DeploymentResponse(_DeploymentResponseBase): + """A future-like object wrapping the result of a unary deployment handle call. + + From inside a deployment, a `DeploymentResponse` can be awaited to retrieve the + output of the call without blocking the asyncio event loop. + + From outside a deployment, `.result()` can be used to retrieve the output in a + blocking manner. + + Example: + + .. code-block:: python + + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Downstream: + def say_hi(self, message: str) -> str: + return f"Hello {message}!" + + @serve.deployment + class Caller: + def __init__(self, handle: DeploymentHandle): + self._downstream_handle = handle + + async def __call__(self, message: str) -> str: + # Inside a deployment: `await` the result to enable concurrency. + response = self._downstream_handle.say_hi.remote(message) + return await response + + app = Caller.bind(Downstream.bind()) + handle: DeploymentHandle = serve.run(app) + + # Outside a deployment: call `.result()` to get output. + response = handle.remote("world") + assert response.result() == "Hello world!" + + A `DeploymentResponse` can be passed directly to another `DeploymentHandle` call + without fetching the result to enable composing multiple deployments together. + + Example: + + .. code-block:: python + + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Adder: + def add(self, val: int) -> int: + return val + 1 + + @serve.deployment + class Caller: + def __init__(self, handle: DeploymentHandle): + self._adder_handle = handle + + async def __call__(self, start: int) -> int: + return await self._adder_handle.add.remote( + # Pass the response directly to another handle call without awaiting. + self._adder_handle.add.remote(start) + ) + + app = Caller.bind(Adder.bind()) + handle: DeploymentHandle = serve.run(app) + assert handle.remote(0).result() == 2 + """ + + def __await__(self): + """Yields the final result of the deployment handle call.""" + try: + replica_result = yield from self._fetch_future_result_async().__await__() + result = yield from replica_result.get_async().__await__() + return result + except asyncio.CancelledError: + if self._cancelled: + raise RequestCancelledError(self.request_id) from None + else: + raise asyncio.CancelledError from None + + def __reduce__(self): + raise RayServeException( + "`DeploymentResponse` is not serializable. If you are passing the " + "`DeploymentResponse` in a nested object (e.g. a list or dictionary) to a " + "downstream deployment handle call, that is no longer supported. Please " + "only pass `DeploymentResponse` objects as top level arguments." + ) + + def result( + self, + *, + timeout_s: Optional[float] = None, + _skip_asyncio_check: bool = False, + ) -> Any: + """Fetch the result of the handle call synchronously. + + This should *not* be used from within a deployment as it runs in an asyncio + event loop. For model composition, `await` the response instead. + + If `timeout_s` is provided and the result is not available before the timeout, + a `TimeoutError` is raised. + """ + + if not _skip_asyncio_check and is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `await response` instead." + ) + + start_time_s = time.time() + replica_result = self._fetch_future_result_sync(timeout_s) + + remaining_timeout_s = calculate_remaining_timeout( + timeout_s=timeout_s, start_time_s=start_time_s, curr_time_s=time.time() + ) + return replica_result.get(remaining_timeout_s) + + @DeveloperAPI + async def _to_object_ref(self) -> ray.ObjectRef: + """Advanced API to convert the response to a Ray `ObjectRef`. + + This is used to pass the output of a `DeploymentHandle` call to a Ray task or + actor method call. + + This method is `async def` because it will block until the handle call has been + assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + replica_result = await self._fetch_future_result_async() + return await replica_result.to_object_ref_async() + + @DeveloperAPI + def _to_object_ref_sync( + self, + _timeout_s: Optional[float] = None, + _allow_running_in_asyncio_loop: bool = False, + ) -> ray.ObjectRef: + """Advanced API to convert the response to a Ray `ObjectRef`. + + This is used to pass the output of a `DeploymentHandle` call to a Ray task or + actor method call. + + This method is a *blocking* call because it will block until the handle call has + been assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + + From inside a deployment, `_to_object_ref` should be used instead to avoid + blocking the asyncio event loop. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + if not _allow_running_in_asyncio_loop and is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `await response._to_object_ref()` instead." + ) + + # First, fetch the result of the future + start_time_s = time.time() + replica_result = self._fetch_future_result_sync(_timeout_s) + + # Then, if necessary, resolve generator to ref + remaining_timeout_s = calculate_remaining_timeout( + timeout_s=_timeout_s, + start_time_s=start_time_s, + curr_time_s=time.time(), + ) + return replica_result.to_object_ref(timeout_s=remaining_timeout_s) + + +@PublicAPI(stability="stable") +class DeploymentResponseGenerator(_DeploymentResponseBase): + """A future-like object wrapping the result of a streaming deployment handle call. + + This is returned when using `handle.options(stream=True)` and calling a generator + deployment method. + + `DeploymentResponseGenerator` is both a synchronous and asynchronous iterator. + + When iterating over results from inside a deployment, `async for` should be used to + avoid blocking the asyncio event loop. + + When iterating over results from outside a deployment, use a standard `for` loop. + + Example: + + .. code-block:: python + + from typing import AsyncGenerator, Generator + + from ray import serve + from ray.serve.handle import DeploymentHandle + + @serve.deployment + class Streamer: + def generate_numbers(self, limit: int) -> Generator[int]: + for i in range(limit): + yield i + + @serve.deployment + class Caller: + def __init__(self, handle: DeploymentHandle): + # Set `stream=True` on the handle to enable streaming calls. + self._streaming_handle = handle.options(stream=True) + + async def __call__(self, limit: int) -> AsyncIterator[int]: + gen: DeploymentResponseGenerator = ( + self._streaming_handle.generate_numbers.remote(limit) + ) + + # Inside a deployment: use `async for` to enable concurrency. + async for i in gen: + yield i + + app = Caller.bind(Streamer.bind()) + handle: DeploymentHandle = serve.run(app) + + # Outside a deployment: use a standard `for` loop. + gen: DeploymentResponseGenerator = handle.options(stream=True).remote(10) + assert [i for i in gen] == list(range(10)) + + A `DeploymentResponseGenerator` *cannot* currently be passed to another + `DeploymentHandle` call. + """ + + def __await__(self): + raise TypeError( + "`DeploymentResponseGenerator` cannot be awaited directly. Use `async for` " + "or `await response.__anext__() instead`." + ) + + def __aiter__(self) -> AsyncIterator[Any]: + return self + + async def __anext__(self) -> Any: + try: + replica_result = await self._fetch_future_result_async() + return await replica_result.__anext__() + except asyncio.CancelledError: + if self._cancelled: + raise RequestCancelledError(self.request_id) from None + else: + raise asyncio.CancelledError from None + + def __iter__(self) -> Iterator[Any]: + return self + + def __next__(self) -> Any: + if is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `async for` or `await response.__anext__()` instead." + ) + + replica_result = self._fetch_future_result_sync() + return replica_result.__next__() + + @DeveloperAPI + async def _to_object_ref_gen(self) -> ObjectRefGenerator: + """Advanced API to convert the generator to a Ray `ObjectRefGenerator`. + + This method is `async def` because it will block until the handle call has been + assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + replica_result = await self._fetch_future_result_async() + return replica_result.to_object_ref_gen() + + @DeveloperAPI + def _to_object_ref_gen_sync( + self, + _timeout_s: Optional[float] = None, + _allow_running_in_asyncio_loop: bool = False, + ) -> ObjectRefGenerator: + """Advanced API to convert the generator to a Ray `ObjectRefGenerator`. + + This method is a *blocking* call because it will block until the handle call has + been assigned to a replica. If there are many requests in flight and all + replicas' queues are full, this may be a slow operation. + + From inside a deployment, `_to_object_ref_gen` should be used instead to avoid + blocking the asyncio event loop. + """ + + ServeUsageTag.DEPLOYMENT_HANDLE_TO_OBJECT_REF_API_USED.record("1") + + if not _allow_running_in_asyncio_loop and is_running_in_asyncio_loop(): + raise RuntimeError( + "Sync methods should not be called from within an `asyncio` event " + "loop. Use `await response._to_object_ref()` instead." + ) + + replica_result = self._fetch_future_result_sync(_timeout_s) + return replica_result.to_object_ref_gen() + + +@PublicAPI(stability="stable") +class DeploymentHandle(_DeploymentHandleBase): + """A handle used to make requests to a deployment at runtime. + + This is primarily used to compose multiple deployments within a single application. + It can also be used to make calls to the ingress deployment of an application (e.g., + for programmatic testing). + + Example: + + + .. code-block:: python + + import ray + from ray import serve + from ray.serve.handle import DeploymentHandle, DeploymentResponse + + @serve.deployment + class Downstream: + def say_hi(self, message: str): + return f"Hello {message}!" + self._message = message + + @serve.deployment + class Ingress: + def __init__(self, handle: DeploymentHandle): + self._downstream_handle = handle + + async def __call__(self, name: str) -> str: + response = self._downstream_handle.say_hi.remote(name) + return await response + + app = Ingress.bind(Downstream.bind()) + handle: DeploymentHandle = serve.run(app) + response = handle.remote("world") + assert response.result() == "Hello world!" + """ + + def options( + self, + *, + method_name: Union[str, DEFAULT] = DEFAULT.VALUE, + multiplexed_model_id: Union[str, DEFAULT] = DEFAULT.VALUE, + stream: Union[bool, DEFAULT] = DEFAULT.VALUE, + use_new_handle_api: Union[bool, DEFAULT] = DEFAULT.VALUE, + _prefer_local_routing: Union[bool, DEFAULT] = DEFAULT.VALUE, + ) -> "DeploymentHandle": + """Set options for this handle and return an updated copy of it. + + Example: + + .. code-block:: python + + response: DeploymentResponse = handle.options( + method_name="other_method", + multiplexed_model_id="model:v1", + ).remote() + """ + if use_new_handle_api is not DEFAULT.VALUE: + warnings.warn( + "Setting `use_new_handle_api` no longer has any effect. " + "This argument will be removed in a future version." + ) + + if _prefer_local_routing is not DEFAULT.VALUE: + warnings.warn( + "Modifying `_prefer_local_routing` with `options()` is " + "deprecated. Please use `init()` instead." + ) + + return self._options( + method_name=method_name, + multiplexed_model_id=multiplexed_model_id, + stream=stream, + _prefer_local_routing=_prefer_local_routing, + ) + + def remote( + self, *args, **kwargs + ) -> Union[DeploymentResponse, DeploymentResponseGenerator]: + """Issue a remote call to a method of the deployment. + + By default, the result is a `DeploymentResponse` that can be awaited to fetch + the result of the call or passed to another `.remote()` call to compose multiple + deployments. + + If `handle.options(stream=True)` is set and a generator method is called, this + returns a `DeploymentResponseGenerator` instead. + + Example: + + .. code-block:: python + + # Fetch the result directly. + response = handle.remote() + result = await response + + # Pass the result to another handle call. + composed_response = handle2.remote(handle1.remote()) + composed_result = await composed_response + + Args: + *args: Positional arguments to be serialized and passed to the + remote method call. + **kwargs: Keyword arguments to be serialized and passed to the + remote method call. + """ + + future, request_metadata = self._remote(args, kwargs) + if self.handle_options.stream: + response_cls = DeploymentResponseGenerator + else: + response_cls = DeploymentResponse + + return response_cls(future, request_metadata) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/metrics.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..bce6e49440047a77b30199e4938484cdc938f3df --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/metrics.py @@ -0,0 +1,249 @@ +from typing import Dict, List, Optional, Tuple, Union + +import ray +from ray.serve import context +from ray.util import metrics +from ray.util.annotations import PublicAPI + +DEPLOYMENT_TAG = "deployment" +REPLICA_TAG = "replica" +APPLICATION_TAG = "application" +ROUTE_TAG = "route" + + +def _add_serve_metric_tags(tag_keys: Optional[Tuple[str]] = None) -> Tuple[str]: + """Add serve context tags to the tag_keys""" + if tag_keys is None: + tag_keys = tuple() + + # If the context doesn't exist, no serve tag is added. + if context._get_internal_replica_context() is None: + return tag_keys + # Check no collision with customer tag + if DEPLOYMENT_TAG in tag_keys: + raise ValueError(f"'{DEPLOYMENT_TAG}' tag is reserved for Ray Serve metrics") + if REPLICA_TAG in tag_keys: + raise ValueError(f"'{REPLICA_TAG}' tag is reserved for Ray Serve metrics") + if APPLICATION_TAG in tag_keys: + raise ValueError(f"'{APPLICATION_TAG}' tag is reserved for Ray Serve metrics") + + # Get serve tag inserted: + ray_serve_tags = (DEPLOYMENT_TAG, REPLICA_TAG) + if context._get_internal_replica_context().app_name: + ray_serve_tags += (APPLICATION_TAG,) + if tag_keys: + tag_keys = ray_serve_tags + tag_keys + else: + tag_keys = ray_serve_tags + return tag_keys + + +def _add_serve_metric_default_tags(default_tags: Dict[str, str]): + """Add serve context tags and values to the default_tags""" + if context._get_internal_replica_context() is None: + return default_tags + if DEPLOYMENT_TAG in default_tags: + raise ValueError(f"'{DEPLOYMENT_TAG}' tag is reserved for Ray Serve metrics") + if REPLICA_TAG in default_tags: + raise ValueError(f"'{REPLICA_TAG}' tag is reserved for Ray Serve metrics") + if APPLICATION_TAG in default_tags: + raise ValueError(f"'{APPLICATION_TAG}' tag is reserved for Ray Serve metrics") + replica_context = context._get_internal_replica_context() + # TODO(zcin): use replica_context.deployment for deployment tag + default_tags[DEPLOYMENT_TAG] = replica_context.deployment + default_tags[REPLICA_TAG] = replica_context.replica_tag + if replica_context.app_name: + default_tags[APPLICATION_TAG] = replica_context.app_name + return default_tags + + +def _add_serve_context_tag_values(tag_keys: Tuple, tags: Dict[str, str]): + """Add serve context tag values to the metric tags""" + + _request_context = ray.serve.context._get_serve_request_context() + if ROUTE_TAG in tag_keys and ROUTE_TAG not in tags: + tags[ROUTE_TAG] = _request_context.route + + +@PublicAPI(stability="beta") +class Counter(metrics.Counter): + """A serve cumulative metric that is monotonically increasing. + + This corresponds to Prometheus' counter metric: + https://prometheus.io/docs/concepts/metric_types/#counter + + Serve-related tags ("deployment", "replica", "application", "route") + are added automatically if not provided. + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self): + self.num_requests = 0 + self.my_counter = metrics.Counter( + "my_counter", + description=("The number of odd-numbered requests " + "to this deployment."), + tag_keys=("model",), + ) + self.my_counter.set_default_tags({"model": "123"}) + + def __call__(self): + self.num_requests += 1 + if self.num_requests % 2 == 1: + self.my_counter.inc() + + .. note:: + + Before Ray 2.10, this exports a Prometheus gauge metric instead of + a counter metric. + Starting in Ray 2.10, this exports both the proper counter metric + (with a suffix "_total") and gauge metric (for compatibility). + The gauge metric will be removed in a future Ray release and you can set + `RAY_EXPORT_COUNTER_AS_GAUGE=0` to disable exporting it in the meantime. + + Args: + name: Name of the metric. + description: Description of the metric. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, name: str, description: str = "", tag_keys: Optional[Tuple[str]] = None + ): + if tag_keys and not isinstance(tag_keys, tuple): + raise TypeError( + "tag_keys should be a tuple type, got: " f"{type(tag_keys)}" + ) + tag_keys = _add_serve_metric_tags(tag_keys) + super().__init__(name, description, tag_keys) + self.set_default_tags({}) + + def set_default_tags(self, default_tags: Dict[str, str]): + super().set_default_tags(_add_serve_metric_default_tags(default_tags)) + + def inc(self, value: Union[int, float] = 1.0, tags: Dict[str, str] = None): + """Increment the counter by the given value, add serve context + tag values to the tags + """ + _add_serve_context_tag_values(self._tag_keys, tags) + super().inc(value, tags) + + +@PublicAPI(stability="beta") +class Gauge(metrics.Gauge): + """Gauges keep the last recorded value and drop everything before. + + This corresponds to Prometheus' gauge metric: + https://prometheus.io/docs/concepts/metric_types/#gauge + + Serve-related tags ("deployment", "replica", "application", "route") + are added automatically if not provided. + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self): + self.num_requests = 0 + self.my_gauge = metrics.Gauge( + "my_gauge", + description=("The current memory usage."), + tag_keys=("model",), + ) + self.my_counter.set_default_tags({"model": "123"}) + + def __call__(self): + process = psutil.Process() + self.gauge.set(process.memory_info().rss) + + Args: + name: Name of the metric. + description: Description of the metric. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, name: str, description: str = "", tag_keys: Optional[Tuple[str]] = None + ): + if tag_keys and not isinstance(tag_keys, tuple): + raise TypeError( + "tag_keys should be a tuple type, got: " f"{type(tag_keys)}" + ) + tag_keys = _add_serve_metric_tags(tag_keys) + super().__init__(name, description, tag_keys) + self.set_default_tags({}) + + def set_default_tags(self, default_tags: Dict[str, str]): + super().set_default_tags(_add_serve_metric_default_tags(default_tags)) + + def set(self, value: Union[int, float], tags: Dict[str, str] = None): + """Set the gauge to the given value, add serve context + tag values to the tags + """ + _add_serve_context_tag_values(self._tag_keys, tags) + super().set(value, tags) + + +@PublicAPI(stability="beta") +class Histogram(metrics.Histogram): + """Tracks the size and number of events in buckets. + + Histograms allow you to calculate aggregate quantiles + such as 25, 50, 95, 99 percentile latency for an RPC. + + This corresponds to Prometheus' histogram metric: + https://prometheus.io/docs/concepts/metric_types/#histogram + + Serve-related tags ("deployment", "replica", "application", "route") + are added automatically if not provided. + + .. code-block:: python + + @serve.deployment + class MyDeployment: + def __init__(self): + self.my_histogram = Histogram( + "my_histogram", + description=("Histogram of the __call__ method running time."), + boundaries=[1,2,4,8,16,32,64], + tag_keys=("model",), + ) + self.my_histogram.set_default_tags({"model": "123"}) + + def __call__(self): + start = time.time() + self.my_histogram.observe(time.time() - start) + + Args: + name: Name of the metric. + description: Description of the metric. + boundaries: Boundaries of histogram buckets. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, + name: str, + description: str = "", + boundaries: List[float] = None, + tag_keys: Optional[Tuple[str]] = None, + ): + if tag_keys and not isinstance(tag_keys, tuple): + raise TypeError( + "tag_keys should be a tuple type, got: " f"{type(tag_keys)}" + ) + tag_keys = _add_serve_metric_tags(tag_keys) + super().__init__(name, description, boundaries, tag_keys) + self.set_default_tags({}) + + def set_default_tags(self, default_tags: Dict[str, str]): + super().set_default_tags(_add_serve_metric_default_tags(default_tags)) + + def observe(self, value: Union[int, float], tags: Dict[str, str] = None): + """Observe the given value, add serve context + tag values to the tags + """ + _add_serve_context_tag_values(self._tag_keys, tags) + super().observe(value, tags) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/multiplex.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/multiplex.py new file mode 100644 index 0000000000000000000000000000000000000000..55d526a9a00e83084503d4c4526d10b98a95e131 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/multiplex.py @@ -0,0 +1,260 @@ +import asyncio +import inspect +import logging +import time +from collections import OrderedDict +from typing import Any, Callable, List, Set + +from ray.serve import metrics +from ray.serve._private.common import ReplicaID, RequestRoutingInfo +from ray.serve._private.constants import ( + MODEL_LOAD_LATENCY_BUCKETS_MS, + PUSH_MULTIPLEXED_MODEL_IDS_INTERVAL_S, + SERVE_LOGGER_NAME, +) +from ray.serve._private.metrics_utils import MetricsPusher +from ray.serve._private.usage import ServeUsageTag +from ray.serve.context import _get_global_client, _get_internal_replica_context + +logger = logging.getLogger(SERVE_LOGGER_NAME) + + +class _ModelMultiplexWrapper: + """A wrapper class that wraps the model load function and + provides the LRU caching functionality. + + The model multiplexer is a wrapper class that wraps the model load function + and provides the LRU caching functionality, and the model load function should + be a coroutine function that takes the model ID as the first argument and + returns the user-constructed model object. + The model multiplexer will also ensure that the number of models on the current + replica does not exceed the specified limit. + The model will be unloaded in the LRU order, the model multiplexer will call the + model's __del__ attribute if it exists to clean up the model resources eagerly. + + """ + + _PUSH_MULTIPLEXED_MODEL_IDS_TASK_NAME = "push_multiplexed_model_ids" + + def __init__( + self, + model_load_func: Callable[[str], Any], + self_arg: Any, + max_num_models_per_replica: int, + ): + """Initialize the model multiplexer. + Args: + model_load_func: the model load async function. + self_arg: self argument when model_load_func is class method. + max_num_models_per_replica: the maximum number of models to be loaded on the + current replica. If it is -1, there is no limit for the number of models + per replica. + """ + + ServeUsageTag.MULTIPLEXED_API_USED.record("1") + + self.models = OrderedDict() + self._func: Callable = model_load_func + self.self_arg: Any = self_arg + self.max_num_models_per_replica: int = max_num_models_per_replica + + # log MODEL_LOAD_LATENCY_BUCKET_MS + logger.debug(f"MODEL_LOAD_LATENCY_BUCKET_MS: {MODEL_LOAD_LATENCY_BUCKETS_MS}") + self.model_load_latency_ms = metrics.Histogram( + "serve_multiplexed_model_load_latency_ms", + description="The time it takes to load a model.", + boundaries=MODEL_LOAD_LATENCY_BUCKETS_MS, + ) + self.model_unload_latency_ms = metrics.Histogram( + "serve_multiplexed_model_unload_latency_ms", + description="The time it takes to unload a model.", + boundaries=MODEL_LOAD_LATENCY_BUCKETS_MS, + ) + self.num_models_gauge = metrics.Gauge( + "serve_num_multiplexed_models", + description="The number of models loaded on the current replica.", + ) + + self.registered_model_gauge = metrics.Gauge( + "serve_registered_multiplexed_model_id", + description="The model id registered on the current replica.", + tag_keys=("model_id",), + ) + self.get_model_requests_counter = metrics.Counter( + "serve_multiplexed_get_model_requests_counter", + description="The counter for get model requests on the current replica.", + ) + self.models_unload_counter = metrics.Counter( + "serve_multiplexed_models_unload_counter", + description="The counter for unloaded models on the current replica.", + ) + self.models_load_counter = metrics.Counter( + "serve_multiplexed_models_load_counter", + description="The counter for loaded models on the current replica.", + ) + + context = _get_internal_replica_context() + if context is None: + raise RuntimeError( + "`@serve.multiplex` can only be used within a deployment " + "(failed to retrieve Serve replica context)." + ) + + self._app_name: str = context.app_name + self._deployment_name: str = context.deployment + self._replica_id: ReplicaID = context.replica_id + + # Whether to push the multiplexed replica info to the controller. + self._push_multiplexed_replica_info: bool = False + + # Model cache lock to ensure that only one model is loading/unloading at a time. + self._model_cache_lock = asyncio.Lock() + # The set of model IDs that are being loaded. This is used to early push + # model ids info to the controller. The tasks will be added when there is cache + # miss, and will be removed when the model is loaded successfully or + # failed to load. + self._model_load_tasks: Set[str] = set() + + self.metrics_pusher = MetricsPusher() + self.metrics_pusher.register_or_update_task( + self._PUSH_MULTIPLEXED_MODEL_IDS_TASK_NAME, + self._push_model_ids_info, + PUSH_MULTIPLEXED_MODEL_IDS_INTERVAL_S, + ) + self.metrics_pusher.start() + + def _get_loading_and_loaded_model_ids(self) -> List[str]: + """Get the model IDs of the loaded models & loading models in the replica. + This is to push the model id information early to the controller, so that + requests can be routed to the replica. + """ + models_list = set(self.models.keys()) + models_list.update(self._model_load_tasks) + return list(models_list) + + def _push_model_ids_info(self): + """Push the multiplexed replica info to the controller.""" + try: + self.num_models_gauge.set(len(self.models)) + + for model_id in self.models: + self.registered_model_gauge.set(1, tags={"model_id": model_id}) + + if self._push_multiplexed_replica_info: + _get_global_client().record_request_routing_info( + RequestRoutingInfo( + replica_id=self._replica_id, + multiplexed_model_ids=self._get_loading_and_loaded_model_ids(), + ) + ) + self._push_multiplexed_replica_info = False + except Exception as e: + logger.warning( + "Failed to push the multiplexed replica info " + f"to the controller. Error: {e}" + ) + + async def shutdown(self): + """Unload all the models when the model multiplexer is deleted.""" + while len(self.models) > 0: + try: + await self.unload_model_lru() + except Exception as e: + logger.exception( + f"Failed to unload model. Error: {e}", + ) + + async def load_model(self, model_id: str) -> Any: + """Load the model if it is not loaded yet, and return + the user-constructed model object. + + Args: + model_id: the model ID. + + Returns: + The user-constructed model object. + """ + + if type(model_id) is not str: + raise TypeError("The model ID must be a string.") + + if not model_id: + raise ValueError("The model ID cannot be empty.") + + self.get_model_requests_counter.inc() + + if model_id in self.models: + # Move the model to the end of the OrderedDict to ensure LRU caching. + model = self.models.pop(model_id) + self.models[model_id] = model + return self.models[model_id] + else: + # Set the flag to push the multiplexed replica info to the controller + # before loading the model. This is to make sure we can push the model + # id info to the controller/router early, so that requests can be routed to + # the replica. + self._push_multiplexed_replica_info = True + self._model_load_tasks.add(model_id) + async with self._model_cache_lock: + # Check if the model has been loaded by another request. + if model_id in self.models: + return self.models[model_id] + try: + # If the number of models per replica is specified, check + # if the number of models on the current replica has + # reached the limit. + if ( + self.max_num_models_per_replica > 0 + and len(self.models) >= self.max_num_models_per_replica + ): + # Unload the least recently used model. + await self.unload_model_lru() + self._push_multiplexed_replica_info = True + + # Load the model. + logger.info(f"Loading model '{model_id}'.") + self.models_load_counter.inc() + load_start_time = time.time() + if self.self_arg is None: + self.models[model_id] = await self._func(model_id) + else: + self.models[model_id] = await self._func( + self.self_arg, model_id + ) + load_latency_ms = (time.time() - load_start_time) * 1000.0 + logger.info( + f"Successfully loaded model '{model_id}' in " + f"{load_latency_ms:.1f}ms." + ) + self._model_load_tasks.discard(model_id) + self.model_load_latency_ms.observe(load_latency_ms) + return self.models[model_id] + except Exception as e: + logger.error( + f"Failed to load model '{model_id}'. Error: {e}", + ) + self._model_load_tasks.discard(model_id) + raise e + + async def unload_model_lru(self) -> None: + """Unload the least recently used model.""" + + self.models_unload_counter.inc() + unload_start_time = time.time() + model_id, model = self.models.popitem(last=False) + logger.info(f"Unloading model '{model_id}'.") + + # If the model has __del__ attribute, call it. + # This is to clean up the model resources eagerly. + if hasattr(model, "__del__"): + if not inspect.iscoroutinefunction(model.__del__): + await asyncio.get_running_loop().run_in_executor(None, model.__del__) + else: + await model.__del__() + model.__del__ = lambda _: None + unload_latency_ms = (time.time() - unload_start_time) * 1000.0 + self.model_unload_latency_ms.observe(unload_latency_ms) + logger.info( + f"Successfully unloaded model '{model_id}' in {unload_latency_ms:.1f}ms." + ) + self.registered_model_gauge.set(0, tags={"model_id": model_id}) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/request_router.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/request_router.py new file mode 100644 index 0000000000000000000000000000000000000000..78a42829517519ad9f72a3e7f8939269ef9534ed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/request_router.py @@ -0,0 +1,14 @@ +from ray.serve._private.common import ReplicaID # noqa: F401 +from ray.serve._private.replica_result import ReplicaResult # noqa: F401 +from ray.serve._private.request_router.common import ( # noqa: F401 + PendingRequest, +) +from ray.serve._private.request_router.replica_wrapper import ( # noqa: F401 + RunningReplica, +) +from ray.serve._private.request_router.request_router import ( # noqa: F401 + FIFOMixin, + LocalityMixin, + MultiplexMixin, + RequestRouter, +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/schema.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..607097fee8a7328c904e32341e67e7f5126f11d7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/schema.py @@ -0,0 +1,1204 @@ +import logging +from collections import Counter +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, Dict, List, Optional, Set, Union +from zlib import crc32 + +from ray._common.pydantic_compat import ( + BaseModel, + Extra, + Field, + NonNegativeInt, + PositiveInt, + StrictInt, + root_validator, + validator, +) +from ray._private.ray_logging.constants import LOGRECORD_STANDARD_ATTRS +from ray._private.runtime_env.packaging import parse_uri +from ray.serve._private.common import ( + DeploymentStatus, + DeploymentStatusTrigger, + ReplicaState, + RequestProtocol, + ServeDeployMode, +) +from ray.serve._private.constants import ( + DEFAULT_GRPC_PORT, + DEFAULT_MAX_ONGOING_REQUESTS, + DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S, + RAY_SERVE_LOG_ENCODING, + SERVE_DEFAULT_APP_NAME, +) +from ray.serve._private.deployment_info import DeploymentInfo +from ray.serve._private.utils import DEFAULT +from ray.serve.config import ProxyLocation, RequestRouterConfig +from ray.util.annotations import PublicAPI + +# Shared amongst multiple schemas. +TARGET_CAPACITY_FIELD = Field( + default=None, + description=( + "[EXPERIMENTAL]: the target capacity percentage for all replicas across the " + "cluster. The `num_replicas`, `min_replicas`, `max_replicas`, and " + "`initial_replicas` for each deployment will be scaled by this percentage." + ), + ge=0, + le=100, +) + + +def _route_prefix_format(cls, v): + """ + The route_prefix + 1. must start with a / character + 2. must not end with a / character (unless the entire prefix is just /) + 3. cannot contain wildcards (must not have "{" or "}") + """ + + if v is None: + return v + + if not v.startswith("/"): + raise ValueError( + f'Got "{v}" for route_prefix. Route prefix must start with "/".' + ) + if len(v) > 1 and v.endswith("/"): + raise ValueError( + f'Got "{v}" for route_prefix. Route prefix ' + 'cannot end with "/" unless the ' + 'entire prefix is just "/".' + ) + if "{" in v or "}" in v: + raise ValueError( + f'Got "{v}" for route_prefix. Route prefix ' + "cannot contain wildcards, so it cannot " + 'contain "{" or "}".' + ) + + return v + + +@PublicAPI(stability="alpha") +class EncodingType(str, Enum): + """Encoding type for the serve logs.""" + + TEXT = "TEXT" + JSON = "JSON" + + +@PublicAPI(stability="alpha") +class LoggingConfig(BaseModel): + """Logging config schema for configuring serve components logs. + + Example: + + .. code-block:: python + + from ray import serve + from ray.serve.schema import LoggingConfig + # Set log level for the deployment. + @serve.deployment(LoggingConfig(log_level="DEBUG")) + class MyDeployment: + def __call__(self) -> str: + return "Hello world!" + # Set log directory for the deployment. + @serve.deployment(LoggingConfig(logs_dir="/my_dir")) + class MyDeployment: + def __call__(self) -> str: + return "Hello world!" + """ + + class Config: + extra = Extra.forbid + + encoding: Union[str, EncodingType] = Field( + default_factory=lambda: RAY_SERVE_LOG_ENCODING, + description=( + "Encoding type for the serve logs. Defaults to 'TEXT'. The default can be " + "overwritten using the `RAY_SERVE_LOG_ENCODING` environment variable. " + "'JSON' is also supported for structured logging." + ), + ) + log_level: Union[int, str] = Field( + default="INFO", + description=( + "Log level for the serve logs. Defaults to INFO. You can set it to " + "'DEBUG' to get more detailed debug logs." + ), + ) + logs_dir: Union[str, None] = Field( + default=None, + description=( + "Directory to store the logs. Default to None, which means " + "logs will be stored in the default directory " + "('/tmp/ray/session_latest/logs/serve/...')." + ), + ) + enable_access_log: bool = Field( + default=True, + description=( + "Whether to enable access logs for each request. Default to True." + ), + ) + additional_log_standard_attrs: List[str] = Field( + default_factory=list, + description=( + "Default attributes from the Python standard logger that will be " + "added to all log records. " + "See https://docs.python.org/3/library/logging.html#logrecord-attributes " + "for a list of available attributes." + ), + ) + + @validator("encoding") + def valid_encoding_format(cls, v): + if v not in list(EncodingType): + raise ValueError( + f"Got '{v}' for encoding. Encoding must be one " + f"of {set(EncodingType)}." + ) + + return v + + @validator("log_level") + def valid_log_level(cls, v): + if isinstance(v, int): + if v not in logging._levelToName: + raise ValueError( + f'Got "{v}" for log_level. log_level must be one of ' + f"{list(logging._levelToName.keys())}." + ) + return logging._levelToName[v] + + if v not in logging._nameToLevel: + raise ValueError( + f'Got "{v}" for log_level. log_level must be one of ' + f"{list(logging._nameToLevel.keys())}." + ) + return v + + @validator("additional_log_standard_attrs") + def valid_additional_log_standard_attrs(cls, v): + for attr in v: + if attr not in LOGRECORD_STANDARD_ATTRS: + raise ValueError( + f"Unknown attribute '{attr}'. " + f"Additional log standard attributes must be one of {LOGRECORD_STANDARD_ATTRS}." + ) + return list(set(v)) + + def _compute_hash(self) -> int: + return crc32( + ( + str(self.encoding) + + str(self.log_level) + + str(self.logs_dir) + + str(self.enable_access_log) + ).encode("utf-8") + ) + + def __eq__(self, other: Any) -> bool: + if not isinstance(other, LoggingConfig): + return False + return self._compute_hash() == other._compute_hash() + + +@PublicAPI(stability="stable") +class RayActorOptionsSchema(BaseModel): + """Options with which to start a replica actor.""" + + runtime_env: dict = Field( + default={}, + description=( + "This deployment's runtime_env. working_dir and " + "py_modules may contain only remote URIs." + ), + ) + num_cpus: float = Field( + default=None, + description=( + "The number of CPUs required by the deployment's " + "application per replica. This is the same as a ray " + "actor's num_cpus. Uses a default if null." + ), + ge=0, + ) + num_gpus: float = Field( + default=None, + description=( + "The number of GPUs required by the deployment's " + "application per replica. This is the same as a ray " + "actor's num_gpus. Uses a default if null." + ), + ge=0, + ) + memory: float = Field( + default=None, + description=( + "Restrict the heap memory usage of each replica. Uses a default if null." + ), + ge=0, + ) + resources: Dict = Field( + default={}, + description=("The custom resources required by each replica."), + ) + accelerator_type: str = Field( + default=None, + description=( + "Forces replicas to run on nodes with the specified accelerator type." + "See :ref:`accelerator types `." + ), + ) + + @validator("runtime_env") + def runtime_env_contains_remote_uris(cls, v): + # Ensure that all uris in py_modules and working_dir are remote + + if v is None: + return + + uris = v.get("py_modules", []) + if "working_dir" in v: + uris = [*uris, v["working_dir"]] + + for uri in uris: + if uri is not None: + try: + parse_uri(uri) + except ValueError as e: + raise ValueError( + "runtime_envs in the Serve config support only " + "remote URIs in working_dir and py_modules. Got " + f"error when parsing URI: {e}" + ) + + return v + + +@PublicAPI(stability="stable") +class DeploymentSchema(BaseModel, allow_population_by_field_name=True): + """ + Specifies options for one deployment within a Serve application. For each deployment + this can optionally be included in `ServeApplicationSchema` to override deployment + options specified in code. + """ + + name: str = Field( + ..., description=("Globally-unique name identifying this deployment.") + ) + num_replicas: Optional[Union[PositiveInt, str]] = Field( + default=DEFAULT.VALUE, + description=( + "The number of processes that handle requests to this " + "deployment. Uses a default if null. Can also be set to " + "`auto` for a default autoscaling configuration " + "(experimental)." + ), + ) + max_ongoing_requests: int = Field( + default=DEFAULT.VALUE, + description=( + "Maximum number of requests that are sent in parallel " + "to each replica of this deployment. The limit is enforced across all " + "callers (HTTP requests or DeploymentHandles). Defaults to " + f"{DEFAULT_MAX_ONGOING_REQUESTS}." + ), + gt=0, + ) + max_queued_requests: StrictInt = Field( + default=DEFAULT.VALUE, + description=( + "[DEPRECATED] The max number of requests that will be executed at once in " + f"each replica. Defaults to {DEFAULT_MAX_ONGOING_REQUESTS}." + ), + ) + user_config: Optional[Dict] = Field( + default=DEFAULT.VALUE, + description=( + "Config to pass into this deployment's " + "reconfigure method. This can be updated dynamically " + "without restarting replicas" + ), + ) + autoscaling_config: Optional[Dict] = Field( + default=DEFAULT.VALUE, + description=( + "Config specifying autoscaling " + "parameters for the deployment's number of replicas. " + "If null, the deployment won't autoscale its number of " + "replicas; the number of replicas will be fixed at " + "num_replicas." + ), + ) + graceful_shutdown_wait_loop_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Duration that deployment replicas will wait until there " + "is no more work to be done before shutting down. Uses a " + "default if null." + ), + ge=0, + ) + graceful_shutdown_timeout_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Serve controller waits for this duration before " + "forcefully killing the replica for shutdown. Uses a " + "default if null." + ), + ge=0, + ) + health_check_period_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Frequency at which the controller will health check " + "replicas. Uses a default if null." + ), + gt=0, + ) + health_check_timeout_s: float = Field( + default=DEFAULT.VALUE, + description=( + "Timeout that the controller will wait for a response " + "from the replica's health check before marking it " + "unhealthy. Uses a default if null." + ), + gt=0, + ) + ray_actor_options: RayActorOptionsSchema = Field( + default=DEFAULT.VALUE, description="Options set for each replica actor." + ) + + placement_group_bundles: List[Dict[str, float]] = Field( + default=DEFAULT.VALUE, + description=( + "Define a set of placement group bundles to be " + "scheduled *for each replica* of this deployment. The replica actor will " + "be scheduled in the first bundle provided, so the resources specified in " + "`ray_actor_options` must be a subset of the first bundle's resources. All " + "actors and tasks created by the replica actor will be scheduled in the " + "placement group by default (`placement_group_capture_child_tasks` is set " + "to True)." + ), + ) + + placement_group_strategy: str = Field( + default=DEFAULT.VALUE, + description=( + "Strategy to use for the replica placement group " + "specified via `placement_group_bundles`. Defaults to `PACK`." + ), + ) + + max_replicas_per_node: int = Field( + default=DEFAULT.VALUE, + description=( + "The max number of replicas of this deployment that can run on a single " + "Valid values are None (default, no limit) or an integer in the range of " + "[1, 100]. " + ), + ) + logging_config: LoggingConfig = Field( + default=DEFAULT.VALUE, + description="Logging config for configuring serve deployment logs.", + ) + request_router_config: Union[Dict, RequestRouterConfig] = Field( + default=DEFAULT.VALUE, + description="Config for the request router used for this deployment.", + ) + + @root_validator + def validate_num_replicas_and_autoscaling_config(cls, values): + num_replicas = values.get("num_replicas", None) + autoscaling_config = values.get("autoscaling_config", None) + + # Cannot have `num_replicas` be an int and a non-null + # autoscaling config + if isinstance(num_replicas, int): + if autoscaling_config not in [None, DEFAULT.VALUE]: + raise ValueError( + "Manually setting num_replicas is not allowed " + "when autoscaling_config is provided." + ) + # A null `num_replicas` or `num_replicas="auto"` can be paired + # with a non-null autoscaling_config + elif num_replicas not in ["auto", None, DEFAULT.VALUE]: + raise ValueError( + f'`num_replicas` must be an int or "auto", but got: {num_replicas}' + ) + + return values + + @root_validator + def validate_max_replicas_per_node_and_placement_group_bundles(cls, values): + max_replicas_per_node = values.get("max_replicas_per_node", None) + placement_group_bundles = values.get("placement_group_bundles", None) + + if max_replicas_per_node not in [ + DEFAULT.VALUE, + None, + ] and placement_group_bundles not in [DEFAULT.VALUE, None]: + raise ValueError( + "Setting max_replicas_per_node is not allowed when " + "placement_group_bundles is provided." + ) + + return values + + @root_validator + def validate_max_queued_requests(cls, values): + max_queued_requests = values.get("max_queued_requests", None) + if max_queued_requests is None or max_queued_requests == DEFAULT.VALUE: + return values + + if max_queued_requests < 1 and max_queued_requests != -1: + raise ValueError( + "max_queued_requests must be -1 (no limit) or a positive integer." + ) + + return values + + def _get_user_configured_option_names(self) -> Set[str]: + """Get set of names for all user-configured options. + + Any field not set to DEFAULT.VALUE is considered a user-configured option. + """ + + return { + field for field, value in self.dict().items() if value is not DEFAULT.VALUE + } + + +def _deployment_info_to_schema(name: str, info: DeploymentInfo) -> DeploymentSchema: + """Converts a DeploymentInfo object to DeploymentSchema.""" + + schema = DeploymentSchema( + name=name, + max_ongoing_requests=info.deployment_config.max_ongoing_requests, + max_queued_requests=info.deployment_config.max_queued_requests, + user_config=info.deployment_config.user_config, + graceful_shutdown_wait_loop_s=( + info.deployment_config.graceful_shutdown_wait_loop_s + ), + graceful_shutdown_timeout_s=info.deployment_config.graceful_shutdown_timeout_s, + health_check_period_s=info.deployment_config.health_check_period_s, + health_check_timeout_s=info.deployment_config.health_check_timeout_s, + ray_actor_options=info.replica_config.ray_actor_options, + request_router_config=info.deployment_config.request_router_config, + ) + + if info.deployment_config.autoscaling_config is not None: + schema.autoscaling_config = info.deployment_config.autoscaling_config.dict() + else: + schema.num_replicas = info.deployment_config.num_replicas + + return schema + + +@PublicAPI(stability="stable") +class ServeApplicationSchema(BaseModel): + """ + Describes one Serve application, and currently can also be used as a standalone + config to deploy a single application to a Ray cluster. + """ + + name: str = Field( + default=SERVE_DEFAULT_APP_NAME, + description=( + "Application name, the name should be unique within the serve instance" + ), + ) + route_prefix: Optional[str] = Field( + default="/", + description=( + "Route prefix for HTTP requests. If not provided, it will use" + "route_prefix of the ingress deployment. By default, the ingress route " + "prefix is '/'." + ), + ) + import_path: str = Field( + ..., + description=( + "An import path to a bound deployment node. Should be of the " + 'form "module.submodule_1...submodule_n.' + 'dag_node". This is equivalent to ' + '"from module.submodule_1...submodule_n import ' + 'dag_node". Only works with Python ' + "applications. This field is REQUIRED when deploying Serve config " + "to a Ray cluster." + ), + ) + runtime_env: dict = Field( + default={}, + description=( + "The runtime_env that the deployment graph will be run in. " + "Per-deployment runtime_envs will inherit from this. working_dir " + "and py_modules may contain only remote URIs." + ), + ) + host: str = Field( + default="0.0.0.0", + description=( + "Host for HTTP servers to listen on. Defaults to " + '"0.0.0.0", which exposes Serve publicly. Cannot be updated once ' + "your Serve application has started running. The Serve application " + "must be shut down and restarted with the new host instead." + ), + ) + port: int = Field( + default=8000, + description=( + "Port for HTTP server. Defaults to 8000. Cannot be updated once " + "your Serve application has started running. The Serve application " + "must be shut down and restarted with the new port instead." + ), + ) + deployments: List[DeploymentSchema] = Field( + default=[], + description="Deployment options that override options specified in the code.", + ) + args: Dict = Field( + default={}, + description="Arguments that will be passed to the application builder.", + ) + logging_config: LoggingConfig = Field( + default=None, + description="Logging config for configuring serve application logs.", + ) + + @property + def deployment_names(self) -> List[str]: + return [d.name for d in self.deployments] + + @validator("runtime_env") + def runtime_env_contains_remote_uris(cls, v): + # Ensure that all uris in py_modules and working_dir are remote. + if v is None: + return + + uris = v.get("py_modules", []) + if "working_dir" in v: + uris = [*uris, v["working_dir"]] + + for uri in uris: + if uri is not None: + try: + parse_uri(uri) + except ValueError as e: + raise ValueError( + "runtime_envs in the Serve config support only " + "remote URIs in working_dir and py_modules. Got " + f"error when parsing URI: {e}" + ) + + return v + + @validator("import_path") + def import_path_format_valid(cls, v: str): + if v is None: + return + + if ":" in v: + if v.count(":") > 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path may have at most one colon." + ) + if v.rfind(":") == 0 or v.rfind(":") == len(v) - 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path may not start or end with a colon." + ) + return v + else: + if v.count(".") < 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path must contain at least on dot or colon " + "separating the module (and potentially submodules) from " + 'the deployment graph. E.g.: "module.deployment_graph".' + ) + if v.rfind(".") == 0 or v.rfind(".") == len(v) - 1: + raise ValueError( + f'Got invalid import path "{v}". An ' + "import path may not start or end with a dot." + ) + + return v + + @staticmethod + def get_empty_schema_dict() -> Dict: + """Returns an empty app schema dictionary. + + Schema can be used as a representation of an empty Serve application config. + """ + + return { + "import_path": "", + "runtime_env": {}, + "deployments": [], + } + + +@PublicAPI(stability="alpha") +class gRPCOptionsSchema(BaseModel): + """Options to start the gRPC Proxy with.""" + + port: int = Field( + default=DEFAULT_GRPC_PORT, + description=( + "Port for gRPC server. Defaults to 9000. Cannot be updated once " + "Serve has started running. Serve must be shut down and restarted " + "with the new port instead." + ), + ) + grpc_servicer_functions: List[str] = Field( + default=[], + description=( + "List of import paths for gRPC `add_servicer_to_server` functions to add " + "to Serve's gRPC proxy. Default to empty list, which means no gRPC methods " + "will be added and no gRPC server will be started. The servicer functions " + "need to be importable from the context of where Serve is running." + ), + ) + request_timeout_s: float = Field( + default=None, + description="The timeout for gRPC requests. Defaults to no timeout.", + ) + + +@PublicAPI(stability="stable") +class HTTPOptionsSchema(BaseModel): + """Options to start the HTTP Proxy with. + + NOTE: This config allows extra parameters to make it forward-compatible (ie + older versions of Serve are able to accept configs from a newer versions, + simply ignoring new parameters). + """ + + host: str = Field( + default="0.0.0.0", + description=( + "Host for HTTP servers to listen on. Defaults to " + '"0.0.0.0", which exposes Serve publicly. Cannot be updated once ' + "Serve has started running. Serve must be shut down and restarted " + "with the new host instead." + ), + ) + port: int = Field( + default=8000, + description=( + "Port for HTTP server. Defaults to 8000. Cannot be updated once " + "Serve has started running. Serve must be shut down and restarted " + "with the new port instead." + ), + ) + root_path: str = Field( + default="", + description=( + 'Root path to mount the serve application (for example, "/serve"). All ' + 'deployment routes will be prefixed with this path. Defaults to "".' + ), + ) + request_timeout_s: float = Field( + default=None, + description="The timeout for HTTP requests. Defaults to no timeout.", + ) + keep_alive_timeout_s: int = Field( + default=DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S, + description="The HTTP proxy will keep idle connections alive for this duration " + "before closing them when no requests are ongoing. Defaults to " + f"{DEFAULT_UVICORN_KEEP_ALIVE_TIMEOUT_S} seconds.", + ) + + +@PublicAPI(stability="stable") +class ServeDeploySchema(BaseModel): + """ + Multi-application config for deploying a list of Serve applications to the Ray + cluster. + + This is the request JSON schema for the v2 REST API + `PUT "/api/serve/applications/"`. + + NOTE: This config allows extra parameters to make it forward-compatible (ie + older versions of Serve are able to accept configs from a newer versions, + simply ignoring new parameters) + """ + + proxy_location: ProxyLocation = Field( + default=ProxyLocation.EveryNode, + description=( + "Config for where to run proxies for ingress traffic to the cluster." + ), + ) + http_options: HTTPOptionsSchema = Field( + default=HTTPOptionsSchema(), description="Options to start the HTTP Proxy with." + ) + grpc_options: gRPCOptionsSchema = Field( + default=gRPCOptionsSchema(), description="Options to start the gRPC Proxy with." + ) + logging_config: LoggingConfig = Field( + default=None, + description="Logging config for configuring serve components logs.", + ) + applications: List[ServeApplicationSchema] = Field( + ..., description="The set of applications to run on the Ray cluster." + ) + target_capacity: Optional[float] = TARGET_CAPACITY_FIELD + + @validator("applications") + def application_names_unique(cls, v): + # Ensure there are no duplicate applications listed + names = [app.name for app in v] + duplicates = {f'"{name}"' for name in names if names.count(name) > 1} + if len(duplicates): + apps_str = ("application " if len(duplicates) == 1 else "applications ") + ( + ", ".join(duplicates) + ) + raise ValueError( + f"Found multiple configs for {apps_str}. Please remove all duplicates." + ) + return v + + @validator("applications") + def application_routes_unique(cls, v): + # Ensure each application with a non-null route prefix has unique route prefixes + routes = [app.route_prefix for app in v if app.route_prefix is not None] + duplicates = {f'"{route}"' for route in routes if routes.count(route) > 1} + if len(duplicates): + routes_str = ( + "route prefix " if len(duplicates) == 1 else "route prefixes " + ) + (", ".join(duplicates)) + raise ValueError( + f"Found duplicate applications for {routes_str}. Please ensure each " + "application's route_prefix is unique." + ) + return v + + @validator("applications") + def application_names_nonempty(cls, v): + for app in v: + if len(app.name) == 0: + raise ValueError("Application names must be nonempty.") + return v + + @root_validator + def nested_host_and_port(cls, values): + # TODO (zcin): ServeApplicationSchema still needs to have host and port + # fields to support single-app mode, but in multi-app mode the host and port + # fields at the top-level deploy config is used instead. Eventually, after + # migration, we should remove these fields from ServeApplicationSchema. + for app_config in values.get("applications"): + if "host" in app_config.dict(exclude_unset=True): + raise ValueError( + f'Host "{app_config.host}" is set in the config for application ' + f"`{app_config.name}`. Please remove it and set host in the top " + "level deploy config only." + ) + if "port" in app_config.dict(exclude_unset=True): + raise ValueError( + f"Port {app_config.port} is set in the config for application " + f"`{app_config.name}`. Please remove it and set port in the top " + "level deploy config only." + ) + return values + + @staticmethod + def get_empty_schema_dict() -> Dict: + """Returns an empty deploy schema dictionary. + + Schema can be used as a representation of an empty Serve deploy config. + """ + + return {"applications": []} + + +# Keep in sync with ServeSystemActorStatus in +# python/ray/dashboard/client/src/type/serve.ts +@PublicAPI(stability="stable") +class ProxyStatus(str, Enum): + """The current status of the proxy.""" + + STARTING = "STARTING" + HEALTHY = "HEALTHY" + UNHEALTHY = "UNHEALTHY" + DRAINING = "DRAINING" + # The DRAINED status is a momentary state + # just before the proxy is removed + # so this status won't show up on the dashboard. + DRAINED = "DRAINED" + + +@PublicAPI(stability="alpha") +@dataclass +class DeploymentStatusOverview: + """Describes the status of a deployment. + + Attributes: + status: The current status of the deployment. + replica_states: A map indicating how many replicas there are of + each replica state. + message: A message describing the deployment status in more + detail. + """ + + status: DeploymentStatus + status_trigger: DeploymentStatusTrigger + replica_states: Dict[ReplicaState, int] + message: str + + +@PublicAPI(stability="stable") +class ApplicationStatus(str, Enum): + """The current status of the application.""" + + NOT_STARTED = "NOT_STARTED" + DEPLOYING = "DEPLOYING" + DEPLOY_FAILED = "DEPLOY_FAILED" + RUNNING = "RUNNING" + UNHEALTHY = "UNHEALTHY" + DELETING = "DELETING" + + +@PublicAPI(stability="alpha") +@dataclass +class ApplicationStatusOverview: + """Describes the status of an application and all its deployments. + + Attributes: + status: The current status of the application. + message: A message describing the application status in more + detail. + last_deployed_time_s: The time at which the application was + deployed. A Unix timestamp in seconds. + deployments: The deployments in this application. + """ + + status: ApplicationStatus + message: str + last_deployed_time_s: float + deployments: Dict[str, DeploymentStatusOverview] + + +@PublicAPI(stability="alpha") +@dataclass(eq=True) +class ServeStatus: + """Describes the status of Serve. + + Attributes: + proxies: The proxy actors running on each node in the cluster. + A map from node ID to proxy status. + applications: The live applications in the cluster. + target_capacity: the target capacity percentage for all replicas across the + cluster. + """ + + proxies: Dict[str, ProxyStatus] = field(default_factory=dict) + applications: Dict[str, ApplicationStatusOverview] = field(default_factory=dict) + target_capacity: Optional[float] = TARGET_CAPACITY_FIELD + + +@PublicAPI(stability="stable") +class ServeActorDetails(BaseModel, frozen=True): + """Detailed info about a Ray Serve actor. + + Attributes: + node_id: ID of the node that the actor is running on. + node_ip: IP address of the node that the actor is running on. + node_instance_id: Cloud provider instance id of the node that the actor is running on. + actor_id: Actor ID. + actor_name: Actor name. + worker_id: Worker ID. + log_file_path: The relative path to the Serve actor's log file from the ray logs + directory. + """ + + node_id: Optional[str] = Field( + description="ID of the node that the actor is running on." + ) + node_ip: Optional[str] = Field( + description="IP address of the node that the actor is running on." + ) + node_instance_id: Optional[str] = Field( + description="Cloud provider instance id of the node that the actor is running on." + ) + actor_id: Optional[str] = Field(description="Actor ID.") + actor_name: Optional[str] = Field(description="Actor name.") + worker_id: Optional[str] = Field(description="Worker ID.") + log_file_path: Optional[str] = Field( + description=( + "The relative path to the Serve actor's log file from the ray logs " + "directory." + ) + ) + + +@PublicAPI(stability="stable") +class ReplicaDetails(ServeActorDetails, frozen=True): + """Detailed info about a single deployment replica.""" + + replica_id: str = Field(description="Unique ID for the replica.") + state: ReplicaState = Field(description="Current state of the replica.") + pid: Optional[int] = Field(description="PID of the replica actor process.") + start_time_s: float = Field( + description=( + "The time at which the replica actor was started. If the controller dies, " + "this is the time at which the controller recovers and retrieves replica " + "state from the running replica actor." + ) + ) + + +@PublicAPI(stability="stable") +class DeploymentDetails(BaseModel, extra=Extra.forbid, frozen=True): + """ + Detailed info about a deployment within a Serve application. + """ + + name: str = Field(description="Deployment name.") + status: DeploymentStatus = Field( + description="The current status of the deployment." + ) + status_trigger: DeploymentStatusTrigger = Field( + description="[EXPERIMENTAL] The trigger for the current status.", + ) + message: str = Field( + description=( + "If there are issues with the deployment, this will describe the issue in " + "more detail." + ) + ) + deployment_config: DeploymentSchema = Field( + description=( + "The set of deployment config options that are currently applied to this " + "deployment. These options may come from the user's code, config file " + "options, or Serve default values." + ) + ) + target_num_replicas: NonNegativeInt = Field( + description=( + "The current target number of replicas for this deployment. This can " + "change over time for autoscaling deployments, but will remain a constant " + "number for other deployments." + ) + ) + required_resources: Dict = Field( + description="The resources required per replica of this deployment." + ) + replicas: List[ReplicaDetails] = Field( + description="Details about the live replicas of this deployment." + ) + + +@PublicAPI(stability="alpha") +class APIType(str, Enum): + """Tracks the type of API that an application originates from.""" + + UNKNOWN = "unknown" + IMPERATIVE = "imperative" + DECLARATIVE = "declarative" + + +@PublicAPI(stability="stable") +class ApplicationDetails(BaseModel, extra=Extra.forbid, frozen=True): + """Detailed info about a Serve application.""" + + name: str = Field(description="Application name.") + route_prefix: Optional[str] = Field( + ..., + description=( + "This is the `route_prefix` of the ingress deployment in the application. " + "Requests to paths under this HTTP path prefix will be routed to this " + "application. This value may be null if the application is deploying " + "and app information has not yet fully propagated in the backend; or " + "if the user explicitly set the prefix to `None`, so the application isn't " + "exposed over HTTP. Routing is done based on longest-prefix match, so if " + 'you have deployment A with a prefix of "/a" and deployment B with a ' + 'prefix of "/a/b", requests to "/a", "/a/", and "/a/c" go to A and ' + 'requests to "/a/b", "/a/b/", and "/a/b/c" go to B. Routes must not end ' + 'with a "/" unless they\'re the root (just "/"), which acts as a catch-all.' + ), + ) + docs_path: Optional[str] = Field( + ..., + description=( + "The path at which the docs for this application is served, for instance " + "the `docs_url` for FastAPI-integrated applications." + ), + ) + status: ApplicationStatus = Field( + description="The current status of the application." + ) + message: str = Field( + description="A message that gives more insight into the application status." + ) + last_deployed_time_s: float = Field( + description="The time at which the application was deployed." + ) + deployed_app_config: Optional[ServeApplicationSchema] = Field( + description=( + "The exact copy of the application config that was submitted to the " + "cluster. This will include all of, and only, the options that were " + "explicitly specified in the submitted config. Default values for " + "unspecified options will not be displayed, and deployments that are part " + "of the application but unlisted in the config will also not be displayed. " + "Note that default values for unspecified options are applied to the " + "cluster under the hood, and deployments that were unlisted will still be " + "deployed. This config simply avoids cluttering with unspecified fields " + "for readability." + ) + ) + source: APIType = Field( + description=( + "The type of API that the application originates from. " + "This is a Developer API that is subject to change." + ), + ) + deployments: Dict[str, DeploymentDetails] = Field( + description="Details about the deployments in this application." + ) + + application_details_route_prefix_format = validator( + "route_prefix", allow_reuse=True + )(_route_prefix_format) + + +@PublicAPI(stability="stable") +class ProxyDetails(ServeActorDetails, frozen=True): + """Detailed info about a Ray Serve ProxyActor. + + Attributes: + status: The current status of the proxy. + """ + + status: ProxyStatus = Field(description="Current status of the proxy.") + + +@PublicAPI(stability="alpha") +class Target(BaseModel, frozen=True): + ip: str = Field(description="IP address of the target.") + port: int = Field(description="Port of the target.") + instance_id: str = Field(description="Instance ID of the target.") + + +@PublicAPI(stability="alpha") +class TargetGroup(BaseModel, frozen=True): + targets: List[Target] = Field(description="List of targets for the given route.") + route_prefix: str = Field(description="Prefix route of the targets.") + protocol: RequestProtocol = Field(description="Protocol of the targets.") + + +@PublicAPI(stability="stable") +class ServeInstanceDetails(BaseModel, extra=Extra.forbid): + """ + Serve metadata with system-level info and details on all applications deployed to + the Ray cluster. + + This is the response JSON schema for v2 REST API `GET /api/serve/applications`. + """ + + controller_info: ServeActorDetails = Field( + description="Details about the Serve controller actor." + ) + proxy_location: Optional[ProxyLocation] = Field( + description=( + "Config for where to run proxies for ingress traffic to the cluster.\n" + '- "Disabled": disable the proxies entirely.\n' + '- "HeadOnly": run only one proxy on the head node.\n' + '- "EveryNode": run proxies on every node that has at least one replica.\n' + ), + ) + http_options: Optional[HTTPOptionsSchema] = Field(description="HTTP Proxy options.") + grpc_options: Optional[gRPCOptionsSchema] = Field(description="gRPC Proxy options.") + proxies: Dict[str, ProxyDetails] = Field( + description=( + "Mapping from node_id to details about the Proxy running on that node." + ) + ) + deploy_mode: ServeDeployMode = Field( + default=ServeDeployMode.MULTI_APP, + description=( + "[DEPRECATED]: single-app configs are removed, so this is always " + "MULTI_APP. This field will be removed in a future release." + ), + ) + applications: Dict[str, ApplicationDetails] = Field( + description="Details about all live applications running on the cluster." + ) + target_capacity: Optional[float] = TARGET_CAPACITY_FIELD + + target_groups: List[TargetGroup] = Field( + default_factory=list, + description=( + "List of target groups, each containing target info for a given route and " + "protocol." + ), + ) + + @staticmethod + def get_empty_schema_dict() -> Dict: + """Empty Serve instance details dictionary. + + Represents no Serve instance running on the cluster. + """ + + return { + "deploy_mode": "MULTI_APP", + "controller_info": {}, + "proxies": {}, + "applications": {}, + "target_capacity": None, + } + + def _get_status(self) -> ServeStatus: + return ServeStatus( + target_capacity=self.target_capacity, + proxies={node_id: proxy.status for node_id, proxy in self.proxies.items()}, + applications={ + app_name: ApplicationStatusOverview( + status=app.status, + message=app.message, + last_deployed_time_s=app.last_deployed_time_s, + deployments={ + deployment_name: DeploymentStatusOverview( + status=deployment.status, + status_trigger=deployment.status_trigger, + replica_states=dict( + Counter([r.state.value for r in deployment.replicas]) + ), + message=deployment.message, + ) + for deployment_name, deployment in app.deployments.items() + }, + ) + for app_name, app in self.applications.items() + }, + ) + + def _get_user_facing_json_serializable_dict( + self, *args, **kwargs + ) -> Dict[str, Any]: + """Generates json serializable dictionary with user facing data.""" + values = super().dict(*args, **kwargs) + + # `serialized_policy_def` and internal router config fields are only used + # internally and should not be exposed to the REST api. This method iteratively + # removes them from each deployment config if exists. + for app_name, application in values["applications"].items(): + for deployment_name, deployment in application["deployments"].items(): + if "deployment_config" in deployment: + # Remove internal fields from request_router_config if it exists + if "request_router_config" in deployment["deployment_config"]: + deployment["deployment_config"]["request_router_config"].pop( + "_serialized_request_router_cls", None + ) + if "autoscaling_config" in deployment["deployment_config"]: + deployment["deployment_config"]["autoscaling_config"].pop( + "_serialized_policy_def", None + ) + + return values diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/scripts.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/scripts.py new file mode 100644 index 0000000000000000000000000000000000000000..44e7e2f928d06542c7a862a23283e821d1d53fda --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/serve/scripts.py @@ -0,0 +1,916 @@ +#!/usr/bin/env python +import os +import pathlib +import re +import sys +import time +import traceback +from dataclasses import asdict +from typing import Any, Dict, List, Optional, Tuple + +import click +import watchfiles +import yaml + +import ray +from ray import serve +from ray._common.utils import import_attr +from ray.autoscaler._private.cli_logger import cli_logger +from ray.dashboard.modules.dashboard_sdk import parse_runtime_env_args +from ray.dashboard.modules.serve.sdk import ServeSubmissionClient +from ray.serve._private import api as _private_api +from ray.serve._private.build_app import BuiltApplication, build_app +from ray.serve._private.constants import ( + DEFAULT_GRPC_PORT, + DEFAULT_HTTP_HOST, + DEFAULT_HTTP_PORT, + SERVE_DEFAULT_APP_NAME, + SERVE_NAMESPACE, +) +from ray.serve.config import DeploymentMode, ProxyLocation, gRPCOptions +from ray.serve.deployment import Application, deployment_to_schema +from ray.serve.schema import ( + LoggingConfig, + ServeApplicationSchema, + ServeDeploySchema, + ServeInstanceDetails, +) + +APP_DIR_HELP_STR = ( + "Local directory to look for the IMPORT_PATH (will be inserted into " + "PYTHONPATH). Defaults to '.', meaning that an object in ./main.py " + "can be imported as 'main.object'. Not relevant if you're importing " + "from an installed module." +) +RAY_INIT_ADDRESS_HELP_STR = ( + "Address to use for ray.init(). Can also be set using " + "the RAY_ADDRESS environment variable." +) +RAY_DASHBOARD_ADDRESS_HELP_STR = ( + "Address for the Ray dashboard. Defaults to http://localhost:8265. " + "Can also be set using the RAY_DASHBOARD_ADDRESS environment variable." +) + + +# See https://stackoverflow.com/a/33300001/11162437 +def str_presenter(dumper: yaml.Dumper, data): + """ + A custom representer to write multi-line strings in block notation using a literal + style. + + Ensures strings with newline characters print correctly. + """ + + if len(data.splitlines()) > 1: + return dumper.represent_scalar("tag:yaml.org,2002:str", data, style="|") + return dumper.represent_scalar("tag:yaml.org,2002:str", data) + + +# See https://stackoverflow.com/a/14693789/11162437 +def remove_ansi_escape_sequences(input: str): + """Removes ANSI escape sequences in a string""" + ansi_escape = re.compile( + r""" + \x1B # ESC + (?: # 7-bit C1 Fe (except CSI) + [@-Z\\-_] + | # or [ for CSI, followed by a control sequence + \[ + [0-?]* # Parameter bytes + [ -/]* # Intermediate bytes + [@-~] # Final byte + ) + """, + re.VERBOSE, + ) + + return ansi_escape.sub("", input) + + +def process_dict_for_yaml_dump(data): + """ + Removes ANSI escape sequences recursively for all strings in dict. + + We often need to use yaml.dump() to print dictionaries that contain exception + tracebacks, which can contain ANSI escape sequences that color printed text. However + yaml.dump() will format the tracebacks incorrectly if ANSI escape sequences are + present, so we need to remove them before dumping. + """ + + for k, v in data.items(): + if isinstance(v, dict): + data[k] = process_dict_for_yaml_dump(v) + if isinstance(v, list): + data[k] = [process_dict_for_yaml_dump(item) for item in v] + elif isinstance(v, str): + data[k] = remove_ansi_escape_sequences(v) + + return data + + +def convert_args_to_dict(args: Tuple[str]) -> Dict[str, str]: + args_dict = dict() + for arg in args: + split = arg.split("=", maxsplit=1) + if len(split) != 2 or len(split[1]) == 0: + raise click.ClickException( + f"Invalid application argument '{arg}', " + "must be of the form '='." + ) + + args_dict[split[0]] = split[1] + + return args_dict + + +def warn_if_agent_address_set(): + if "RAY_AGENT_ADDRESS" in os.environ: + cli_logger.warning( + "The `RAY_AGENT_ADDRESS` env var has been deprecated in favor of " + "the `RAY_DASHBOARD_ADDRESS` env var. The `RAY_AGENT_ADDRESS` is " + "ignored." + ) + + +@click.group( + help="CLI for managing Serve applications on a Ray cluster.", + context_settings=dict(help_option_names=["--help", "-h"]), +) +def cli(): + pass + + +@cli.command(help="Start Serve on the Ray cluster.") +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_ADDRESS", "auto"), + required=False, + type=str, + help=RAY_INIT_ADDRESS_HELP_STR, +) +@click.option( + "--http-host", + default=DEFAULT_HTTP_HOST, + required=False, + type=str, + help="Host for HTTP proxies to listen on. " f"Defaults to {DEFAULT_HTTP_HOST}.", +) +@click.option( + "--http-port", + default=DEFAULT_HTTP_PORT, + required=False, + type=int, + help="Port for HTTP proxies to listen on. " f"Defaults to {DEFAULT_HTTP_PORT}.", +) +@click.option( + "--http-location", + default=DeploymentMode.HeadOnly, + required=False, + type=click.Choice(list(DeploymentMode)), + help="DEPRECATED: Use `--proxy-location` instead.", +) +@click.option( + "--proxy-location", + default=ProxyLocation.EveryNode, + required=False, + type=click.Choice(list(ProxyLocation)), + help="Location of the proxies. Defaults to EveryNode.", +) +@click.option( + "--grpc-port", + default=DEFAULT_GRPC_PORT, + required=False, + type=int, + help="Port for gRPC proxies to listen on. " f"Defaults to {DEFAULT_GRPC_PORT}.", +) +@click.option( + "--grpc-servicer-functions", + default=[], + required=False, + multiple=True, + help="Servicer function for adding the method handler to the gRPC server. " + "Defaults to an empty list and no gRPC server is started.", +) +def start( + address, + http_host, + http_port, + http_location, + proxy_location, + grpc_port, + grpc_servicer_functions, +): + if http_location != DeploymentMode.HeadOnly: + cli_logger.warning( + "The `--http-location` flag to `serve start` is deprecated, " + "use `--proxy-location` instead." + ) + + proxy_location = http_location + + ray.init( + address=address, + namespace=SERVE_NAMESPACE, + ) + serve.start( + proxy_location=proxy_location, + http_options=dict( + host=http_host, + port=http_port, + ), + grpc_options=gRPCOptions( + port=grpc_port, + grpc_servicer_functions=grpc_servicer_functions, + ), + ) + + +def _generate_config_from_file_or_import_path( + config_or_import_path: str, + *, + name: Optional[str], + arguments: Dict[str, str], + runtime_env: Optional[Dict[str, Any]], +) -> ServeDeploySchema: + """Generates a deployable config schema for the passed application(s).""" + if pathlib.Path(config_or_import_path).is_file(): + config_path = config_or_import_path + cli_logger.print(f"Deploying from config file: '{config_path}'.") + if len(arguments) > 0: + raise click.ClickException( + "Application arguments cannot be specified for a config file." + ) + + # TODO(edoakes): should we enable overriding? + with open(config_path, "r") as config_file: + if runtime_env and len(runtime_env) > 0: + cli_logger.warning( + "Passed in runtime_env is ignored when using config file" + ) + if name is not None: + cli_logger.warning("Passed in name is ignored when using config file") + config_dict = yaml.safe_load(config_file) + config = ServeDeploySchema.parse_obj(config_dict) + else: + # TODO(edoakes): should we default to --working-dir="." for this? + import_path = config_or_import_path + cli_logger.print(f"Deploying from import path: '{import_path}'.") + + app = ServeApplicationSchema( + import_path=import_path, + runtime_env=runtime_env, + args=arguments, + ) + if name is not None: + app.name = name + config = ServeDeploySchema(applications=[app]) + + return config + + +@cli.command( + short_help="Deploy an application or group of applications.", + help=( + "Deploy an application from an import path (e.g., main:app) " + "or a group of applications from a YAML config file.\n\n" + "Passed import paths must point to an Application object or " + "a function that returns one. If a function is used, arguments can be " + "passed to it in 'key=val' format after the import path, for example:\n\n" + "serve deploy main:app model_path='/path/to/model.pkl' num_replicas=5\n\n" + "This command makes a REST API request to a running Ray cluster." + ), +) +@click.argument("config_or_import_path") +@click.argument("arguments", nargs=-1, required=False) +@click.option( + "--runtime-env", + type=str, + default=None, + required=False, + help=( + "Path to a local YAML file containing a runtime_env definition. Ignored " + "when deploying from a config file." + ), +) +@click.option( + "--runtime-env-json", + type=str, + default=None, + required=False, + help=( + "JSON-serialized runtime_env dictionary. Ignored when deploying from a " + "config file." + ), +) +@click.option( + "--working-dir", + type=str, + default=None, + required=False, + help=( + "Directory containing files that your application(s) will run in. This must " + "be a remote URI to a .zip file (e.g., S3 bucket). This overrides the " + "working_dir in --runtime-env if both are specified. Ignored when deploying " + "from a config file." + ), +) +@click.option( + "--name", + required=False, + default=None, + type=str, + help="Custom name for the application. Ignored when deploying from a config file.", +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +def deploy( + config_or_import_path: str, + arguments: Tuple[str], + runtime_env: str, + runtime_env_json: str, + working_dir: str, + name: Optional[str], + address: str, +): + args_dict = convert_args_to_dict(arguments) + final_runtime_env = parse_runtime_env_args( + runtime_env=runtime_env, + runtime_env_json=runtime_env_json, + working_dir=working_dir, + ) + + config = _generate_config_from_file_or_import_path( + config_or_import_path, + name=name, + arguments=args_dict, + runtime_env=final_runtime_env, + ) + + ServeSubmissionClient(address).deploy_applications( + config.dict(exclude_unset=True), + ) + cli_logger.success( + "\nSent deploy request successfully.\n " + "* Use `serve status` to check applications' statuses.\n " + "* Use `serve config` to see the current application config(s).\n" + ) + + +@cli.command( + short_help="Run an application or group of applications.", + help=( + "Run an application from an import path (e.g., my_script:" + "app) or a group of applications from a YAML config file.\n\n" + "Passed import paths must point to an Application object or " + "a function that returns one. If a function is used, arguments can be " + "passed to it in 'key=val' format after the import path, for example:\n\n" + "serve run my_script:app model_path='/path/to/model.pkl' num_replicas=5\n\n" + "If passing a YAML config, existing applications with no code changes will not " + "be updated.\n\n" + "By default, this will block and stream logs to the console. If you " + "Ctrl-C the command, it will shut down Serve on the cluster." + ), +) +@click.argument("config_or_import_path") +@click.argument("arguments", nargs=-1, required=False) +@click.option( + "--runtime-env", + type=str, + default=None, + required=False, + help="Path to a local YAML file containing a runtime_env definition. " + "This will be passed to ray.init() as the default for deployments.", +) +@click.option( + "--runtime-env-json", + type=str, + default=None, + required=False, + help="JSON-serialized runtime_env dictionary. This will be passed to " + "ray.init() as the default for deployments.", +) +@click.option( + "--working-dir", + type=str, + default=None, + required=False, + help=( + "Directory containing files that your application(s) will run in. Can be a " + "local directory or a remote URI to a .zip file (S3, GS, HTTP). " + "This overrides the working_dir in --runtime-env if both are " + "specified. This will be passed to ray.init() as the default for " + "deployments." + ), +) +@click.option( + "--app-dir", + "-d", + default=".", + type=str, + help=APP_DIR_HELP_STR, +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_ADDRESS", None), + required=False, + type=str, + help=RAY_INIT_ADDRESS_HELP_STR, +) +@click.option( + "--blocking/--non-blocking", + default=True, + help=( + "Whether or not this command should be blocking. If blocking, it " + "will loop and log status until Ctrl-C'd, then clean up the app." + ), +) +@click.option( + "--reload", + "-r", + is_flag=True, + help=( + "This is an experimental feature - Listens for changes to files in the working directory, " + "--working-dir or the working_dir in the --runtime-env, and automatically redeploys " + "the application. This will block until Ctrl-C'd, then clean up the " + "app." + ), +) +@click.option( + "--route-prefix", + required=False, + type=str, + default="/", + help=( + "Route prefix for the application. This should only be used " + "when running an application specified by import path and " + "will be ignored if running a config file." + ), +) +@click.option( + "--name", + required=False, + default=SERVE_DEFAULT_APP_NAME, + type=str, + help=( + "Name of the application. This should only be used " + "when running an application specified by import path and " + "will be ignored if running a config file." + ), +) +def run( + config_or_import_path: str, + arguments: Tuple[str], + runtime_env: str, + runtime_env_json: str, + working_dir: str, + app_dir: str, + address: str, + blocking: bool, + reload: bool, + route_prefix: str, + name: str, +): + sys.path.insert(0, app_dir) + args_dict = convert_args_to_dict(arguments) + final_runtime_env = parse_runtime_env_args( + runtime_env=runtime_env, + runtime_env_json=runtime_env_json, + working_dir=working_dir, + ) + + if pathlib.Path(config_or_import_path).is_file(): + if len(args_dict) > 0: + cli_logger.warning( + "Application arguments are ignored when running a config file." + ) + + is_config = True + config_path = config_or_import_path + cli_logger.print(f"Running config file: '{config_path}'.") + + with open(config_path, "r") as config_file: + config_dict = yaml.safe_load(config_file) + + config = ServeDeploySchema.parse_obj(config_dict) + + else: + is_config = False + import_path = config_or_import_path + cli_logger.print(f"Running import path: '{import_path}'.") + app = _private_api.call_user_app_builder_with_args_if_necessary( + import_attr(import_path), args_dict + ) + + # Only initialize ray if it has not happened yet. + if not ray.is_initialized(): + # Setting the runtime_env here will set defaults for the deployments. + ray.init( + address=address, namespace=SERVE_NAMESPACE, runtime_env=final_runtime_env + ) + elif ( + address is not None + and address != "auto" + and address != ray.get_runtime_context().gcs_address + ): + # Warning users the address they passed is different from the existing ray + # instance. + ray_address = ray.get_runtime_context().gcs_address + cli_logger.warning( + "An address was passed to `serve run` but the imported module also " + f"connected to Ray at a different address: '{ray_address}'. You do not " + "need to call `ray.init` in your code when using `serve run`." + ) + + http_options = {"location": "EveryNode"} + grpc_options = gRPCOptions() + # Merge http_options and grpc_options with the ones on ServeDeploySchema. + if is_config and isinstance(config, ServeDeploySchema): + config_http_options = config.http_options.dict() + http_options = {**config_http_options, **http_options} + grpc_options = gRPCOptions(**config.grpc_options.dict()) + + client = _private_api.serve_start( + http_options=http_options, + grpc_options=grpc_options, + ) + + try: + if is_config: + client.deploy_apps(config, _blocking=False) + cli_logger.success("Submitted deploy config successfully.") + if blocking: + while True: + # Block, letting Ray print logs to the terminal. + time.sleep(10) + else: + # This should not block if reload is true so the watchfiles can be triggered + should_block = blocking and not reload + serve.run(app, blocking=should_block, name=name, route_prefix=route_prefix) + + if reload: + if not blocking: + raise click.ClickException( + "The --non-blocking option conflicts with the --reload option." + ) + if working_dir: + watch_dir = working_dir + else: + watch_dir = app_dir + + for changes in watchfiles.watch( + watch_dir, + rust_timeout=10000, + yield_on_timeout=True, + ): + if changes: + try: + # The module needs to be reloaded with `importlib` in order to + # pick up any changes. + app = _private_api.call_user_app_builder_with_args_if_necessary( + import_attr(import_path, reload_module=True), args_dict + ) + serve.run( + target=app, + blocking=False, + name=name, + route_prefix=route_prefix, + ) + except Exception: + traceback.print_exc() + cli_logger.error( + "Deploying the latest version of the application failed." + ) + + except KeyboardInterrupt: + cli_logger.info("Got KeyboardInterrupt, shutting down...") + serve.shutdown() + sys.exit() + + except Exception: + traceback.print_exc() + cli_logger.error( + "Received unexpected error, see console logs for more details. Shutting " + "down..." + ) + serve.shutdown() + sys.exit() + + +@cli.command(help="Gets the current configs of Serve applications on the cluster.") +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +@click.option( + "--name", + "-n", + required=False, + type=str, + help=( + "Name of an application. Only applies to multi-application mode. If set, this " + "will only fetch the config for the specified application." + ), +) +def config(address: str, name: Optional[str]): + warn_if_agent_address_set() + + serve_details = ServeInstanceDetails( + **ServeSubmissionClient(address).get_serve_details() + ) + + # Fetch app configs for all live applications on the cluster + if name is None: + print( + "\n---\n\n".join( + yaml.safe_dump( + app.deployed_app_config.dict(exclude_unset=True), + sort_keys=False, + ) + for app in serve_details.applications.values() + if app.deployed_app_config is not None + ), + end="", + ) + # Fetch a specific app config by name. + else: + app = serve_details.applications.get(name) + if app is None or app.deployed_app_config is None: + print(f'No config has been deployed for application "{name}".') + else: + config = app.deployed_app_config.dict(exclude_unset=True) + print(yaml.safe_dump(config, sort_keys=False), end="") + + +@cli.command( + short_help="Get the current status of all Serve applications on the cluster.", + help=( + "Prints status information about all applications on the cluster.\n\n" + "An application may be:\n\n" + "- NOT_STARTED: the application does not exist.\n" + "- DEPLOYING: the deployments in the application are still deploying and " + "haven't reached the target number of replicas.\n" + "- RUNNING: all deployments are healthy.\n" + "- DEPLOY_FAILED: the application failed to deploy or reach a running state.\n" + "- DELETING: the application is being deleted, and the deployments in the " + "application are being teared down.\n\n" + "The deployments within each application may be:\n\n" + "- HEALTHY: all replicas are acting normally and passing their health checks.\n" + "- UNHEALTHY: at least one replica is not acting normally and may not be " + "passing its health check.\n" + "- UPDATING: the deployment is updating." + ), +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +@click.option( + "--name", + "-n", + default=None, + required=False, + type=str, + help=( + "Name of an application. If set, this will display only the status of the " + "specified application." + ), +) +def status(address: str, name: Optional[str]): + warn_if_agent_address_set() + + serve_details = ServeInstanceDetails( + **ServeSubmissionClient(address).get_serve_details() + ) + status = asdict(serve_details._get_status()) + + # Ensure multi-line strings in app_status is dumped/printed correctly + yaml.SafeDumper.add_representer(str, str_presenter) + + if name is None: + print( + yaml.safe_dump( + # Ensure exception traceback in app_status are printed correctly + process_dict_for_yaml_dump(status), + default_flow_style=False, + sort_keys=False, + ), + end="", + ) + else: + if name not in serve_details.applications: + cli_logger.error(f'Application "{name}" does not exist.') + else: + print( + yaml.safe_dump( + # Ensure exception tracebacks in app_status are printed correctly + process_dict_for_yaml_dump(status["applications"][name]), + default_flow_style=False, + sort_keys=False, + ), + end="", + ) + + +@cli.command( + help="Shuts down Serve on the cluster, deleting all applications.", +) +@click.option( + "--address", + "-a", + default=os.environ.get("RAY_DASHBOARD_ADDRESS", "http://localhost:8265"), + required=False, + type=str, + help=RAY_DASHBOARD_ADDRESS_HELP_STR, +) +@click.option("--yes", "-y", is_flag=True, help="Bypass confirmation prompt.") +def shutdown(address: str, yes: bool): + warn_if_agent_address_set() + + # check if the address is a valid Ray address + try: + # see what applications are deployed on the cluster + serve_details = ServeInstanceDetails( + **ServeSubmissionClient(address).get_serve_details() + ) + if serve_details.controller_info.node_id is None: + cli_logger.warning( + f"No Serve instance found running on the cluster at {address}." + ) + return + except Exception as e: + cli_logger.error( + f"Unable to shutdown Serve on the cluster at address {address}: {e}" + ) + return + + if not yes: + click.confirm( + f"This will shut down Serve on the cluster at address " + f'"{address}" and delete all applications there. Do you ' + "want to continue?", + abort=True, + ) + + ServeSubmissionClient(address).delete_applications() + + cli_logger.success( + "Sent shutdown request; applications will be deleted asynchronously." + ) + + +@cli.command( + short_help="Generate a config file for the specified applications.", + help=( + "Imports the applications at IMPORT_PATHS and generates a structured, multi-" + "application config for them. If the flag --single-app is set, accepts one " + "application and generates a single-application config. Config " + "outputted from this command can be used by `serve deploy` or the REST API. " + ), +) +@click.argument("import_paths", nargs=-1, required=True) +@click.option( + "--app-dir", + "-d", + default=".", + type=str, + help=APP_DIR_HELP_STR, +) +@click.option( + "--output-path", + "-o", + default=None, + type=str, + help=( + "Local path where the output config will be written in YAML format. " + "If not provided, the config will be printed to STDOUT." + ), +) +@click.option( + "--grpc-servicer-functions", + default=[], + required=False, + multiple=True, + help="Servicer function for adding the method handler to the gRPC server. " + "Defaults to an empty list and no gRPC server is started.", +) +def build( + import_paths: Tuple[str], + app_dir: str, + output_path: Optional[str], + grpc_servicer_functions: List[str], +): + sys.path.insert(0, app_dir) + + def build_app_config(import_path: str, name: str = None): + app: Application = import_attr(import_path) + if not isinstance(app, Application): + raise TypeError( + f"Expected '{import_path}' to be an Application but got {type(app)}." + ) + + built_app: BuiltApplication = build_app(app, name=name) + schema = ServeApplicationSchema( + name=name, + route_prefix="/" if len(import_paths) == 1 else f"/{name}", + import_path=import_path, + runtime_env={}, + deployments=[deployment_to_schema(d) for d in built_app.deployments], + ) + + return schema.dict(exclude_unset=True) + + config_str = ( + "# This file was generated using the `serve build` command " + f"on Ray v{ray.__version__}.\n\n" + ) + + app_configs = [] + for app_index, import_path in enumerate(import_paths): + app_configs.append(build_app_config(import_path, name=f"app{app_index + 1}")) + + deploy_config = { + "proxy_location": "EveryNode", + "http_options": { + "host": "0.0.0.0", + "port": 8000, + }, + "grpc_options": { + "port": DEFAULT_GRPC_PORT, + "grpc_servicer_functions": grpc_servicer_functions, + }, + "logging_config": LoggingConfig().dict(), + "applications": app_configs, + } + + # Parse + validate the set of application configs + ServeDeploySchema.parse_obj(deploy_config) + + config_str += yaml.dump( + deploy_config, + Dumper=ServeDeploySchemaDumper, + default_flow_style=False, + sort_keys=False, + ) + cli_logger.info( + "The auto-generated application names default to `app1`, `app2`, ... etc. " + "Rename as necessary.\n", + ) + + # Ensure file ends with only one newline + config_str = config_str.rstrip("\n") + "\n" + + with open(output_path, "w") if output_path else sys.stdout as f: + f.write(config_str) + + +class ServeDeploySchemaDumper(yaml.SafeDumper): + """YAML dumper object with custom formatting for ServeDeploySchema. + + Reformat config to follow this spacing: + --------------------------------------- + + host: 0.0.0.0 + + port: 8000 + + applications: + + - name: app1 + + import_path: app1.path + + runtime_env: {} + + deployments: + + - name: deployment1 + ... + + - name: deployment2 + ... + """ + + def write_line_break(self, data=None): + # https://github.com/yaml/pyyaml/issues/127#issuecomment-525800484 + super().write_line_break(data) + + # Indents must be at most 4 to ensure that only the top 4 levels of + # the config file have line breaks between them. + if len(self.indents) <= 4: + super().write_line_break() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/thirdparty_files/psutil/_psutil_linux.abi3.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/thirdparty_files/psutil/_psutil_linux.abi3.so new file mode 100644 index 0000000000000000000000000000000000000000..6500d975b4cb05c92d04c1dacabe07f240479c47 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/thirdparty_files/psutil/_psutil_linux.abi3.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c2ebac21139007410080811a015c249ed6fb2f207b1a64e018e47ae19174081 +size 115336 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7713ccb705afc01bc9880f08e56bef578fe819b8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/__init__.py @@ -0,0 +1,84 @@ +# Try import ray[train] core requirements (defined in setup.py) +# isort: off +try: + import fsspec # noqa: F401 + import pandas # noqa: F401 + import pyarrow # noqa: F401 + import requests # noqa: F401 +except ImportError as exc: + raise ImportError( + "Can't import ray.train as some dependencies are missing. " + 'Run `pip install "ray[train]"` to fix.' + ) from exc +# isort: on + + +from ray.air.config import CheckpointConfig, FailureConfig, RunConfig, ScalingConfig +from ray.air.result import Result + +# Import this first so it can be used in other modules +from ray.train._checkpoint import Checkpoint +from ray.train._internal.data_config import DataConfig +from ray.train._internal.session import get_checkpoint, get_dataset_shard, report +from ray.train._internal.syncer import SyncConfig +from ray.train.backend import BackendConfig +from ray.train.constants import TRAIN_DATASET_KEY +from ray.train.context import get_context +from ray.train.trainer import TrainingIterator +from ray.train.v2._internal.constants import is_v2_enabled + +if is_v2_enabled(): + from ray.train.v2.api.callback import UserCallback # noqa: F811 + from ray.train.v2.api.config import ( # noqa: F811 + FailureConfig, + RunConfig, + ScalingConfig, + ) + from ray.train.v2.api.result import Result # noqa: F811 + from ray.train.v2.api.train_fn_utils import ( # noqa: F811 + get_checkpoint, + get_context, + get_dataset_shard, + report, + ) + + +__all__ = [ + "get_checkpoint", + "get_context", + "get_dataset_shard", + "report", + "BackendConfig", + "Checkpoint", + "CheckpointConfig", + "DataConfig", + "FailureConfig", + "Result", + "RunConfig", + "ScalingConfig", + "SyncConfig", + "TrainingIterator", + "TRAIN_DATASET_KEY", +] + +get_checkpoint.__module__ = "ray.train" +get_context.__module__ = "ray.train" +get_dataset_shard.__module__ = "ray.train" +report.__module__ = "ray.train" +BackendConfig.__module__ = "ray.train" +Checkpoint.__module__ = "ray.train" +CheckpointConfig.__module__ = "ray.train" +DataConfig.__module__ = "ray.train" +FailureConfig.__module__ = "ray.train" +Result.__module__ = "ray.train" +RunConfig.__module__ = "ray.train" +ScalingConfig.__module__ = "ray.train" +SyncConfig.__module__ = "ray.train" +TrainingIterator.__module__ = "ray.train" + +if is_v2_enabled(): + __all__.append("UserCallback") + UserCallback.__module__ = "ray.train" + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/_checkpoint.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/_checkpoint.py new file mode 100644 index 0000000000000000000000000000000000000000..5ee65be4f20fe17126b315726bcfb825e9c89e45 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/_checkpoint.py @@ -0,0 +1,424 @@ +import contextlib +import glob +import json +import logging +import os +import platform +import shutil +import tempfile +import traceback +import uuid +from pathlib import Path +from typing import Any, Dict, Iterator, List, Optional, Union + +import pyarrow.fs + +from ray.air._internal.filelock import TempFileLock +from ray.train._internal.storage import _download_from_fs_path, _exists_at_fs_path +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + +# The filename of the file that stores user metadata set on the checkpoint. +_METADATA_FILE_NAME = ".metadata.json" + +# The prefix of the temp checkpoint directory that `to_directory` downloads to +# on the local filesystem. +_CHECKPOINT_TEMP_DIR_PREFIX = "checkpoint_tmp_" + + +class _CheckpointMetaClass(type): + def __getattr__(self, item): + try: + return super().__getattribute__(item) + except AttributeError as exc: + if item in { + "from_dict", + "to_dict", + "from_bytes", + "to_bytes", + "get_internal_representation", + }: + raise _get_migration_error(item) from exc + elif item in { + "from_uri", + "to_uri", + "uri", + }: + raise _get_uri_error(item) from exc + elif item in {"get_preprocessor", "set_preprocessor"}: + raise _get_preprocessor_error(item) from exc + + raise exc + + +@PublicAPI(stability="beta") +class Checkpoint(metaclass=_CheckpointMetaClass): + """A reference to data persisted as a directory in local or remote storage. + + Access the checkpoint contents locally using ``checkpoint.to_directory()`` + or ``checkpoint.as_directory``. + + Attributes + ---------- + path: A path on the filesystem containing the checkpoint contents. + filesystem: PyArrow FileSystem that can be used to access data at the `path`. + + See Also + -------- + ray.train.report : Report a checkpoint during training (with Ray Train/Tune). + ray.train.get_checkpoint : Get the latest checkpoint during training + (for restoration). + + :ref:`train-checkpointing` + :ref:`persistent-storage-guide` + + Examples + -------- + + Creating a checkpoint using ``Checkpoint.from_directory``: + + >>> from ray.train import Checkpoint + >>> checkpoint = Checkpoint.from_directory("/tmp/example_checkpoint_dir") + >>> checkpoint.filesystem # doctest: +ELLIPSIS + >> checkpoint.path + '/tmp/example_checkpoint_dir' + + Creating a checkpoint from a remote URI: + + >>> checkpoint = Checkpoint("s3://bucket/path/to/checkpoint") + >>> checkpoint.filesystem # doctest: +ELLIPSIS + >> checkpoint.path + 'bucket/path/to/checkpoint' + + Creating a checkpoint with a custom filesystem: + + >>> checkpoint = Checkpoint( + ... path="bucket/path/to/checkpoint", + ... filesystem=pyarrow.fs.S3FileSystem(), + ... ) + >>> checkpoint.filesystem # doctest: +ELLIPSIS + >> checkpoint.path + 'bucket/path/to/checkpoint' + + Accessing a checkpoint's contents: + + >>> import os # doctest: +SKIP + >>> with checkpoint.as_directory() as local_checkpoint_dir: # doctest: +SKIP + ... print(os.listdir(local_checkpoint_dir)) # doctest: +SKIP + ['model.pt', 'optimizer.pt', 'misc.pt'] + """ + + def __init__( + self, + path: Union[str, os.PathLike], + filesystem: Optional["pyarrow.fs.FileSystem"] = None, + ): + """Construct a Checkpoint. + + Args: + path: A local path or remote URI containing the checkpoint data. + If a filesystem is provided, then this path must NOT be a URI. + It should be a path on the filesystem with the prefix already stripped. + filesystem: PyArrow FileSystem to use to access data at the path. + If not specified, this is inferred from the URI scheme. + """ + self.path = str(path) + self.filesystem = filesystem + + if path and not filesystem: + self.filesystem, self.path = pyarrow.fs.FileSystem.from_uri(path) + + # This random UUID is used to create a temporary directory name on the + # local filesystem, which will be used for downloading checkpoint data. + # This ensures that if multiple processes download the same checkpoint object + # only one process performs the actual download while the others wait. + # This prevents duplicated download efforts and data. + # NOTE: Calling `to_directory` from multiple `Checkpoint` objects + # that point to the same (fs, path) will still download the data multiple times. + # This only ensures a canonical temp directory name for a single `Checkpoint`. + self._uuid = uuid.uuid4() + + def __repr__(self): + return f"Checkpoint(filesystem={self.filesystem.type_name}, path={self.path})" + + def get_metadata(self) -> Dict[str, Any]: + """Return the metadata dict stored with the checkpoint. + + If no metadata is stored, an empty dict is returned. + """ + metadata_path = Path(self.path, _METADATA_FILE_NAME).as_posix() + if not _exists_at_fs_path(self.filesystem, metadata_path): + return {} + + with self.filesystem.open_input_file(metadata_path) as f: + return json.loads(f.readall().decode("utf-8")) + + def set_metadata(self, metadata: Dict[str, Any]) -> None: + """Set the metadata stored with this checkpoint. + + This will overwrite any existing metadata stored with this checkpoint. + """ + metadata_path = Path(self.path, _METADATA_FILE_NAME).as_posix() + with self.filesystem.open_output_stream(metadata_path) as f: + f.write(json.dumps(metadata).encode("utf-8")) + + def update_metadata(self, metadata: Dict[str, Any]) -> None: + """Update the metadata stored with this checkpoint. + + This will update any existing metadata stored with this checkpoint. + """ + existing_metadata = self.get_metadata() + existing_metadata.update(metadata) + self.set_metadata(existing_metadata) + + @classmethod + def from_directory(cls, path: Union[str, os.PathLike]) -> "Checkpoint": + """Create checkpoint object from a local directory. + + Args: + path: Local directory containing checkpoint data. + + Returns: + A ray.train.Checkpoint object. + """ + return cls(path, filesystem=pyarrow.fs.LocalFileSystem()) + + def to_directory(self, path: Optional[Union[str, os.PathLike]] = None) -> str: + """Write checkpoint data to a local directory. + + *If multiple processes on the same node call this method simultaneously,* + only a single process will perform the download, while the others + wait for the download to finish. Once the download finishes, all processes + receive the same local directory to read from. + + Args: + path: Target directory to download data to. If not specified, + this method will use a temporary directory. + + Returns: + str: Directory containing checkpoint data. + """ + user_provided_path = path is not None + local_path = ( + path if user_provided_path else self._get_temporary_checkpoint_dir() + ) + local_path = os.path.normpath(os.path.expanduser(str(local_path))) + os.makedirs(local_path, exist_ok=True) + + try: + # Timeout 0 means there will be only one attempt to acquire + # the file lock. If it cannot be acquired, throw a TimeoutError + with TempFileLock(local_path, timeout=0): + _download_from_fs_path( + fs=self.filesystem, fs_path=self.path, local_path=local_path + ) + except TimeoutError: + # if the directory is already locked, then wait but do not do anything. + with TempFileLock(local_path, timeout=-1): + pass + if not os.path.exists(local_path): + raise RuntimeError( + f"Checkpoint directory {local_path} does not exist, " + "even though it should have been created by " + "another process. Please raise an issue on GitHub: " + "https://github.com/ray-project/ray/issues" + ) + + return local_path + + @contextlib.contextmanager + def as_directory(self) -> Iterator[str]: + """Returns checkpoint contents in a local directory as a context. + + This function makes checkpoint data available as a directory while avoiding + unnecessary copies and left-over temporary data. + + *If the checkpoint points to a local directory*, this method just returns the + local directory path without making a copy, and nothing will be cleaned up + after exiting the context. + + *If the checkpoint points to a remote directory*, this method will download the + checkpoint to a local temporary directory and return the path + to the temporary directory. + + *If multiple processes on the same node call this method simultaneously,* + only a single process will perform the download, while the others + wait for the download to finish. Once the download finishes, all processes + receive the same local (temporary) directory to read from. + + Once all processes have finished working with the checkpoint, + the temporary directory is cleaned up. + + Users should treat the returned checkpoint directory as read-only and avoid + changing any data within it, as it may be deleted when exiting the context. + + Example: + + .. testcode:: + :hide: + + from pathlib import Path + import tempfile + + from ray.train import Checkpoint + + temp_dir = tempfile.mkdtemp() + (Path(temp_dir) / "example.txt").write_text("example checkpoint data") + checkpoint = Checkpoint.from_directory(temp_dir) + + .. testcode:: + + with checkpoint.as_directory() as checkpoint_dir: + # Do some read-only processing of files within checkpoint_dir + pass + + # At this point, if a temporary directory was created, it will have + # been deleted. + + """ + if isinstance(self.filesystem, pyarrow.fs.LocalFileSystem): + yield self.path + else: + del_lock_path = _get_del_lock_path(self._get_temporary_checkpoint_dir()) + open(del_lock_path, "a").close() + + temp_dir = self.to_directory() + try: + yield temp_dir + finally: + # Always cleanup the del lock after we're done with the directory. + # This avoids leaving a lock file behind in the case of an exception + # in the user code. + try: + os.remove(del_lock_path) + except Exception: + logger.warning( + f"Could not remove {del_lock_path} deletion file lock. " + f"Traceback:\n{traceback.format_exc()}" + ) + + # If there are no more lock files, that means there are no more + # readers of this directory, and we can safely delete it. + # In the edge case (process crash before del lock file is removed), + # we do not remove the directory at all. + # Since it's in /tmp, this is not that big of a deal. + # check if any lock files are remaining + remaining_locks = _list_existing_del_locks(temp_dir) + if not remaining_locks: + try: + # Timeout 0 means there will be only one attempt to acquire + # the file lock. If it cannot be acquired, a TimeoutError + # will be thrown. + with TempFileLock(temp_dir, timeout=0): + shutil.rmtree(temp_dir, ignore_errors=True) + except TimeoutError: + pass + + def _get_temporary_checkpoint_dir(self) -> str: + """Return the name for the temporary checkpoint dir that this checkpoint + will get downloaded to, if accessing via `to_directory` or `as_directory`. + """ + tmp_dir_path = tempfile.gettempdir() + checkpoint_dir_name = _CHECKPOINT_TEMP_DIR_PREFIX + self._uuid.hex + if platform.system() == "Windows": + # Max path on Windows is 260 chars, -1 for joining \ + # Also leave a little for the del lock + del_lock_name = _get_del_lock_path("") + checkpoint_dir_name = ( + _CHECKPOINT_TEMP_DIR_PREFIX + + self._uuid.hex[ + -259 + + len(_CHECKPOINT_TEMP_DIR_PREFIX) + + len(tmp_dir_path) + + len(del_lock_name) : + ] + ) + if not checkpoint_dir_name.startswith(_CHECKPOINT_TEMP_DIR_PREFIX): + raise RuntimeError( + "Couldn't create checkpoint directory due to length " + "constraints. Try specifying a shorter checkpoint path." + ) + return Path(tmp_dir_path, checkpoint_dir_name).as_posix() + + def __fspath__(self): + raise TypeError( + "You cannot use `Checkpoint` objects directly as paths. " + "Use `Checkpoint.to_directory()` or `Checkpoint.as_directory()` instead." + ) + + +def _get_del_lock_path(path: str, suffix: str = None) -> str: + """Get the path to the deletion lock file for a file/directory at `path`. + + Example: + + >>> _get_del_lock_path("/tmp/checkpoint_tmp") # doctest: +ELLIPSIS + '/tmp/checkpoint_tmp.del_lock_... + >>> _get_del_lock_path("/tmp/checkpoint_tmp/") # doctest: +ELLIPSIS + '/tmp/checkpoint_tmp.del_lock_... + >>> _get_del_lock_path("/tmp/checkpoint_tmp.txt") # doctest: +ELLIPSIS + '/tmp/checkpoint_tmp.txt.del_lock_... + + """ + suffix = suffix if suffix is not None else str(os.getpid()) + return f"{path.rstrip('/')}.del_lock_{suffix}" + + +def _list_existing_del_locks(path: str) -> List[str]: + """List all the deletion lock files for a file/directory at `path`. + + For example, if 2 checkpoints are being read via `as_directory`, + then this should return a list of 2 deletion lock files. + """ + return list(glob.glob(f"{_get_del_lock_path(path, suffix='*')}")) + + +def _get_migration_error(name: str): + return AttributeError( + f"The new `ray.train.Checkpoint` class does not support `{name}()`. " + f"Instead, only directories are supported.\n\n" + f"Example to store a dictionary in a checkpoint:\n\n" + f"import os, tempfile\n" + f"import ray.cloudpickle as pickle\n" + f"from ray import train\n" + f"from ray.train import Checkpoint\n\n" + f"with tempfile.TemporaryDirectory() as checkpoint_dir:\n" + f" with open(os.path.join(checkpoint_dir, 'data.pkl'), 'wb') as fp:\n" + f" pickle.dump({{'data': 'value'}}, fp)\n\n" + f" checkpoint = Checkpoint.from_directory(checkpoint_dir)\n" + f" train.report(..., checkpoint=checkpoint)\n\n" + f"Example to load a dictionary from a checkpoint:\n\n" + f"if train.get_checkpoint():\n" + f" with train.get_checkpoint().as_directory() as checkpoint_dir:\n" + f" with open(os.path.join(checkpoint_dir, 'data.pkl'), 'rb') as fp:\n" + f" data = pickle.load(fp)" + ) + + +def _get_uri_error(name: str): + return AttributeError( + f"The new `ray.train.Checkpoint` class does not support `{name}()`. " + f"To create a checkpoint from remote storage, create a `Checkpoint` using its " + f"constructor instead of `from_directory`.\n" + f'Example: `Checkpoint(path="s3://a/b/c")`.\n' + f"Then, access the contents of the checkpoint with " + f"`checkpoint.as_directory()` / `checkpoint.to_directory()`.\n" + f"To upload data to remote storage, use e.g. `pyarrow.fs.FileSystem` " + f"or your client of choice." + ) + + +def _get_preprocessor_error(name: str): + return AttributeError( + f"The new `ray.train.Checkpoint` class does not support `{name}()`. " + f"To include preprocessor information in checkpoints, " + f"pass it as metadata in the Trainer constructor.\n" + f"Example: `TorchTrainer(..., metadata={{...}})`.\n" + f"After training, access it in the checkpoint via `checkpoint.get_metadata()`. " + f"See here: https://docs.ray.io/en/master/train/user-guides/" + f"data-loading-preprocessing.html#preprocessing-structured-data" + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/backend.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..b50f5867e7a75f47b36a0778463d7a113be1585d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/backend.py @@ -0,0 +1,59 @@ +import logging +from contextlib import nullcontext +from typing import TypeVar + +from ray.train._internal.utils import Singleton +from ray.train._internal.worker_group import WorkerGroup +from ray.util.annotations import DeveloperAPI +from ray.widgets import make_table_html_repr + +EncodedData = TypeVar("EncodedData") + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class BackendConfig: + """Parent class for configurations of training backend.""" + + @property + def backend_cls(self): + return Backend + + @property + def train_func_context(self): + return nullcontext + + def _repr_html_(self) -> str: + return make_table_html_repr(obj=self, title=type(self).__name__) + + +@DeveloperAPI +class Backend(metaclass=Singleton): + """Singleton for distributed communication backend. + + Attributes: + share_cuda_visible_devices: If True, each worker + process will have CUDA_VISIBLE_DEVICES set as the visible device + IDs of all workers on the same node for this training instance. + If False, each worker will have CUDA_VISIBLE_DEVICES set to the + device IDs allocated by Ray for that worker. + """ + + share_cuda_visible_devices: bool = False + + def on_start(self, worker_group: WorkerGroup, backend_config: BackendConfig): + """Logic for starting this backend.""" + pass + + def on_shutdown(self, worker_group: WorkerGroup, backend_config: BackendConfig): + """Logic for shutting down the backend.""" + pass + + def on_training_start( + self, worker_group: WorkerGroup, backend_config: BackendConfig + ): + """Logic ran right before training is started. + + Session API is available at this point.""" + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/base_trainer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/base_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..b69211ddc65b02709d371709e6e46fb789a922ce --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/base_trainer.py @@ -0,0 +1,911 @@ +import abc +import copy +import inspect +import json +import logging +import os +import warnings +from functools import partial +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Type, Union + +import pyarrow.fs + +import ray +import ray.cloudpickle as pickle +from ray._private.dict import deep_update +from ray._private.usage import usage_lib +from ray.air._internal import usage as air_usage +from ray.air._internal.config import ensure_only_allowed_dataclass_keys_updated +from ray.air._internal.usage import AirEntrypoint +from ray.air.config import RunConfig, ScalingConfig +from ray.air.result import Result +from ray.train import Checkpoint +from ray.train._internal.session import get_session +from ray.train._internal.storage import ( + StorageContext, + _exists_at_fs_path, + get_fs_and_path, +) +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.context import _GET_METADATA_DEPRECATION_MESSAGE +from ray.train.utils import _log_deprecation_warning +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.data import Dataset + from ray.tune import Trainable + +_TRAINER_PKL = "trainer.pkl" + +# A type representing either a ray.data.Dataset or a function that returns a +# ray.data.Dataset and accepts no arguments. +GenDataset = Union["Dataset", Callable[[], "Dataset"]] + + +logger = logging.getLogger(__name__) + +PREPROCESSOR_DEPRECATION_MESSAGE = ( + "The `preprocessor` argument to Trainers is deprecated as of Ray 2.7. " + "Instead, use the Preprocessor `fit` and `transform` APIs directly on the Ray " + "Dataset. For any state that needs to be saved to the trained checkpoint, pass it " + "in using the `metadata` argument of the `Trainer`. " + "For a full example, see " + "https://docs.ray.io/en/master/train/user-guides/data-loading-preprocessing.html#preprocessing-structured-data " # noqa:E501 +) + +_TRAINER_RESTORE_DEPRECATION_WARNING = ( + "The `restore` and `can_restore` APIs are deprecated and " + f"will be removed in a future release. {V2_MIGRATION_GUIDE_MESSAGE}" +) + +_RESUME_FROM_CHECKPOINT_DEPRECATION_WARNING = ( + "`resume_from_checkpoint` is deprecated and will be removed in an upcoming " + f"release. {V2_MIGRATION_GUIDE_MESSAGE}" +) + + +@PublicAPI(stability="beta") +class TrainingFailedError(RuntimeError): + """An error indicating that training has failed.""" + + _RESTORE_MSG = ( + "The Ray Train run failed. Please inspect the previous error messages for a " + "cause. After fixing the issue (assuming that the error is not caused by " + "your own application logic, but rather an error such as OOM), you can restart " + "the run from scratch or continue this run.\n" + "To continue this run, you can use: " + '`trainer = {trainer_cls_name}.restore("{path}")`.' + ) + + _FAILURE_CONFIG_MSG = ( + "To start a new run that will retry on training failures, set " + "`train.RunConfig(failure_config=train.FailureConfig(max_failures))` " + "in the Trainer's `run_config` with `max_failures > 0`, or `max_failures = -1` " + "for unlimited retries." + ) + + +def _train_coordinator_fn( + config: dict, trainer_cls: Type["BaseTrainer"], metadata: dict +): + """This is the function that defines the logic of the Ray Train coordinator. + This is responsible for setting up a remote instance of the `trainer_cls` + (a different instance than the one calling `trainer.fit` on the driver!) + and running the training loop. + """ + assert metadata is not None, metadata + # Propagate user metadata from the Trainer constructor. + get_session().metadata = metadata + + # config already contains merged values. + # Instantiate new Trainer in Trainable. + trainer = trainer_cls(**config) + + # Get the checkpoint from Tune and pass it to workers later on. + checkpoint = ray.tune.get_checkpoint() + if checkpoint: + # Set `starting_checkpoint` for auto-recovery fault-tolerance + # as well as manual restoration. + trainer.starting_checkpoint = checkpoint + # else: Train will restore from the user-provided + # `resume_from_checkpoint` == `starting_checkpoint`. + + # Evaluate datasets if they are wrapped in a factory. + trainer.datasets = { + k: d() if callable(d) else d for k, d in trainer.datasets.items() + } + + trainer.setup() + trainer.training_loop() + + +@DeveloperAPI +class BaseTrainer(abc.ABC): + """Defines interface for distributed training on Ray. + + Note: The base ``BaseTrainer`` class cannot be instantiated directly. Only + one of its subclasses can be used. + + Note to developers: If a new trainer is added, please update + `air/_internal/usage.py`. + + **How does a trainer work?** + + - First, initialize the Trainer. The initialization runs locally, + so heavyweight setup should not be done in ``__init__``. + - Then, when you call ``trainer.fit()``, the Trainer is serialized + and copied to a remote Ray actor. The following methods are then + called in sequence on the remote actor. + - ``trainer.setup()``: Any heavyweight Trainer setup should be + specified here. + - ``trainer.training_loop()``: Executes the main training logic. + - Calling ``trainer.fit()`` will return a ``ray.result.Result`` + object where you can access metrics from your training run, as well + as any checkpoints that may have been saved. + + **How do I create a new Trainer?** + + Subclass ``ray.train.trainer.BaseTrainer``, and override the ``training_loop`` + method, and optionally ``setup``. + + .. testcode:: + + import torch + + from ray.train.trainer import BaseTrainer + from ray import train, tune + + + class MyPytorchTrainer(BaseTrainer): + def setup(self): + self.model = torch.nn.Linear(1, 1) + self.optimizer = torch.optim.SGD( + self.model.parameters(), lr=0.1) + + def training_loop(self): + # You can access any Trainer attributes directly in this method. + # self.datasets["train"] has already been + dataset = self.datasets["train"] + + torch_ds = dataset.iter_torch_batches(dtypes=torch.float) + loss_fn = torch.nn.MSELoss() + + for epoch_idx in range(10): + loss = 0 + num_batches = 0 + torch_ds = dataset.iter_torch_batches( + dtypes=torch.float, batch_size=2 + ) + for batch in torch_ds: + X = torch.unsqueeze(batch["x"], 1) + y = torch.unsqueeze(batch["y"], 1) + # Compute prediction error + pred = self.model(X) + batch_loss = loss_fn(pred, y) + + # Backpropagation + self.optimizer.zero_grad() + batch_loss.backward() + self.optimizer.step() + + loss += batch_loss.item() + num_batches += 1 + loss /= num_batches + + # Use Tune functions to report intermediate + # results. + train.report({"loss": loss, "epoch": epoch_idx}) + + + # Initialize the Trainer, and call Trainer.fit() + import ray + train_dataset = ray.data.from_items( + [{"x": i, "y": i} for i in range(10)]) + my_trainer = MyPytorchTrainer(datasets={"train": train_dataset}) + result = my_trainer.fit() + + .. testoutput:: + :hide: + + ... + + Args: + scaling_config: Configuration for how to scale training. + run_config: Configuration for the execution of the training run. + datasets: Any Datasets to use for training. Use the key "train" + to denote which dataset is the training dataset. + metadata: Dict that should be made available via + `train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + resume_from_checkpoint: A checkpoint to resume training from. + """ + + _scaling_config_allowed_keys: List[str] = [ + "trainer_resources", + ] + _handles_checkpoint_freq: bool = False + _handles_checkpoint_at_end: bool = False + + # fields to propagate to Tuner param_space. + # See `BaseTrainer._extract_fields_for_tuner_param_space` for more details. + _fields_for_tuner_param_space = [] + + def __init__( + self, + *, + scaling_config: Optional[ScalingConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + self.scaling_config = ( + scaling_config if scaling_config is not None else ScalingConfig() + ) + self.run_config = ( + copy.copy(run_config) if run_config is not None else RunConfig() + ) + self.metadata = metadata + self.datasets = datasets if datasets is not None else {} + self.starting_checkpoint = resume_from_checkpoint + + if _v2_migration_warnings_enabled(): + if metadata is not None: + _log_deprecation_warning(_GET_METADATA_DEPRECATION_MESSAGE) + if resume_from_checkpoint is not None: + _log_deprecation_warning(_RESUME_FROM_CHECKPOINT_DEPRECATION_WARNING) + + # These attributes should only be set through `BaseTrainer.restore` + self._restore_path = None + self._restore_storage_filesystem = None + + self._validate_attributes() + + usage_lib.record_library_usage("train") + air_usage.tag_air_trainer(self) + + @classmethod + @Deprecated(message=_TRAINER_RESTORE_DEPRECATION_WARNING) + def restore( + cls: Type["BaseTrainer"], + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + scaling_config: Optional[ScalingConfig] = None, + **kwargs, + ) -> "BaseTrainer": + """Restores a Train experiment from a previously interrupted/failed run. + + Restore should be used for experiment-level fault tolerance in the event + that the head node crashes (e.g., OOM or some other runtime error) or the + entire cluster goes down (e.g., network error affecting all nodes). + + A run that has already completed successfully will not be resumed from this API. + To continue training from a successful run, launch a new run with the + ``Trainer(resume_from_checkpoint)`` API instead, passing in a + checkpoint from the previous run to start with. + + .. note:: + + Restoring an experiment from a path that's pointing to a *different* + location than the original experiment path is supported. However, Ray Train + assumes that the full experiment directory is available + (including checkpoints) so that it's possible to resume trials from their + latest state. + + For example, if the original experiment path was run locally, then the + results are uploaded to cloud storage, Ray Train expects the full contents + to be available in cloud storage if attempting to resume + via ``Trainer.restore("s3://...")``. The restored run will + continue writing results to the same cloud storage location. + + The following example can be paired with implementing job retry using + :ref:`Ray Jobs ` to produce a Train experiment that will + attempt to resume on both experiment-level and trial-level failures: + + .. testcode:: + + import os + import ray + from ray import train + from ray.train.trainer import BaseTrainer + + experiment_name = "unique_experiment_name" + storage_path = os.path.expanduser("~/ray_results") + experiment_dir = os.path.join(storage_path, experiment_name) + + # Define some dummy inputs for demonstration purposes + datasets = {"train": ray.data.from_items([{"a": i} for i in range(10)])} + + class CustomTrainer(BaseTrainer): + def training_loop(self): + pass + + if CustomTrainer.can_restore(experiment_dir): + trainer = CustomTrainer.restore( + experiment_dir, datasets=datasets + ) + else: + trainer = CustomTrainer( + datasets=datasets, + run_config=train.RunConfig( + name=experiment_name, + storage_path=storage_path, + # Tip: You can also enable retries on failure for + # worker-level fault tolerance + failure_config=train.FailureConfig(max_failures=3), + ), + ) + + result = trainer.fit() + + .. testoutput:: + :hide: + + ... + + Args: + path: The path to the experiment directory of the training run to restore. + This can be a local path or a remote URI if the experiment was + uploaded to the cloud. + storage_filesystem: Custom ``pyarrow.fs.FileSystem`` + corresponding to the ``path``. This may be necessary if the original + experiment passed in a custom filesystem. + datasets: Re-specified datasets used in the original training run. + This must include all the datasets that were passed in the + original trainer constructor. + scaling_config: Optionally re-specified scaling config. This can be + modified to be different from the original spec. + **kwargs: Other optionally re-specified arguments, passed in by subclasses. + + Raises: + ValueError: If all datasets were not re-supplied on restore. + + Returns: + BaseTrainer: A restored instance of the class that is calling this method. + """ + if _v2_migration_warnings_enabled(): + _log_deprecation_warning(_TRAINER_RESTORE_DEPRECATION_WARNING) + + if not cls.can_restore(path, storage_filesystem): + raise ValueError( + f"Invalid restore path: {path}. Make sure that this path exists and " + "is the experiment directory that results from a call to " + "`trainer.fit()`." + ) + fs, fs_path = get_fs_and_path(path, storage_filesystem) + trainer_pkl_path = Path(fs_path, _TRAINER_PKL).as_posix() + with fs.open_input_file(trainer_pkl_path) as f: + trainer_cls, param_dict = pickle.loads(f.readall()) + + if trainer_cls is not cls: + warnings.warn( + f"Invalid trainer type. You are attempting to restore a trainer of type" + f" {trainer_cls} with `{cls.__name__}.restore`, " + "which will most likely fail. " + f"Use `{trainer_cls.__name__}.restore` instead." + ) + + original_datasets = param_dict.pop("datasets", {}) + if original_datasets and not datasets: + raise ValueError( + "The following datasets need to be provided again on restore: " + f"{list(original_datasets.keys())}\n" + f"Use {cls.__name__}.restore(..., datasets=datasets) " + "with the datasets that were provided to the original trainer." + ) + datasets = datasets or {} + if set(original_datasets) != set(datasets): + raise ValueError( + "The provided datasets don't match the original dataset keys.\n" + f" Expected datasets for the keys: {list(original_datasets.keys())}\n" + f" Actual datasets provided: {list(datasets.keys())}" + ) + param_dict["datasets"] = datasets + + if scaling_config: + param_dict["scaling_config"] = scaling_config + + for param_name, val in kwargs.items(): + # Overwrite the old value if something is passed into restore + if val is not None: + param_dict[param_name] = val + + try: + trainer = cls(**param_dict) + except Exception as e: + raise ValueError( + "Trainer restoration failed (see above for the stack trace). " + "Make sure that you use the right trainer class to restore: " + f"`{cls.__name__}.restore`\n" + ) from e + trainer._restore_path = path + trainer._restore_storage_filesystem = storage_filesystem + return trainer + + @classmethod + @Deprecated( + message=_TRAINER_RESTORE_DEPRECATION_WARNING, + warning=_v2_migration_warnings_enabled(), + ) + def can_restore( + cls: Type["BaseTrainer"], + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + ) -> bool: + """Checks whether a given directory contains a restorable Train experiment. + + Args: + path: The path to the experiment directory of the Train experiment. + This can be either a local directory (e.g., ~/ray_results/exp_name) + or a remote URI (e.g., s3://bucket/exp_name). + + Returns: + bool: Whether this path exists and contains the trainer state to resume from + """ + if _v2_migration_warnings_enabled(): + _log_deprecation_warning(_TRAINER_RESTORE_DEPRECATION_WARNING) + + fs, fs_path = get_fs_and_path(path, storage_filesystem) + trainer_pkl_path = Path(fs_path, _TRAINER_PKL).as_posix() + return _exists_at_fs_path(fs, trainer_pkl_path) + + def __repr__(self): + # A dictionary that maps parameters to their default values. + default_values: Dict[str, Any] = { + "scaling_config": ScalingConfig(), + "run_config": RunConfig(), + "datasets": {}, + "starting_checkpoint": None, + } + + non_default_arguments = [] + for parameter, default_value in default_values.items(): + value = getattr(self, parameter) + if value != default_value: + non_default_arguments.append(f"{parameter}={value!r}") + + if non_default_arguments: + return f"<{self.__class__.__name__} {' '.join(non_default_arguments)}>" + + return f"<{self.__class__.__name__}>" + + def __new__(cls, *args, **kwargs): + # Store the init args as attributes so this can be merged with Tune hparams. + trainer = super(BaseTrainer, cls).__new__(cls) + parameters = inspect.signature(cls.__init__).parameters + parameters = list(parameters.keys()) + # Remove self. + parameters = parameters[1:] + arg_dict = dict(zip(parameters, args)) + trainer._param_dict = {**arg_dict, **kwargs} + return trainer + + def _validate_attributes(self): + """Called on __init()__ to validate trainer attributes.""" + # Run config + if not isinstance(self.run_config, RunConfig): + raise ValueError( + f"`run_config` should be an instance of `ray.train.RunConfig`, " + f"found {type(self.run_config)} with value `{self.run_config}`." + ) + # Scaling config + if not isinstance(self.scaling_config, ScalingConfig): + raise ValueError( + "`scaling_config` should be an instance of `ScalingConfig`, " + f"found {type(self.scaling_config)} with value `{self.scaling_config}`." + ) + # Datasets + if not isinstance(self.datasets, dict): + raise ValueError( + f"`datasets` should be a dict mapping from a string to " + f"`ray.data.Dataset` objects, " + f"found {type(self.datasets)} with value `{self.datasets}`." + ) + else: + for key, dataset in self.datasets.items(): + if not isinstance(dataset, ray.data.Dataset) and not callable(dataset): + raise ValueError( + f"The Dataset under '{key}' key is not a " + "`ray.data.Dataset`. " + f"Received {dataset} instead." + ) + # Metadata. + self.metadata = self.metadata or {} + if not isinstance(self.metadata, dict): + raise TypeError( + f"The provided metadata must be a dict, was {type(self.metadata)}." + ) + try: + self.metadata = json.loads(json.dumps(self.metadata)) + except Exception as e: + raise ValueError( + "The provided metadata must be JSON-serializable: " + f"{self.metadata}: {e}" + ) + + if self.starting_checkpoint is not None and not isinstance( + self.starting_checkpoint, Checkpoint + ): + raise ValueError( + f"`resume_from_checkpoint` should be an instance of " + f"`ray.train.Checkpoint`, found {type(self.starting_checkpoint)} " + f"with value `{self.starting_checkpoint}`." + ) + + self._log_v2_deprecation_warnings() + + def _log_v2_deprecation_warnings(self): + """Logs deprecation warnings for v2 migration. + + Log them here in the Ray Train case rather than in the configuration + constructors to avoid logging incorrect deprecation warnings when + `ray.train.RunConfig` is passed to Ray Tune. + """ + + if not _v2_migration_warnings_enabled(): + return + + from ray.train.v2._internal.migration_utils import ( + CALLBACKS_DEPRECATION_MESSAGE, + FAIL_FAST_DEPRECATION_MESSAGE, + LOG_TO_FILE_DEPRECATION_MESSAGE, + PROGRESS_REPORTER_DEPRECATION_MESSAGE, + STOP_DEPRECATION_MESSAGE, + SYNC_CONFIG_DEPRECATION_MESSAGE, + TRAINER_RESOURCES_DEPRECATION_MESSAGE, + VERBOSE_DEPRECATION_MESSAGE, + ) + + # ScalingConfig deprecations + if self.scaling_config.trainer_resources is not None: + _log_deprecation_warning(TRAINER_RESOURCES_DEPRECATION_MESSAGE) + + # FailureConfig deprecations + if self.run_config.failure_config.fail_fast: + _log_deprecation_warning(FAIL_FAST_DEPRECATION_MESSAGE) + + # RunConfig deprecations + # NOTE: _verbose is the original verbose value passed by the user + if self.run_config._verbose is not None: + _log_deprecation_warning(VERBOSE_DEPRECATION_MESSAGE) + + if self.run_config.log_to_file: + _log_deprecation_warning(LOG_TO_FILE_DEPRECATION_MESSAGE) + + if self.run_config.stop is not None: + _log_deprecation_warning(STOP_DEPRECATION_MESSAGE) + + if self.run_config.callbacks is not None: + _log_deprecation_warning(CALLBACKS_DEPRECATION_MESSAGE) + + if self.run_config.progress_reporter is not None: + _log_deprecation_warning(PROGRESS_REPORTER_DEPRECATION_MESSAGE) + + if self.run_config.sync_config != ray.train.SyncConfig(): + _log_deprecation_warning(SYNC_CONFIG_DEPRECATION_MESSAGE) + + @classmethod + def _validate_scaling_config(cls, scaling_config: ScalingConfig) -> ScalingConfig: + """Returns scaling config dataclass after validating updated keys.""" + ensure_only_allowed_dataclass_keys_updated( + dataclass=scaling_config, + allowed_keys=cls._scaling_config_allowed_keys, + ) + return scaling_config + + def setup(self) -> None: + """Called during fit() to perform initial setup on the Trainer. + + .. note:: This method is run on a remote process. + + This method will not be called on the driver, so any expensive setup + operations should be placed here and not in ``__init__``. + + This method is called prior to ``preprocess_datasets`` and + ``training_loop``. + """ + pass + + def preprocess_datasets(self) -> None: + """Deprecated.""" + raise DeprecationWarning( + "`preprocess_datasets` is no longer used, since preprocessors " + f"are no longer accepted by Trainers.\n{PREPROCESSOR_DEPRECATION_MESSAGE}" + ) + + @abc.abstractmethod + def training_loop(self) -> None: + """Loop called by fit() to run training and report results to Tune. + + .. note:: This method runs on a remote process. + + ``self.datasets`` have already been evaluated if they were wrapped in a factory. + + You can use the :ref:`Ray Train utilities ` + (:func:`train.report() ` and + :func:`train.get_checkpoint() `) inside + this training loop. + + Example: + + .. testcode:: + + from ray.train.trainer import BaseTrainer + from ray import train + + class MyTrainer(BaseTrainer): + def training_loop(self): + for epoch_idx in range(5): + ... + train.report({"epoch": epoch_idx}) + + """ + raise NotImplementedError + + @PublicAPI(stability="beta") + def fit(self) -> Result: + """Runs training. + + Returns: + A Result object containing the training result. + + Raises: + ray.train.base_trainer.TrainingFailedError: If any failures during the execution + of ``self.as_trainable()``, or during the Tune execution loop. + """ + from ray.tune import ResumeConfig, TuneError + from ray.tune.tuner import Tuner + + trainable = self.as_trainable() + param_space = self._extract_fields_for_tuner_param_space() + + self.run_config.name = ( + self.run_config.name or StorageContext.get_experiment_dir_name(trainable) + ) + # The storage context here is only used to access the resolved + # storage fs and experiment path, in order to avoid duplicating that logic. + # This is NOT the storage context object that gets passed to remote workers. + storage = StorageContext( + storage_path=self.run_config.storage_path, + experiment_dir_name=self.run_config.name, + storage_filesystem=self.run_config.storage_filesystem, + ) + + if self._restore_path: + tuner = Tuner.restore( + path=self._restore_path, + trainable=trainable, + param_space=param_space, + _resume_config=ResumeConfig( + finished=ResumeConfig.ResumeType.RESUME, + unfinished=ResumeConfig.ResumeType.RESUME, + errored=ResumeConfig.ResumeType.RESUME, + ), + storage_filesystem=self._restore_storage_filesystem, + ) + else: + tuner = Tuner( + trainable=trainable, + param_space=param_space, + run_config=self.run_config, + _entrypoint=AirEntrypoint.TRAINER, + ) + + self._save(storage.storage_filesystem, storage.experiment_fs_path) + + restore_msg = TrainingFailedError._RESTORE_MSG.format( + trainer_cls_name=self.__class__.__name__, + path=str(storage.experiment_fs_path), + ) + + try: + result_grid = tuner.fit() + except TuneError as e: + # Catch any `TuneError`s raised by the `Tuner.fit` call. + # Unwrap the `TuneError` if needed. + parent_error = e.__cause__ or e + + # Raise it to the user as a `TrainingFailedError` with a message to restore. + raise TrainingFailedError(restore_msg) from parent_error + # Other exceptions get passed through directly (ex: on `fail_fast='raise'`) + + assert len(result_grid) == 1 + result = result_grid[0] + if result.error: + # Raise trainable errors to the user with a message to restore + # or configure `FailureConfig` in a new run. + raise TrainingFailedError( + "\n".join([restore_msg, TrainingFailedError._FAILURE_CONFIG_MSG]) + ) from result.error + return result + + def _save(self, fs: pyarrow.fs.FileSystem, experiment_path: str): + """Saves the current trainer's class along with the `param_dict` of + parameters passed to this trainer's constructor. + + This is used to recreate the trainer on restore. + Unless a parameter is re-specified during restoration (only a subset + of parameters can be passed in again), that parameter will be loaded + from the saved copy. + + Datasets should not be saved as part of the state. Instead, we save the + keys and replace the dataset values with dummy functions that will + raise an error if invoked. The error only serves as a guardrail for + misuse (e.g., manually unpickling and constructing the Trainer again) + and is not typically surfaced, since datasets must be re-specified + upon restoration. + """ + param_dict = self._param_dict.copy() + datasets = param_dict.pop("datasets", {}) + + def raise_fn(): + raise RuntimeError + + if datasets: + param_dict["datasets"] = { + dataset_name: raise_fn for dataset_name in datasets + } + + cls_and_param_dict = (self.__class__, param_dict) + + fs.create_dir(experiment_path) + with fs.open_output_stream(Path(experiment_path, _TRAINER_PKL).as_posix()) as f: + f.write(pickle.dumps(cls_and_param_dict)) + + def _extract_fields_for_tuner_param_space(self) -> Dict: + """Extracts fields to be included in `Tuner.param_space`. + + This is needed to leverage the full logging/integration offerings from Tune. + For example, `param_space` is logged automatically to wandb integration. + + Currently only done for `train_loop_config`. + + Returns: + A dictionary that should be passed to Tuner.param_space. + """ + result = {} + for key in self._fields_for_tuner_param_space: + if key in self._param_dict.keys(): + result[key] = copy.deepcopy(self._param_dict[key]) + return result + + def _generate_trainable_cls(self) -> Type["Trainable"]: + """Generates the base Trainable class. + + Returns: + A Trainable class to use for training. + """ + + from ray.tune.execution.placement_groups import PlacementGroupFactory + from ray.tune.trainable import wrap_function + + trainer_cls = self.__class__ + scaling_config = self.scaling_config + metadata = self.metadata + + train_coordinator_fn = partial( + _train_coordinator_fn, trainer_cls=trainer_cls, metadata=metadata + ) + # Change the name of the training function to match the name of the Trainer + # class. This will mean the Tune trial name will match the name of Trainer on + # stdout messages and the results directory. + train_coordinator_fn.__name__ = trainer_cls.__name__ + + trainable_cls = wrap_function(train_coordinator_fn) + has_base_dataset = bool(self.datasets) + if has_base_dataset: + from ray.data.context import DataContext + + dataset_context = DataContext.get_current() + else: + dataset_context = None + + class TrainTrainable(trainable_cls): + """Adds default resources to the Trainable.""" + + _handles_checkpoint_freq = trainer_cls._handles_checkpoint_freq + _handles_checkpoint_at_end = trainer_cls._handles_checkpoint_at_end + + @classmethod + def has_base_dataset(cls) -> bool: + """Whether a dataset is provided through the Trainer.""" + return has_base_dataset + + @classmethod + def base_scaling_config(cls) -> ScalingConfig: + """Returns the unchanged scaling config provided through the Trainer.""" + return scaling_config + + def setup(self, config, **kwargs): + base_config = dict(kwargs) + # Merge Tuner param space hyperparameters in `config` into the + # base config passed to the Trainer constructor, which is `base_config`. + # `base_config` is pulled from the object store from the usage of + # tune.with_parameters in `BaseTrainer.as_trainable`. + + # run_config is not a tunable hyperparameter so it does not need to be + # merged. + run_config = base_config.pop("run_config", None) + self._merged_config = deep_update( + base_config, self.config, new_keys_allowed=True + ) + self._merged_config["run_config"] = run_config + merged_scaling_config = self._merged_config.get( + "scaling_config", ScalingConfig() + ) + if isinstance(merged_scaling_config, dict): + merged_scaling_config = ScalingConfig(**merged_scaling_config) + self._merged_config[ + "scaling_config" + ] = self._reconcile_scaling_config_with_trial_resources( + merged_scaling_config + ) + if self.has_base_dataset(): + # Set the DataContext on the Trainer actor to the DataContext + # specified on the driver. + DataContext._set_current(dataset_context) + super(TrainTrainable, self).setup(config) + + def _reconcile_scaling_config_with_trial_resources( + self, scaling_config: ScalingConfig + ) -> ScalingConfig: + """ + ResourceChangingScheduler workaround. + + Ensures that the scaling config matches trial resources. + + This should be replaced with RCS returning a ScalingConfig + in the future. + """ + + trial_resources = self.trial_resources + # This will be false if the resources are default + if not isinstance(trial_resources, PlacementGroupFactory): + return scaling_config + + # Ignore ResourceChangingScheduler workaround when resource bundles + # are unchanged + if self.trial_resources == scaling_config.as_placement_group_factory(): + return scaling_config + + trainer_cls._validate_scaling_config(scaling_config) + + return ScalingConfig.from_placement_group_factory(trial_resources) + + def _trainable_func(self, config): + # We ignore the config passed by Tune and instead use the merged + # config which includes the initial Trainer args. + super()._trainable_func(self._merged_config) + + @classmethod + def default_resource_request(cls, config): + # `config["scaling_config"] is a dataclass when passed via the + # `scaling_config` argument in `Trainer` and is a dict when passed + # via the `scaling_config` key of `param_spec`. + + # Conversion logic must be duplicated in `TrainTrainable.__init__` + # because this is a class method. + updated_scaling_config = config.get("scaling_config", scaling_config) + if isinstance(updated_scaling_config, dict): + updated_scaling_config = ScalingConfig(**updated_scaling_config) + validated_scaling_config = trainer_cls._validate_scaling_config( + updated_scaling_config + ) + return validated_scaling_config.as_placement_group_factory() + + return TrainTrainable + + def as_trainable(self) -> Type["Trainable"]: + """Converts self to a ``tune.Trainable`` class.""" + from ray import tune + + base_config = self._param_dict + trainable_cls = self._generate_trainable_cls() + + # Wrap with `tune.with_parameters` to handle very large values in base_config + return tune.with_parameters(trainable_cls, **base_config) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..d444e2cf046135e873f8e251752c5dcee58c9b2a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/constants.py @@ -0,0 +1,132 @@ +from pathlib import Path + +import ray +from ray._private.ray_constants import env_bool +from ray.air.constants import ( # noqa: F401 + COPY_DIRECTORY_CHECKPOINTS_INSTEAD_OF_MOVING_ENV, + EVALUATION_DATASET_KEY, + MODEL_KEY, + PREPROCESSOR_KEY, + TRAIN_DATASET_KEY, +) + + +def _get_ray_train_session_dir() -> str: + assert ray.is_initialized(), "Ray must be initialized to get the session dir." + return Path( + ray._private.worker._global_node.get_session_dir_path(), "artifacts" + ).as_posix() + + +DEFAULT_STORAGE_PATH = Path("~/ray_results").expanduser().as_posix() + +# Autofilled ray.train.report() metrics. Keys should be consistent with Tune. +CHECKPOINT_DIR_NAME = "checkpoint_dir_name" +TIME_TOTAL_S = "_time_total_s" +WORKER_HOSTNAME = "_hostname" +WORKER_NODE_IP = "_node_ip" +WORKER_PID = "_pid" + +# Will not be reported unless ENABLE_DETAILED_AUTOFILLED_METRICS_ENV +# env var is not 0 +DETAILED_AUTOFILLED_KEYS = {WORKER_HOSTNAME, WORKER_NODE_IP, WORKER_PID, TIME_TOTAL_S} + +# Default filename for JSON logger +RESULT_FILE_JSON = "results.json" + +# The name of the subdirectory inside the trainer run_dir to store checkpoints. +TRAIN_CHECKPOINT_SUBDIR = "checkpoints" + +# The key to use to specify the checkpoint id for Tune. +# This needs to be added to the checkpoint dictionary so if the Tune trial +# is restarted, the checkpoint_id can continue to increment. +TUNE_CHECKPOINT_ID = "_current_checkpoint_id" + +# Deprecated configs can use this value to detect if the user has set it. +_DEPRECATED_VALUE = "DEPRECATED" + + +# ================================================== +# Train V2 constants +# ================================================== + +# Set this to 1 to enable deprecation warnings for V2 migration. +ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR = "RAY_TRAIN_ENABLE_V2_MIGRATION_WARNINGS" + + +V2_MIGRATION_GUIDE_MESSAGE = ( + "See this issue for more context and migration options: " + "https://github.com/ray-project/ray/issues/49454. " + "Disable these warnings by setting the environment variable: " + f"{ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR}=0" +) + + +def _v2_migration_warnings_enabled() -> bool: + return env_bool(ENABLE_V2_MIGRATION_WARNINGS_ENV_VAR, True) + + +# ================================================== +# Environment Variables +# ================================================== + +ENABLE_DETAILED_AUTOFILLED_METRICS_ENV = ( + "TRAIN_RESULT_ENABLE_DETAILED_AUTOFILLED_METRICS" +) + +# Integer value which if set will override the value of +# Backend.share_cuda_visible_devices. 1 for True, 0 for False. +ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_CUDA_VISIBLE_DEVICES" + +# Integer value which if set will not share HIP accelerator visible devices +# across workers. 1 for True (default), 0 for False. +ENABLE_SHARE_HIP_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_HIP_VISIBLE_DEVICES" + +# Integer value which if set will not share neuron-core accelerator visible cores +# across workers. 1 for True (default), 0 for False. +ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV = ( + "TRAIN_ENABLE_SHARE_NEURON_CORES_ACCELERATOR" +) + +# Integer value which if set will not share npu visible devices +# across workers. 1 for True (default), 0 for False. +ENABLE_SHARE_NPU_RT_VISIBLE_DEVICES_ENV = "TRAIN_ENABLE_SHARE_ASCEND_RT_VISIBLE_DEVICES" + +# Integer value which indicates the number of seconds to wait when creating +# the worker placement group before timing out. +TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV = "TRAIN_PLACEMENT_GROUP_TIMEOUT_S" + +# Integer value which if set will change the placement group strategy from +# PACK to SPREAD. 1 for True, 0 for False. +TRAIN_ENABLE_WORKER_SPREAD_ENV = "TRAIN_ENABLE_WORKER_SPREAD" + +# Set this to 0 to disable changing the working directory of each Tune Trainable +# or Train worker to the trial directory. Defaults to 1. +RAY_CHDIR_TO_TRIAL_DIR = "RAY_CHDIR_TO_TRIAL_DIR" + +# Set this to 1 to count preemption errors toward `FailureConfig(max_failures)`. +# Defaults to 0, which always retries on node preemption failures. +RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE = "RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE" + +# Set this to 1 to start a StateActor and collect information Train Runs +# Defaults to 0 +RAY_TRAIN_ENABLE_STATE_TRACKING = "RAY_TRAIN_ENABLE_STATE_TRACKING" + + +# NOTE: When adding a new environment variable, please track it in this list. +TRAIN_ENV_VARS = { + ENABLE_DETAILED_AUTOFILLED_METRICS_ENV, + ENABLE_SHARE_CUDA_VISIBLE_DEVICES_ENV, + ENABLE_SHARE_NEURON_CORES_ACCELERATOR_ENV, + TRAIN_PLACEMENT_GROUP_TIMEOUT_S_ENV, + TRAIN_ENABLE_WORKER_SPREAD_ENV, + RAY_CHDIR_TO_TRIAL_DIR, + RAY_TRAIN_COUNT_PREEMPTION_AS_FAILURE, + RAY_TRAIN_ENABLE_STATE_TRACKING, +} + +# Key for AIR Checkpoint metadata in TrainingResult metadata +CHECKPOINT_METADATA_KEY = "checkpoint_metadata" + +# Key for AIR Checkpoint world rank in TrainingResult metadata +CHECKPOINT_RANK_KEY = "checkpoint_rank" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/context.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/context.py new file mode 100644 index 0000000000000000000000000000000000000000..7aefb4b9005544bd8ce3e9c1f8d4e78659dee87c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/context.py @@ -0,0 +1,144 @@ +import threading +from typing import TYPE_CHECKING, Any, Dict, Optional + +from ray.train._internal import session +from ray.train._internal.storage import StorageContext +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.utils import _copy_doc, _log_deprecation_warning +from ray.util.annotations import Deprecated, DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.tune.execution.placement_groups import PlacementGroupFactory + + +# The context singleton on this process. +_default_context: "Optional[TrainContext]" = None +_context_lock = threading.Lock() + + +_GET_METADATA_DEPRECATION_MESSAGE = ( + "`get_metadata` was an experimental API that accessed the metadata passed " + "to `Trainer(metadata=...)`. This API can be replaced by passing " + "the metadata directly to the training function (e.g., via `train_loop_config`). " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + +_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE = ( + "`{}` is deprecated because the concept of a `Trial` will " + "soon be removed in Ray Train." + "Ray Train will no longer assume that it's running within a Ray Tune `Trial` " + "in the future. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" +) + + +@PublicAPI(stability="stable") +class TrainContext: + """Context containing metadata that can be accessed within Ray Train workers.""" + + @_copy_doc(session.get_experiment_name) + def get_experiment_name(self) -> str: + return session.get_experiment_name() + + @_copy_doc(session.get_world_size) + def get_world_size(self) -> int: + return session.get_world_size() + + @_copy_doc(session.get_world_rank) + def get_world_rank(self) -> int: + return session.get_world_rank() + + @_copy_doc(session.get_local_rank) + def get_local_rank(self) -> int: + return session.get_local_rank() + + @_copy_doc(session.get_local_world_size) + def get_local_world_size(self) -> int: + return session.get_local_world_size() + + @_copy_doc(session.get_node_rank) + def get_node_rank(self) -> int: + return session.get_node_rank() + + @DeveloperAPI + @_copy_doc(session.get_storage) + def get_storage(self) -> StorageContext: + return session.get_storage() + + # Deprecated APIs + + @Deprecated( + message=_GET_METADATA_DEPRECATION_MESSAGE, + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_metadata) + def get_metadata(self) -> Dict[str, Any]: + return session.get_metadata() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_name"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_name) + def get_trial_name(self) -> str: + return session.get_trial_name() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_id"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_id) + def get_trial_id(self) -> str: + return session.get_trial_id() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format( + "get_trial_resources" + ), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_resources) + def get_trial_resources(self) -> "PlacementGroupFactory": + return session.get_trial_resources() + + @Deprecated( + message=_TUNE_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_trial_dir"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(session.get_trial_dir) + def get_trial_dir(self) -> str: + return session.get_trial_dir() + + +@PublicAPI(stability="stable") +def get_context() -> TrainContext: + """Get or create a singleton training context. + + The context is only available within a function passed to Ray Train. + + See the :class:`~ray.train.TrainContext` API reference to see available methods. + """ + from ray.tune.trainable.trainable_fn_utils import _in_tune_session + + # If we are running in a Tune function, switch to Tune context. + if _in_tune_session(): + from ray.tune import get_context as get_tune_context + + if _v2_migration_warnings_enabled(): + _log_deprecation_warning( + "`ray.train.get_context()` should be switched to " + "`ray.tune.get_context()` when running in a function " + "passed to Ray Tune. This will be an error in the future. " + f"{V2_MIGRATION_GUIDE_MESSAGE}" + ) + return get_tune_context() + + global _default_context + + with _context_lock: + if _default_context is None: + _default_context = TrainContext() + return _default_context diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/data_parallel_trainer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/data_parallel_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..f2e6d5a5e6317cfbb85970422ab826f48101961e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/data_parallel_trainer.py @@ -0,0 +1,586 @@ +import logging +import uuid +from typing import Any, Callable, Dict, List, Optional, Type, Union + +import ray +from ray._private.ray_constants import env_integer +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.air.config import RunConfig, ScalingConfig +from ray.train import BackendConfig, Checkpoint, TrainingIterator +from ray.train._internal import session +from ray.train._internal.backend_executor import BackendExecutor, TrialInfo +from ray.train._internal.data_config import DataConfig +from ray.train._internal.session import _TrainingResult, get_session +from ray.train._internal.utils import construct_train_func, count_required_parameters +from ray.train.base_trainer import _TRAINER_RESTORE_DEPRECATION_WARNING +from ray.train.constants import RAY_TRAIN_ENABLE_STATE_TRACKING +from ray.train.trainer import BaseTrainer, GenDataset +from ray.util.annotations import Deprecated, DeveloperAPI +from ray.widgets import Template +from ray.widgets.util import repr_with_fallback + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class DataParallelTrainer(BaseTrainer): + """A Trainer for data parallel training. + + You should subclass this Trainer if your Trainer follows SPMD (single program, + multiple data) programming paradigm - you want multiple processes to run the same + function, but on different data. + + This Trainer runs the function ``train_loop_per_worker`` on multiple Ray + Actors. + + The ``train_loop_per_worker`` function is expected to take in either 0 or 1 + arguments: + + .. testcode:: + + def train_loop_per_worker(): + ... + + .. testcode:: + + def train_loop_per_worker(config: Dict): + ... + + If ``train_loop_per_worker`` accepts an argument, then + ``train_loop_config`` will be passed in as the argument. This is useful if you + want to tune the values in ``train_loop_config`` as hyperparameters. + + If the ``datasets`` dict contains a training dataset (denoted by + the "train" key), then it will be split into multiple dataset + shards that can then be accessed by ``train.get_dataset_shard("train")`` inside + ``train_loop_per_worker``. All the other datasets will not be split and + ``train.get_dataset_shard(...)`` will return the entire Dataset. + + Inside the ``train_loop_per_worker`` function, you can use any of the + :ref:`Ray Train loop methods `. + + .. testcode:: + + from ray import train + + def train_loop_per_worker(): + # Report intermediate results for callbacks or logging and + # checkpoint data. + train.report(...) + + # Returns dict of last saved checkpoint. + train.get_checkpoint() + + # Returns the Dataset shard for the given key. + train.get_dataset_shard("my_dataset") + + # Returns the total number of workers executing training. + train.get_context().get_world_size() + + # Returns the rank of this worker. + train.get_context().get_world_rank() + + # Returns the rank of the worker on the current node. + train.get_context().get_local_rank() + + Any returns from the ``train_loop_per_worker`` will be discarded and not + used or persisted anywhere. + + **How do I use DataParallelTrainer or any of its subclasses?** + + Example: + + .. testcode:: + + import ray + from ray import train + from ray.train import ScalingConfig + from ray.train.data_parallel_trainer import DataParallelTrainer + + def train_loop_for_worker(): + dataset_shard_for_this_worker = train.get_dataset_shard("train") + + # 3 items for 3 workers, each worker gets 1 item + batches = list(dataset_shard_for_this_worker.iter_batches(batch_size=1)) + assert len(batches) == 1 + + train_dataset = ray.data.from_items([1, 2, 3]) + assert train_dataset.count() == 3 + trainer = DataParallelTrainer( + train_loop_for_worker, + scaling_config=ScalingConfig(num_workers=3), + datasets={"train": train_dataset}, + ) + result = trainer.fit() + + .. testoutput:: + :hide: + + ... + + **How do I develop on top of DataParallelTrainer?** + + In many cases, using DataParallelTrainer directly is sufficient to execute + functions on multiple actors. + + However, you may want to subclass ``DataParallelTrainer`` and create a custom + Trainer for the following 2 use cases: + + - **Use Case 1:** You want to do data parallel training, but want to have + a predefined ``training_loop_per_worker``. + + - **Use Case 2:** You want to implement a custom + :py:class:`~ray.train.backend.Backend` that automatically handles + additional setup or teardown logic on each actor, so that the users of this + new trainer do not have to implement this logic. For example, a + ``TensorflowTrainer`` can be built on top of ``DataParallelTrainer`` + that automatically handles setting the proper environment variables for + distributed Tensorflow on each actor. + + For 1, you can set a predefined training loop in __init__ + + .. testcode:: + + from ray.train.data_parallel_trainer import DataParallelTrainer + + class MyDataParallelTrainer(DataParallelTrainer): + def __init__(self, *args, **kwargs): + predefined_train_loop_per_worker = lambda: 1 + super().__init__(predefined_train_loop_per_worker, *args, **kwargs) + + + For 2, you can implement the ``ray.train.Backend`` and ``ray.train.BackendConfig`` + interfaces. + + .. testcode:: + + from dataclasses import dataclass + from ray.train.backend import Backend, BackendConfig + + class MyBackend(Backend): + def on_start(self, worker_group, backend_config): + def set_env_var(env_var_value): + import os + os.environ["MY_ENV_VAR"] = env_var_value + + worker_group.execute(set_env_var, backend_config.env_var) + + @dataclass + class MyBackendConfig(BackendConfig): + env_var: str = "default_value" + + def backend_cls(self): + return MyBackend + + class MyTrainer(DataParallelTrainer): + def __init__(self, train_loop_per_worker, my_backend_config: + MyBackendConfig, **kwargs): + + super().__init__( + train_loop_per_worker, + backend_config=my_backend_config, **kwargs) + + Args: + train_loop_per_worker: The training function to execute. + This can either take in no arguments or a ``config`` dict. + train_loop_config: Configurations to pass into + ``train_loop_per_worker`` if it accepts an argument. + backend_config: Configuration for setting up a Backend (e.g. Torch, + Tensorflow, Horovod) on each worker to enable distributed + communication. If no Backend should be set up, then set this to None. + scaling_config: Configuration for how to scale data parallel training. + dataset_config: Configuration for dataset ingest. This is merged with the + default dataset config for the given trainer (`cls._dataset_config`). + run_config: Configuration for the execution of the training run. + datasets: Ray Datasets to use for training and evaluation. + This is a dict where the key is the name of the dataset, which + can be accessed from within the ``train_loop_per_worker`` by calling + ``train.get_dataset_shard(dataset_key)``. + By default, all datasets are sharded equally across workers. + This can be configured via ``dataset_config``. + metadata: Dict that should be made available via + `train.get_context().get_metadata()` and in `checkpoint.get_metadata()` + for checkpoints saved from this Trainer. Must be JSON-serializable. + resume_from_checkpoint: A checkpoint to resume training from. + """ + + # Exposed here for testing purposes. Should never need + # to be overriden. + _backend_executor_cls: Type[BackendExecutor] = BackendExecutor + _training_iterator_cls: Type[TrainingIterator] = TrainingIterator + + _scaling_config_allowed_keys = BaseTrainer._scaling_config_allowed_keys + [ + "num_workers", + "resources_per_worker", + "use_gpu", + "placement_strategy", + "accelerator_type", + ] + + # For backwards compatibility with the legacy dataset config API. + _dataset_config = None + + _fields_for_tuner_param_space = BaseTrainer._fields_for_tuner_param_space + [ + "train_loop_config" + ] + + def __init__( + self, + train_loop_per_worker: Union[Callable[[], None], Callable[[Dict], None]], + *, + train_loop_config: Optional[Dict] = None, + backend_config: Optional[BackendConfig] = None, + scaling_config: Optional[ScalingConfig] = None, + dataset_config: Optional[DataConfig] = None, + run_config: Optional[RunConfig] = None, + datasets: Optional[Dict[str, GenDataset]] = None, + metadata: Optional[Dict[str, Any]] = None, + resume_from_checkpoint: Optional[Checkpoint] = None, + ): + self._train_loop_per_worker = train_loop_per_worker + self._train_loop_config = train_loop_config + + if dataset_config is None: + dataset_config = DataConfig() + + if not isinstance(dataset_config, DataConfig): + raise ValueError( + "`dataset_config` must be an instance of ray.train.DataConfig, " + f"was: {dataset_config}" + ) + self._data_config = dataset_config + + backend_config = ( + backend_config if backend_config is not None else BackendConfig() + ) + self._backend_config = backend_config + + super(DataParallelTrainer, self).__init__( + scaling_config=scaling_config, + run_config=run_config, + datasets=datasets, + metadata=metadata, + resume_from_checkpoint=resume_from_checkpoint, + ) + + train_total_resources = self.scaling_config.total_resources + self._data_config.set_train_total_resources( + train_total_resources.get("CPU", 0), + train_total_resources.get("GPU", 0), + ) + + if env_integer(RAY_TRAIN_ENABLE_STATE_TRACKING, 0): + from ray.train._internal.state.state_actor import get_or_create_state_actor + + get_or_create_state_actor() + + @classmethod + @Deprecated(message=_TRAINER_RESTORE_DEPRECATION_WARNING) + def restore( + cls, + path: str, + train_loop_per_worker: Optional[ + Union[Callable[[], None], Callable[[Dict], None]] + ] = None, + train_loop_config: Optional[Dict] = None, + **kwargs, + ): + """Restores a DataParallelTrainer from a previously interrupted/failed run. + + Args: + train_loop_per_worker: Optionally re-specified train loop function. + This should be used to re-specify a function that is not + restorable in a new Ray cluster (e.g., it holds onto outdated + object references). This should be the same training loop + that was passed to the original trainer constructor. + train_loop_config: Optionally re-specified train config. + This should similarly be used if the original `train_loop_config` + contained outdated object references, and it should not be modified + from what was originally passed in. + + See :meth:`BaseTrainer.restore() ` + for descriptions of the other arguments. + + Returns a restored instance of the `DataParallelTrainer`. + """ + return super(DataParallelTrainer, cls).restore( + path=path, + train_loop_per_worker=train_loop_per_worker, + train_loop_config=train_loop_config, + **kwargs, + ) + + def _validate_attributes(self): + super()._validate_attributes() + + self._validate_train_loop_per_worker( + self._train_loop_per_worker, "train_loop_per_worker" + ) + + def _validate_train_loop_per_worker( + self, train_loop_per_worker: Callable, fn_name: str + ) -> None: + num_required_params = count_required_parameters(train_loop_per_worker) + if num_required_params > 1: + raise ValueError( + f"{fn_name} should take in 0 or 1 arguments, " + f"but it accepts {num_required_params} arguments instead." + ) + + @classmethod + def _validate_scaling_config(cls, scaling_config: ScalingConfig) -> ScalingConfig: + scaling_config = super(DataParallelTrainer, cls)._validate_scaling_config( + scaling_config + ) + + # This validation happens after the scaling config is updated from + # its specification in the Tuner `param_space` + if not scaling_config.use_gpu and "GPU" in ray.available_resources(): + logger.info( + "GPUs are detected in your Ray cluster, but GPU " + "training is not enabled for this trainer. To enable " + "GPU training, make sure to set `use_gpu` to True " + "in your scaling config." + ) + + if scaling_config.num_workers is None: + raise ValueError( + "You must specify the 'num_workers' in `scaling_config` as either an " + f"argument of `{cls.__name__}` or through the `param_space` of a " + "`Tuner` (if performing hyperparameter tuning)." + ) + + if scaling_config.num_workers <= 0: + raise ValueError( + "'num_workers' in `scaling_config` must be a positive " + f"integer. Received {scaling_config.num_workers}" + ) + + return scaling_config + + def _run_training(self, training_iterator: TrainingIterator) -> None: + """This method loops over the `TrainingIterator`: + The actual iteration (for ... in ...) waits for the training function + on each worker to report a result and supplies it as a list of results. + Afterwards (in the body of the loop), it will report the result + to the Tune session. + The iterator ends after the training function on each worker has finished. + """ + for training_results in training_iterator: + # TODO(ml-team): add ability to report results from multiple workers. + self._propagate_results(training_results) + + def _propagate_results(self, training_results: List[_TrainingResult]): + first_worker_result = training_results[0] + assert all(isinstance(result, _TrainingResult) for result in training_results) + + tune_session = get_session() + + # Check if any workers reported a checkpoint. + # If so, report a checkpoint pointing to the persisted location + # to Tune for book-keeping. + # NOTE: This removes the restriction for any individual worker + # (ex: global rank 0 worker) from needing to report a checkpoint. + # All workers reported a checkpoint to the same fs path, so there's + # no need to report multiple checkpoints to Tune. + worker_checkpoints = [ + result.checkpoint + for result in training_results + if result.checkpoint is not None + ] + at_least_one_reported_checkpoint = len(worker_checkpoints) > 0 + + if at_least_one_reported_checkpoint: + # Update the coordinator's checkpoint index to the latest. + # This is what keeps the checkpoint index in line with the workers. + tune_session.storage._update_checkpoint_index(first_worker_result.metrics) + + # Make sure that all workers uploaded to the same location. + assert all( + checkpoint.path == tune_session.storage.checkpoint_fs_path + for checkpoint in worker_checkpoints + ) + + checkpoint = ( + Checkpoint( + filesystem=tune_session.storage.storage_filesystem, + path=tune_session.storage.checkpoint_fs_path, + ) + if at_least_one_reported_checkpoint + else None + ) + + tracked_training_result = _TrainingResult( + checkpoint=checkpoint, + metrics=first_worker_result.metrics, + ) + + logger.debug( + "Report (metrics, checkpoint) to the Tune session:\n" + f" metrics={tracked_training_result.metrics}\n" + f" checkpoint={tracked_training_result.checkpoint}" + ) + + # Report the metrics and checkpoint to Tune. + tune_session._report_training_result(tracked_training_result) + + def training_loop(self) -> None: + scaling_config = self._validate_scaling_config(self.scaling_config) + + train_loop_per_worker = construct_train_func( + self._train_loop_per_worker, + self._train_loop_config, + train_func_context=self._backend_config.train_func_context, + fn_arg_name="train_loop_per_worker", + discard_returns=True, + ) + + trial_info = TrialInfo( + name=session.get_trial_name(), + id=session.get_trial_id(), + resources=session.get_trial_resources(), + logdir=session.get_trial_dir(), + driver_ip=ray.util.get_node_ip_address(), + driver_node_id=ray.get_runtime_context().get_node_id(), + experiment_name=session.get_experiment_name(), + run_id=uuid.uuid4().hex, + ) + + backend_executor = self._backend_executor_cls( + backend_config=self._backend_config, + trial_info=trial_info, + num_workers=scaling_config.num_workers, + resources_per_worker=scaling_config._resources_per_worker_not_none, + max_retries=0, + ) + + # Start the remote actors. + backend_executor.start() + + training_iterator = self._training_iterator_cls( + backend_executor=backend_executor, + backend_config=self._backend_config, + train_func=train_loop_per_worker, + datasets=self.datasets, + metadata=self.metadata, + data_config=self._data_config, + checkpoint=self.starting_checkpoint, + ) + + self._run_training(training_iterator) + + # Shutdown workers. + backend_executor.shutdown() + + def get_dataset_config(self) -> DataConfig: + """Returns a copy of this Trainer's final dataset configs. + + Returns: + The merged default + user-supplied dataset config. + """ + + return self._data_config + + @repr_with_fallback(["ipywidgets", "8"]) + def _repr_mimebundle_(self, **kwargs): + """Returns a mimebundle with an ipywidget repr and a simple text repr. + + Depending on the frontend where the data is being displayed, + different mimetypes will be used from this bundle. + See https://ipython.readthedocs.io/en/stable/config/integrating.html + for information about this method, and + https://ipywidgets.readthedocs.io/en/latest/embedding.html + for more information about the jupyter widget mimetype. + + Returns: + A mimebundle containing an ipywidget repr and a simple text repr. + """ + from ipywidgets import HTML, Layout, Tab, VBox + + title = HTML(f"

    {self.__class__.__name__}

    ") + + children = [] + titles = [] + + if self.datasets: + children.append(self._datasets_repr_()) + titles.append("Datasets") + + children.append(HTML(self._data_config_repr_html_())) + titles.append("Data Config") + + if self._train_loop_config: + children.append(HTML(self._train_loop_config_repr_html_())) + titles.append("Train Loop Config") + + if self.scaling_config: + children.append(HTML(self.scaling_config._repr_html_())) + titles.append("Scaling Config") + + if self.run_config: + children.append(HTML(self.run_config._repr_html_())) + titles.append("Run Config") + + if self._backend_config: + children.append(HTML(self._backend_config._repr_html_())) + titles.append("Backend Config") + + tab = Tab(children, titles=titles) + widget = VBox([title, tab], layout=Layout(width="100%")) + bundle = widget._repr_mimebundle_(**kwargs) + bundle.update( + { + "text/plain": repr(self), + } + ) + return bundle + + def _train_loop_config_repr_html_(self) -> str: + if self._train_loop_config: + table_data = {} + for k, v in self._train_loop_config.items(): + if isinstance(v, str) or str(v).isnumeric(): + table_data[k] = v + elif hasattr(v, "_repr_html_"): + table_data[k] = v._repr_html_() + else: + table_data[k] = str(v) + + return Template("title_data.html.j2").render( + title="Train Loop Config", + data=Template("scrollableTable.html.j2").render( + table=tabulate( + table_data.items(), + headers=["Setting", "Value"], + showindex=False, + tablefmt="unsafehtml", + ), + max_height="none", + ), + ) + else: + return "" + + def _data_config_repr_html_(self) -> str: + # TODO make this rendering nicer. + content = [str(self._data_config)] + return Template("rendered_html_common.html.j2").render(content=content) + + def _datasets_repr_(self) -> str: + from ipywidgets import HTML, Layout, VBox + + content = [] + if self.datasets: + for name, config in self.datasets.items(): + tab = config._tab_repr_() + if tab: + content.append( + HTML( + Template("title_data.html.j2").render( + title=f"Dataset - {name}", data=None + ) + ) + ) + content.append(config._tab_repr_()) + + return VBox(content, layout=Layout(width="100%")) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/error.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/error.py new file mode 100644 index 0000000000000000000000000000000000000000..1aa8c82471bbe8c800b2415c8af3b1aef601d00d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/error.py @@ -0,0 +1,6 @@ +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +class SessionMisuseError(Exception): + """Indicates a method or function was used outside of a session.""" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/predictor.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/predictor.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4ef100e360b14cdabc71a7fc9a3dc4e25d771b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/predictor.py @@ -0,0 +1,254 @@ +import abc +from typing import Callable, Dict, Optional, Type, Union + +import numpy as np +import pandas as pd + +from ray.air.data_batch_type import DataBatchType +from ray.air.util.data_batch_conversion import ( + BatchFormat, + _convert_batch_type_to_numpy, + _convert_batch_type_to_pandas, +) +from ray.data import Preprocessor +from ray.train import Checkpoint +from ray.util.annotations import DeveloperAPI, PublicAPI + +try: + import pyarrow + + pa_table = pyarrow.Table +except ImportError: + pa_table = None + +# Reverse mapping from data batch type to batch format. +TYPE_TO_ENUM: Dict[Type[DataBatchType], BatchFormat] = { + np.ndarray: BatchFormat.NUMPY, + dict: BatchFormat.NUMPY, + pd.DataFrame: BatchFormat.PANDAS, +} + + +@PublicAPI(stability="beta") +class PredictorNotSerializableException(RuntimeError): + """Error raised when trying to serialize a Predictor instance.""" + + pass + + +@PublicAPI(stability="beta") +class Predictor(abc.ABC): + """Predictors load models from checkpoints to perform inference. + + .. note:: + The base ``Predictor`` class cannot be instantiated directly. Only one of + its subclasses can be used. + + **How does a Predictor work?** + + Predictors expose a ``predict`` method that accepts an input batch of type + ``DataBatchType`` and outputs predictions of the same type as the input batch. + + When the ``predict`` method is called the following occurs: + + - The input batch is converted into a pandas DataFrame. Tensor input (like a + ``np.ndarray``) will be converted into a single column Pandas Dataframe. + - If there is a :ref:`Preprocessor ` saved in the provided + :class:`Checkpoint `, the preprocessor will be used to + transform the DataFrame. + - The transformed DataFrame will be passed to the model for inference (via the + ``predictor._predict_pandas`` method). + - The predictions will be outputted by ``predict`` in the same type as the + original input. + + **How do I create a new Predictor?** + + To implement a new Predictor for your particular framework, you should subclass + the base ``Predictor`` and implement the following two methods: + + 1. ``_predict_pandas``: Given a pandas.DataFrame input, return a + pandas.DataFrame containing predictions. + 2. ``from_checkpoint``: Logic for creating a Predictor from a + :class:`Checkpoint `. + 3. Optionally ``_predict_numpy`` for better performance when working with + tensor data to avoid extra copies from Pandas conversions. + """ + + def __init__(self, preprocessor: Optional[Preprocessor] = None): + """Subclasseses must call Predictor.__init__() to set a preprocessor.""" + self._preprocessor: Optional[Preprocessor] = preprocessor + # Whether tensor columns should be automatically cast from/to the tensor + # extension type at UDF boundaries. This can be overridden by subclasses. + self._cast_tensor_columns = False + + @classmethod + @abc.abstractmethod + def from_checkpoint(cls, checkpoint: Checkpoint, **kwargs) -> "Predictor": + """Create a specific predictor from a checkpoint. + + Args: + checkpoint: Checkpoint to load predictor data from. + kwargs: Arguments specific to predictor implementations. + + Returns: + Predictor: Predictor object. + """ + raise NotImplementedError + + @classmethod + def from_pandas_udf( + cls, pandas_udf: Callable[[pd.DataFrame], pd.DataFrame] + ) -> "Predictor": + """Create a Predictor from a Pandas UDF. + + Args: + pandas_udf: A function that takes a pandas.DataFrame and other + optional kwargs and returns a pandas.DataFrame. + """ + + class PandasUDFPredictor(Predictor): + @classmethod + def from_checkpoint(cls, checkpoint: Checkpoint, **kwargs) -> "Predictor": + return PandasUDFPredictor() + + def _predict_pandas(self, df, **kwargs) -> "pd.DataFrame": + return pandas_udf(df, **kwargs) + + return PandasUDFPredictor() + + def get_preprocessor(self) -> Optional[Preprocessor]: + """Get the preprocessor to use prior to executing predictions.""" + return self._preprocessor + + def set_preprocessor(self, preprocessor: Optional[Preprocessor]) -> None: + """Set the preprocessor to use prior to executing predictions.""" + self._preprocessor = preprocessor + + @classmethod + @DeveloperAPI + def preferred_batch_format(cls) -> BatchFormat: + """Batch format hint for upstream producers to try yielding best block format. + + The preferred batch format to use if both `_predict_pandas` and + `_predict_numpy` are implemented. Defaults to Pandas. + + Can be overriden by predictor classes depending on the framework type, + e.g. TorchPredictor prefers Numpy and XGBoostPredictor prefers Pandas as + native batch format. + + """ + return BatchFormat.PANDAS + + @classmethod + def _batch_format_to_use(cls) -> BatchFormat: + """Determine the batch format to use for the predictor.""" + has_pandas_implemented = cls._predict_pandas != Predictor._predict_pandas + has_numpy_implemented = cls._predict_numpy != Predictor._predict_numpy + if has_pandas_implemented and has_numpy_implemented: + return cls.preferred_batch_format() + elif has_pandas_implemented: + return BatchFormat.PANDAS + elif has_numpy_implemented: + return BatchFormat.NUMPY + else: + raise NotImplementedError( + f"Predictor {cls.__name__} must implement at least one of " + "`_predict_pandas` and `_predict_numpy`." + ) + + def _set_cast_tensor_columns(self): + """Enable automatic tensor column casting. + + If this is called on a predictor, the predictor will cast tensor columns to + NumPy ndarrays in the input to the preprocessors and cast tensor columns back to + the tensor extension type in the prediction outputs. + """ + self._cast_tensor_columns = True + + def predict(self, data: DataBatchType, **kwargs) -> DataBatchType: + """Perform inference on a batch of data. + + Args: + data: A batch of input data of type ``DataBatchType``. + kwargs: Arguments specific to predictor implementations. These are passed + directly to ``_predict_numpy`` or ``_predict_pandas``. + + Returns: + DataBatchType: + Prediction result. The return type will be the same as the input type. + """ + if not hasattr(self, "_preprocessor"): + raise NotImplementedError( + "Subclasses of Predictor must call Predictor.__init__(preprocessor)." + ) + try: + batch_format = TYPE_TO_ENUM[type(data)] + except KeyError: + raise RuntimeError( + f"Invalid input data type of {type(data)}, supported " + f"types: {list(TYPE_TO_ENUM.keys())}" + ) + + if self._preprocessor: + data = self._preprocessor.transform_batch(data) + + batch_format_to_use = self._batch_format_to_use() + + # We can finish prediction as long as one predict method is implemented. + # For prediction, we have to return back in the same format as the input. + if batch_format == BatchFormat.PANDAS: + if batch_format_to_use == BatchFormat.PANDAS: + return self._predict_pandas( + _convert_batch_type_to_pandas(data), **kwargs + ) + elif batch_format_to_use == BatchFormat.NUMPY: + return _convert_batch_type_to_pandas( + self._predict_numpy(_convert_batch_type_to_numpy(data), **kwargs) + ) + elif batch_format == BatchFormat.NUMPY: + if batch_format_to_use == BatchFormat.PANDAS: + return _convert_batch_type_to_numpy( + self._predict_pandas(_convert_batch_type_to_pandas(data), **kwargs) + ) + elif batch_format_to_use == BatchFormat.NUMPY: + return self._predict_numpy(_convert_batch_type_to_numpy(data), **kwargs) + + @DeveloperAPI + def _predict_pandas(self, data: "pd.DataFrame", **kwargs) -> "pd.DataFrame": + """Perform inference on a Pandas DataFrame. + + Args: + data: A pandas DataFrame to perform predictions on. + kwargs: Arguments specific to the predictor implementation. + + Returns: + A pandas DataFrame containing the prediction result. + + """ + raise NotImplementedError + + @DeveloperAPI + def _predict_numpy( + self, data: Union[np.ndarray, Dict[str, np.ndarray]], **kwargs + ) -> Union[np.ndarray, Dict[str, np.ndarray]]: + """Perform inference on a Numpy data. + + All Predictors working with tensor data (like deep learning predictors) + should implement this method. + + Args: + data: A Numpy ndarray or dictionary of ndarrays to perform predictions on. + kwargs: Arguments specific to the predictor implementation. + + Returns: + A Numpy ndarray or dictionary of ndarray containing the prediction result. + + """ + raise NotImplementedError + + def __reduce__(self): + raise PredictorNotSerializableException( + "Predictor instances are not serializable. Instead, you may want " + "to serialize a checkpoint and initialize the Predictor with " + "Predictor.from_checkpoint." + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/session.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/session.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/trainer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..725ba029d766c37d838e456f58abd2182e836a8d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/trainer.py @@ -0,0 +1,194 @@ +import logging +import traceback +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, TypeVar, Union + +from ray.air._internal.util import ( + StartTraceback, + StartTracebackWithWorkerRank, + skip_exceptions, +) +from ray.data import Dataset +from ray.train import Checkpoint, DataConfig +from ray.train._internal.backend_executor import ( + BackendExecutor, + InactiveWorkerGroupError, + TrainBackendError, + TrainingWorkerError, +) +from ray.train._internal.session import _TrainingResult, _TrainSession, get_session +from ray.train._internal.utils import ActorWrapper +from ray.train.backend import BackendConfig +from ray.train.base_trainer import ( # noqa: F401 + BaseTrainer, + GenDataset, + TrainingFailedError, +) +from ray.util.annotations import DeveloperAPI + +T = TypeVar("T") +S = TypeVar("S") + +logger = logging.getLogger(__name__) + + +@DeveloperAPI +class TrainingIterator: + """An iterator over Train results. Returned by ``trainer.run_iterator``.""" + + def __init__( + self, + backend_executor: Union[BackendExecutor, ActorWrapper], + backend_config: BackendConfig, + train_func: Union[Callable[[], T], Callable[[Dict[str, Any]], T]], + datasets: Dict[str, Dataset], + metadata: Dict[str, Any], + data_config: DataConfig, + checkpoint: Optional[Union[Dict, str, Path, Checkpoint]], + ): + self._backend_executor = backend_executor + self._backend = backend_config.backend_cls() + self._train_func = train_func + self._datasets = datasets + self._metadata = metadata + self._data_config = data_config + + self._start_training( + train_func=train_func, + datasets=self._datasets, + metadata=self._metadata, + data_config=self._data_config, + checkpoint=checkpoint, + ) + + self._finished_training = False + + def __iter__(self): + return self + + def _start_training( + self, + train_func, + datasets, + metadata, + data_config, + checkpoint: Optional[Checkpoint] = None, + ): + tune_session: _TrainSession = get_session() + assert tune_session, "`_start_training` should only be called from within Tune" + storage = tune_session.storage + + self._run_with_error_handling( + lambda: self._backend_executor.start_training( + train_func=train_func, + datasets=datasets, + metadata=metadata, + data_config=data_config, + storage=storage, + checkpoint=checkpoint, + ) + ) + + def _run_with_error_handling(self, func: Callable): + try: + return func() + except TrainingWorkerError: + # TODO(ml-team): This Train fault-tolerance code doesn't get used + # since max_retries=0 + # Workers have already been restarted. + logger.info( + "Workers have been successfully restarted. Resuming " + "training from latest checkpoint." + ) + self._start_training( + self._train_func, + self._datasets, + self._metadata, + self._data_config, + ) + return self._run_with_error_handling(func) + except InactiveWorkerGroupError: + raise RuntimeError( + "This Trainer is not active. It is either shutdown " + "already or never started in the first place. " + "Either create a new Trainer or start this one." + ) from None + except TrainBackendError: + raise RuntimeError( + "Training failed. You should not be seeing " + "this error and this is a bug. Please create " + "a new issue at " + "https://github.com/ray-project/ray." + ) from None + + def __next__(self): + if self.is_finished(): + self._backend_executor.report_final_run_status(errored=False) + raise StopIteration + try: + next_results = self._run_with_error_handling(self._fetch_next_result) + if next_results is None: + self._backend_executor.report_final_run_status(errored=False) + self._run_with_error_handling(self._finish_training) + self._finished_training = True + raise StopIteration + else: + return next_results + except StartTraceback as e: + # If this is a StartTraceback, then this is a user error. + # We raise it directly + if isinstance(e, StartTracebackWithWorkerRank): + failed_rank = e.worker_rank + else: + failed_rank = None + + # Extract the stack trace from the exception + e = skip_exceptions(e) + stack_trace = "".join( + traceback.format_exception(type(e), e, e.__traceback__) + ) + + self._backend_executor.report_final_run_status( + errored=True, stack_trace=stack_trace, failed_rank=failed_rank + ) + try: + # Exception raised in at least one training worker. Immediately raise + # this error to the user and do not attempt to terminate gracefully. + self._backend_executor.shutdown(graceful_termination=False) + self._finished_training = True + except Exception: + pass + raise + + def _fetch_next_result(self) -> Optional[List[Dict]]: + """Fetch next results produced by ``session.report()`` from each worker. + + Assumes ``start_training`` has already been called. + + Returns: + A list of dictionaries of values passed to ``session.report()`` from + each worker. Each item corresponds to an intermediate result + a single worker. If there are no more items to fetch, + returns None. + """ + results = self._backend_executor.get_next_results() + if results is None: + return None + assert all(isinstance(result, _TrainingResult) for result in results) + return results + + def _finish_training(self): + """Finish training and return final results. Propagate any exceptions. + + Blocks until training is finished on all workers. + + Assumes `start_training` has already been called. + + Returns: + A list of return values from calling ``train_func`` on each worker. + Each item corresponds to the return value from a single worker. + """ + return self._backend_executor.finish_training() + + def is_finished(self) -> bool: + return self._finished_training diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/utils.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..395cd01ab968237b5f727a93b4d8e6b3e7861edc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/train/utils.py @@ -0,0 +1,19 @@ +import warnings + +from ray.util.annotations import RayDeprecationWarning + + +def _copy_doc(copy_func): + def wrapped(func): + func.__doc__ = copy_func.__doc__ + return func + + return wrapped + + +def _log_deprecation_warning(message: str): + warnings.warn( + message, + RayDeprecationWarning, + stacklevel=2, + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7f49e6e41d0eeb22cb2161a55aab14802cf9b0e4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/__init__.py @@ -0,0 +1,114 @@ +# isort: off +# Try import ray[tune] core requirements (defined in setup.py) +try: + import fsspec # noqa: F401 + import pandas # noqa: F401 + import pyarrow # noqa: F401 + import requests # noqa: F401 +except ImportError as exc: + raise ImportError( + "Can't import ray.tune as some dependencies are missing. " + 'Run `pip install "ray[tune]"` to fix.' + ) from exc +# isort: on + +from ray.tune.trainable.trainable_fn_utils import Checkpoint, get_checkpoint, report +from ray.tune.impl.config import CheckpointConfig, FailureConfig, RunConfig +from ray.tune.syncer import SyncConfig +from ray.air.result import Result +from ray.tune.analysis import ExperimentAnalysis +from ray.tune.callback import Callback +from ray.tune.context import TuneContext, get_context +from ray.tune.error import TuneError +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.experiment import Experiment +from ray.tune.progress_reporter import ( + CLIReporter, + JupyterNotebookReporter, + ProgressReporter, +) +from ray.tune.registry import register_env, register_trainable +from ray.tune.result_grid import ResultGrid +from ray.tune.schedulers import create_scheduler +from ray.tune.search import create_searcher, grid_search +from ray.tune.search.sample import ( + choice, + lograndint, + loguniform, + qlograndint, + qloguniform, + qrandint, + qrandn, + quniform, + randint, + randn, + sample_from, + uniform, +) +from ray.tune.stopper import Stopper +from ray.tune.trainable import Trainable +from ray.tune.trainable.util import with_parameters, with_resources +from ray.tune.tune import run, run_experiments +from ray.tune.tune_config import ResumeConfig, TuneConfig +from ray.tune.tuner import Tuner + +__all__ = [ + "Trainable", + "Callback", + "TuneError", + "grid_search", + "register_env", + "register_trainable", + "run", + "run_experiments", + "with_parameters", + "with_resources", + "Stopper", + "Experiment", + "sample_from", + "uniform", + "quniform", + "choice", + "randint", + "lograndint", + "qrandint", + "qlograndint", + "randn", + "qrandn", + "loguniform", + "qloguniform", + "ExperimentAnalysis", + "CLIReporter", + "JupyterNotebookReporter", + "ProgressReporter", + "ResultGrid", + "create_searcher", + "create_scheduler", + "PlacementGroupFactory", + "Tuner", + "TuneConfig", + "ResumeConfig", + "RunConfig", + "CheckpointConfig", + "FailureConfig", + "Result", + "Checkpoint", + "get_checkpoint", + "report", + "get_context", + "TuneContext", + "SyncConfig", +] + +report.__module__ = "ray.tune" +get_checkpoint.__module__ = "ray.tune" +get_context.__module__ = "ray.tune" +TuneContext.__module__ = "ray.tune" +Checkpoint.__module__ = "ray.tune" +Result.__module__ = "ray.tune" +RunConfig.__module__ = "ray.tune" +CheckpointConfig.__module__ = "ray.tune" +FailureConfig.__module__ = "ray.tune" + + +# DO NOT ADD ANYTHING AFTER THIS LINE. diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/callback.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/callback.py new file mode 100644 index 0000000000000000000000000000000000000000..666c6a592ecb3ec9121cb5a14c4db09b4706d05f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/callback.py @@ -0,0 +1,512 @@ +import glob +import warnings +from abc import ABCMeta +from pathlib import Path +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +import ray.tune +from ray.tune.utils.util import _atomic_save, _load_newest_checkpoint +from ray.util.annotations import DeveloperAPI, PublicAPI + +if TYPE_CHECKING: + from ray.tune.experiment import Trial + from ray.tune.stopper import Stopper + + +class _CallbackMeta(ABCMeta): + """A helper metaclass to ensure container classes (e.g. CallbackList) have + implemented all the callback methods (e.g. `on_*`). + """ + + def __new__(mcs, name: str, bases: Tuple[type], attrs: Dict[str, Any]) -> type: + cls = super().__new__(mcs, name, bases, attrs) + + if mcs.need_check(cls, name, bases, attrs): + mcs.check(cls, name, bases, attrs) + + return cls + + @classmethod + def need_check( + mcs, cls: type, name: str, bases: Tuple[type], attrs: Dict[str, Any] + ) -> bool: + return attrs.get("IS_CALLBACK_CONTAINER", False) + + @classmethod + def check( + mcs, cls: type, name: str, bases: Tuple[type], attrs: Dict[str, Any] + ) -> None: + methods = set() + for base in bases: + methods.update( + attr_name + for attr_name, attr in vars(base).items() + if mcs.need_override_by_subclass(attr_name, attr) + ) + overridden = { + attr_name + for attr_name, attr in attrs.items() + if mcs.need_override_by_subclass(attr_name, attr) + } + missing = methods.difference(overridden) + if missing: + raise TypeError( + f"Found missing callback method: {missing} " + f"in class {cls.__module__}.{cls.__qualname__}." + ) + + @classmethod + def need_override_by_subclass(mcs, attr_name: str, attr: Any) -> bool: + return ( + ( + attr_name.startswith("on_") + and not attr_name.startswith("on_trainer_init") + ) + or attr_name == "setup" + ) and callable(attr) + + +@PublicAPI(stability="beta") +class Callback(metaclass=_CallbackMeta): + """Tune base callback that can be extended and passed to a ``TrialRunner`` + + Tune callbacks are called from within the ``TrialRunner`` class. There are + several hooks that can be used, all of which are found in the submethod + definitions of this base class. + + The parameters passed to the ``**info`` dict vary between hooks. The + parameters passed are described in the docstrings of the methods. + + This example will print a metric each time a result is received: + + .. testcode:: + + from ray import tune + from ray.tune import Callback + + + class MyCallback(Callback): + def on_trial_result(self, iteration, trials, trial, result, + **info): + print(f"Got result: {result['metric']}") + + + def train_func(config): + for i in range(10): + tune.report(metric=i) + + tuner = tune.Tuner( + train_func, + run_config=tune.RunConfig( + callbacks=[MyCallback()] + ) + ) + tuner.fit() + + .. testoutput:: + :hide: + + ... + """ + + # File templates for any artifacts written by this callback + # These files should live in the `trial.local_path` for each trial. + # TODO(ml-team): Make this more visible to users to override. Internal use for now. + _SAVED_FILE_TEMPLATES = [] + + # arguments here match Experiment.public_spec + def setup( + self, + stop: Optional["Stopper"] = None, + num_samples: Optional[int] = None, + total_num_samples: Optional[int] = None, + **info, + ): + """Called once at the very beginning of training. + + Any Callback setup should be added here (setting environment + variables, etc.) + + Arguments: + stop: Stopping criteria. + If ``time_budget_s`` was passed to ``tune.RunConfig``, a + ``TimeoutStopper`` will be passed here, either by itself + or as a part of a ``CombinedStopper``. + num_samples: Number of times to sample from the + hyperparameter space. Defaults to 1. If `grid_search` is + provided as an argument, the grid will be repeated + `num_samples` of times. If this is -1, (virtually) infinite + samples are generated until a stopping condition is met. + total_num_samples: Total number of samples factoring + in grid search samplers. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_step_begin(self, iteration: int, trials: List["Trial"], **info): + """Called at the start of each tuning loop step. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_step_end(self, iteration: int, trials: List["Trial"], **info): + """Called at the end of each tuning loop step. + + The iteration counter is increased before this hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_start( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after starting a trial instance. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has been started. + **info: Kwargs dict for forward compatibility. + + """ + pass + + def on_trial_restore( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after restoring a trial instance. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has been restored. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_save( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after receiving a checkpoint from a trial. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just saved a checkpoint. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_result( + self, + iteration: int, + trials: List["Trial"], + trial: "Trial", + result: Dict, + **info, + ): + """Called after receiving a result from a trial. + + The search algorithm and scheduler are notified before this + hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just sent a result. + result: Result that the trial sent. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_complete( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after a trial instance completed. + + The search algorithm and scheduler are notified before this + hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has been completed. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_recover( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after a trial instance failed (errored) but the trial is scheduled + for retry. + + The search algorithm and scheduler are not notified. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has errored. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_trial_error( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + """Called after a trial instance failed (errored). + + The search algorithm and scheduler are notified before this + hook is called. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has errored. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_checkpoint( + self, + iteration: int, + trials: List["Trial"], + trial: "Trial", + checkpoint: "ray.tune.Checkpoint", + **info, + ): + """Called after a trial saved a checkpoint with Tune. + + Arguments: + iteration: Number of iterations of the tuning loop. + trials: List of trials. + trial: Trial that just has errored. + checkpoint: Checkpoint object that has been saved + by the trial. + **info: Kwargs dict for forward compatibility. + """ + pass + + def on_experiment_end(self, trials: List["Trial"], **info): + """Called after experiment is over and all trials have concluded. + + Arguments: + trials: List of trials. + **info: Kwargs dict for forward compatibility. + """ + pass + + def get_state(self) -> Optional[Dict]: + """Get the state of the callback. + + This method should be implemented by subclasses to return a dictionary + representation of the object's current state. + + This is called automatically by Tune to periodically checkpoint callback state. + Upon :ref:`Tune experiment restoration `, + callback state will be restored via :meth:`~ray.tune.Callback.set_state`. + + .. testcode:: + + from typing import Dict, List, Optional + + from ray.tune import Callback + from ray.tune.experiment import Trial + + class MyCallback(Callback): + def __init__(self): + self._trial_ids = set() + + def on_trial_start( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self._trial_ids.add(trial.trial_id) + + def get_state(self) -> Optional[Dict]: + return {"trial_ids": self._trial_ids.copy()} + + def set_state(self, state: Dict) -> Optional[Dict]: + self._trial_ids = state["trial_ids"] + + Returns: + dict: State of the callback. Should be `None` if the callback does not + have any state to save (this is the default). + """ + return None + + def set_state(self, state: Dict): + """Set the state of the callback. + + This method should be implemented by subclasses to restore the callback's + state based on the given dict state. + + This is used automatically by Tune to restore checkpoint callback state + on :ref:`Tune experiment restoration `. + + See :meth:`~ray.tune.Callback.get_state` for an example implementation. + + Args: + state: State of the callback. + """ + pass + + +@DeveloperAPI +class CallbackList(Callback): + """Call multiple callbacks at once.""" + + IS_CALLBACK_CONTAINER = True + CKPT_FILE_TMPL = "callback-states-{}.pkl" + + def __init__(self, callbacks: List[Callback]): + self._callbacks = callbacks + + def setup(self, **info): + for callback in self._callbacks: + try: + callback.setup(**info) + except TypeError as e: + if "argument" in str(e): + warnings.warn( + "Please update `setup` method in callback " + f"`{callback.__class__}` to match the method signature" + " in `ray.tune.callback.Callback`.", + FutureWarning, + ) + callback.setup() + else: + raise e + + def on_step_begin(self, **info): + for callback in self._callbacks: + callback.on_step_begin(**info) + + def on_step_end(self, **info): + for callback in self._callbacks: + callback.on_step_end(**info) + + def on_trial_start(self, **info): + for callback in self._callbacks: + callback.on_trial_start(**info) + + def on_trial_restore(self, **info): + for callback in self._callbacks: + callback.on_trial_restore(**info) + + def on_trial_save(self, **info): + for callback in self._callbacks: + callback.on_trial_save(**info) + + def on_trial_result(self, **info): + for callback in self._callbacks: + callback.on_trial_result(**info) + + def on_trial_complete(self, **info): + for callback in self._callbacks: + callback.on_trial_complete(**info) + + def on_trial_recover(self, **info): + for callback in self._callbacks: + callback.on_trial_recover(**info) + + def on_trial_error(self, **info): + for callback in self._callbacks: + callback.on_trial_error(**info) + + def on_checkpoint(self, **info): + for callback in self._callbacks: + callback.on_checkpoint(**info) + + def on_experiment_end(self, **info): + for callback in self._callbacks: + callback.on_experiment_end(**info) + + def get_state(self) -> Optional[Dict]: + """Gets the state of all callbacks contained within this list. + If there are no stateful callbacks, then None will be returned in order + to avoid saving an unnecessary callback checkpoint file.""" + state = {} + any_stateful_callbacks = False + for i, callback in enumerate(self._callbacks): + callback_state = callback.get_state() + if callback_state: + any_stateful_callbacks = True + state[i] = callback_state + if not any_stateful_callbacks: + return None + return state + + def set_state(self, state: Dict): + """Sets the state for all callbacks contained within this list. + Skips setting state for all stateless callbacks where `get_state` + returned None.""" + for i, callback in enumerate(self._callbacks): + callback_state = state.get(i, None) + if callback_state: + callback.set_state(callback_state) + + def save_to_dir(self, checkpoint_dir: str, session_str: str = "default"): + """Save the state of the callback list to the checkpoint_dir. + + Args: + checkpoint_dir: directory where the checkpoint is stored. + session_str: Unique identifier of the current run session (ex: timestamp). + """ + state_dict = self.get_state() + + if state_dict: + file_name = self.CKPT_FILE_TMPL.format(session_str) + tmp_file_name = f".tmp-{file_name}" + _atomic_save( + state=state_dict, + checkpoint_dir=checkpoint_dir, + file_name=file_name, + tmp_file_name=tmp_file_name, + ) + + def restore_from_dir(self, checkpoint_dir: str): + """Restore the state of the list of callbacks from the checkpoint_dir. + + You should check if it's possible to restore with `can_restore` + before calling this method. + + Args: + checkpoint_dir: directory where the checkpoint is stored. + + Raises: + RuntimeError: if unable to find checkpoint. + NotImplementedError: if the `set_state` method is not implemented. + """ + state_dict = _load_newest_checkpoint( + checkpoint_dir, self.CKPT_FILE_TMPL.format("*") + ) + if not state_dict: + raise RuntimeError( + "Unable to find checkpoint in {}.".format(checkpoint_dir) + ) + self.set_state(state_dict) + + def can_restore(self, checkpoint_dir: str) -> bool: + """Check if the checkpoint_dir contains the saved state for this callback list. + + Returns: + can_restore: True if the checkpoint_dir contains a file of the + format `CKPT_FILE_TMPL`. False otherwise. + """ + return any( + glob.iglob(Path(checkpoint_dir, self.CKPT_FILE_TMPL.format("*")).as_posix()) + ) + + def __len__(self) -> int: + return len(self._callbacks) + + def __getitem__(self, i: int) -> "Callback": + return self._callbacks[i] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/constants.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a71580b342a2157b2946a8c1458a65b7833bb7c4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/constants.py @@ -0,0 +1,36 @@ +# ================================================== +# Environment Variables +# ================================================== + +# Environment variable for Tune execution callbacks +RAY_TUNE_CALLBACKS_ENV_VAR = "RAY_TUNE_CALLBACKS" + +# NOTE: When adding a new environment variable, please track it in this list. +TUNE_ENV_VARS = { + "RAY_AIR_LOCAL_CACHE_DIR", + "TUNE_DISABLE_AUTO_CALLBACK_LOGGERS", + "TUNE_DISABLE_AUTO_INIT", + "TUNE_DISABLE_DATED_SUBDIR", + "TUNE_DISABLE_STRICT_METRIC_CHECKING", + "TUNE_DISABLE_SIGINT_HANDLER", + "TUNE_FORCE_TRIAL_CLEANUP_S", + "TUNE_FUNCTION_THREAD_TIMEOUT_S", + "TUNE_GLOBAL_CHECKPOINT_S", + "TUNE_MAX_LEN_IDENTIFIER", + "TUNE_MAX_PENDING_TRIALS_PG", + "TUNE_PLACEMENT_GROUP_PREFIX", + "TUNE_PLACEMENT_GROUP_RECON_INTERVAL", + "TUNE_PRINT_ALL_TRIAL_ERRORS", + "TUNE_RESULT_DIR", + "TUNE_RESULT_BUFFER_LENGTH", + "TUNE_RESULT_DELIM", + "TUNE_RESULT_BUFFER_MAX_TIME_S", + "TUNE_RESULT_BUFFER_MIN_TIME_S", + "TUNE_WARN_THRESHOLD_S", + "TUNE_WARN_INSUFFICENT_RESOURCE_THRESHOLD_S", + "TUNE_WARN_INSUFFICENT_RESOURCE_THRESHOLD_S_AUTOSCALER", + "TUNE_WARN_EXCESSIVE_EXPERIMENT_CHECKPOINT_SYNC_THRESHOLD_S", + "TUNE_STATE_REFRESH_PERIOD", + "TUNE_RESTORE_RETRY_NUM", + RAY_TUNE_CALLBACKS_ENV_VAR, +} diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/context.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/context.py new file mode 100644 index 0000000000000000000000000000000000000000..ef1046885b8e33451a3e31b8a7afb4fa694574d8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/context.py @@ -0,0 +1,116 @@ +import threading +from typing import Any, Dict, Optional + +from ray.train._internal import session +from ray.train.constants import ( + V2_MIGRATION_GUIDE_MESSAGE, + _v2_migration_warnings_enabled, +) +from ray.train.context import TrainContext as TrainV1Context +from ray.train.utils import _copy_doc +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.util.annotations import Deprecated, PublicAPI + +# The context singleton on this process. +_tune_context: Optional["TuneContext"] = None +_tune_context_lock = threading.Lock() + + +_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE = ( + "`{}` is deprecated for Ray Tune because there is no concept of worker ranks " + "for Ray Tune, so these methods only make sense to use in the context of " + f"a Ray Train worker. {V2_MIGRATION_GUIDE_MESSAGE}" +) + + +@PublicAPI(stability="beta") +class TuneContext(TrainV1Context): + """Context to access metadata within Ray Tune functions.""" + + # NOTE: These methods are deprecated on the TrainContext, but are still + # available on the TuneContext. Re-defining them here to avoid the + # deprecation warnings. + + @_copy_doc(session.get_trial_name) + def get_trial_name(self) -> str: + return session.get_trial_name() + + @_copy_doc(session.get_trial_id) + def get_trial_id(self) -> str: + return session.get_trial_id() + + @_copy_doc(session.get_trial_resources) + def get_trial_resources(self) -> PlacementGroupFactory: + return session.get_trial_resources() + + @_copy_doc(session.get_trial_dir) + def get_trial_dir(self) -> str: + return session.get_trial_dir() + + # Deprecated APIs + + @Deprecated + def get_metadata(self) -> Dict[str, Any]: + raise DeprecationWarning( + "`get_metadata` is deprecated for Ray Tune, as it has never been usable." + ) + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_world_size"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_world_size) + def get_world_size(self) -> int: + return session.get_world_size() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_world_rank"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_world_rank) + def get_world_rank(self) -> int: + return session.get_world_rank() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_local_rank"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_local_rank) + def get_local_rank(self) -> int: + return session.get_local_rank() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format( + "get_local_world_size" + ), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_local_world_size) + def get_local_world_size(self) -> int: + return session.get_local_world_size() + + @Deprecated( + message=_TRAIN_SPECIFIC_CONTEXT_DEPRECATION_MESSAGE.format("get_node_rank"), + warning=_v2_migration_warnings_enabled(), + ) + @_copy_doc(TrainV1Context.get_node_rank) + def get_node_rank(self) -> int: + return session.get_node_rank() + + +@PublicAPI(stability="beta") +def get_context() -> TuneContext: + """Get or create a singleton Ray Tune context. + + The context is only available in a tune function passed to the `ray.tune.Tuner`. + + See the :class:`~ray.tune.TuneContext` API reference to see available methods. + """ + global _tune_context + + with _tune_context_lock: + if _tune_context is None: + # TODO(justinvyu): This default should be a dummy context + # that is only used for testing / running outside of Tune. + _tune_context = TuneContext() + return _tune_context diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/error.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/error.py new file mode 100644 index 0000000000000000000000000000000000000000..9f2b427a2788e09a4c5bf5bc2d208dce31ae2dfd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/error.py @@ -0,0 +1,48 @@ +from ray.util.annotations import PublicAPI + + +@PublicAPI +class TuneError(Exception): + """General error class raised by ray.tune.""" + + pass + + +class _AbortTrialExecution(TuneError): + """Error that indicates a trial should not be retried.""" + + pass + + +class _SubCategoryTuneError(TuneError): + """The more specific TuneError that happens for a certain Tune + subroutine. For example starting/stopping a trial. + """ + + def __init__(self, traceback_str: str): + self.traceback_str = traceback_str + + def __str__(self): + return self.traceback_str + + +class _TuneStopTrialError(_SubCategoryTuneError): + """Error that happens when stopping a tune trial.""" + + pass + + +class _TuneStartTrialError(_SubCategoryTuneError): + """Error that happens when starting a tune trial.""" + + pass + + +class _TuneNoNextExecutorEventError(_SubCategoryTuneError): + """Error that happens when waiting to get the next event to + handle from RayTrialExecutor. + + Note: RayTaskError will be raised by itself and will not be using + this category. This category is for everything else.""" + + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/progress_reporter.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/progress_reporter.py new file mode 100644 index 0000000000000000000000000000000000000000..aa1c642fbe5f7c3c5bd18b1818fef74008659da1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/progress_reporter.py @@ -0,0 +1,1596 @@ +from __future__ import print_function + +import collections +import datetime +import numbers +import sys +import textwrap +import time +import warnings +from pathlib import Path +from typing import Any, Callable, Collection, Dict, List, Optional, Tuple, Union + +import numpy as np +import pandas as pd + +import ray +from ray._private.dict import flatten_dict +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.air.constants import EXPR_ERROR_FILE, TRAINING_ITERATION +from ray.air.util.node import _force_on_current_node +from ray.experimental.tqdm_ray import safe_print +from ray.tune.callback import Callback +from ray.tune.experiment.trial import DEBUG_PRINT_INTERVAL, Trial, _Location +from ray.tune.logger import pretty_print +from ray.tune.result import ( + AUTO_RESULT_KEYS, + DEFAULT_METRIC, + DONE, + EPISODE_REWARD_MEAN, + EXPERIMENT_TAG, + MEAN_ACCURACY, + MEAN_LOSS, + NODE_IP, + PID, + TIME_TOTAL_S, + TIMESTEPS_TOTAL, + TRIAL_ID, +) +from ray.tune.trainable import Trainable +from ray.tune.utils import unflattened_lookup +from ray.tune.utils.log import Verbosity, has_verbosity, set_verbosity +from ray.util.annotations import DeveloperAPI, PublicAPI +from ray.util.queue import Empty, Queue +from ray.widgets import Template + +try: + from collections.abc import Mapping, MutableMapping +except ImportError: + from collections import Mapping, MutableMapping + + +IS_NOTEBOOK = ray.widgets.util.in_notebook() + +SKIP_RESULTS_IN_REPORT = {"config", TRIAL_ID, EXPERIMENT_TAG, DONE} + + +@PublicAPI +class ProgressReporter: + """Abstract class for experiment progress reporting. + + `should_report()` is called to determine whether or not `report()` should + be called. Tune will call these functions after trial state transitions, + receiving training results, and so on. + """ + + def setup( + self, + start_time: Optional[float] = None, + total_samples: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + **kwargs, + ): + """Setup progress reporter for a new Ray Tune run. + + This function is used to initialize parameters that are set on runtime. + It will be called before any of the other methods. + + Defaults to no-op. + + Args: + start_time: Timestamp when the Ray Tune run is started. + total_samples: Number of samples the Ray Tune run will run. + metric: Metric to optimize. + mode: Must be one of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + **kwargs: Keyword arguments for forward-compatibility. + """ + pass + + def should_report(self, trials: List[Trial], done: bool = False): + """Returns whether or not progress should be reported. + + Args: + trials: Trials to report on. + done: Whether this is the last progress report attempt. + """ + raise NotImplementedError + + def report(self, trials: List[Trial], done: bool, *sys_info: Dict): + """Reports progress across trials. + + Args: + trials: Trials to report on. + done: Whether this is the last progress report attempt. + sys_info: System info. + """ + raise NotImplementedError + + +@DeveloperAPI +class TuneReporterBase(ProgressReporter): + """Abstract base class for the default Tune reporters. + + If metric_columns is not overridden, Tune will attempt to automatically + infer the metrics being outputted, up to 'infer_limit' number of + metrics. + + Args: + metric_columns: Names of metrics to + include in progress table. If this is a dict, the keys should + be metric names and the values should be the displayed names. + If this is a list, the metric name is used directly. + parameter_columns: Names of parameters to + include in progress table. If this is a dict, the keys should + be parameter names and the values should be the displayed names. + If this is a list, the parameter name is used directly. If empty, + defaults to all available parameters. + max_progress_rows: Maximum number of rows to print + in the progress table. The progress table describes the + progress of each trial. Defaults to 20. + max_error_rows: Maximum number of rows to print in the + error table. The error table lists the error file, if any, + corresponding to each trial. Defaults to 20. + max_column_length: Maximum column length (in characters). Column + headers and values longer than this will be abbreviated. + max_report_frequency: Maximum report frequency in seconds. + Defaults to 5s. + infer_limit: Maximum number of metrics to automatically infer + from tune results. + print_intermediate_tables: Print intermediate result + tables. If None (default), will be set to True for verbosity + levels above 3, otherwise False. If True, intermediate tables + will be printed with experiment progress. If False, tables + will only be printed at then end of the tuning run for verbosity + levels greater than 2. + metric: Metric used to determine best current trial. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + + # Truncated representations of column names (to accommodate small screens). + DEFAULT_COLUMNS = collections.OrderedDict( + { + MEAN_ACCURACY: "acc", + MEAN_LOSS: "loss", + TRAINING_ITERATION: "iter", + TIME_TOTAL_S: "total time (s)", + TIMESTEPS_TOTAL: "ts", + EPISODE_REWARD_MEAN: "reward", + } + ) + VALID_SUMMARY_TYPES = { + int, + float, + np.float32, + np.float64, + np.int32, + np.int64, + type(None), + } + + def __init__( + self, + *, + metric_columns: Optional[Union[List[str], Dict[str, str]]] = None, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: Optional[int] = None, + max_progress_rows: int = 20, + max_error_rows: int = 20, + max_column_length: int = 20, + max_report_frequency: int = 5, + infer_limit: int = 3, + print_intermediate_tables: Optional[bool] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + ): + self._total_samples = total_samples + self._metrics_override = metric_columns is not None + self._inferred_metrics = {} + self._metric_columns = metric_columns or self.DEFAULT_COLUMNS.copy() + self._parameter_columns = parameter_columns or [] + self._max_progress_rows = max_progress_rows + self._max_error_rows = max_error_rows + self._max_column_length = max_column_length + self._infer_limit = infer_limit + + if print_intermediate_tables is None: + self._print_intermediate_tables = has_verbosity(Verbosity.V3_TRIAL_DETAILS) + else: + self._print_intermediate_tables = print_intermediate_tables + + self._max_report_freqency = max_report_frequency + self._last_report_time = 0 + + self._start_time = time.time() + + self._metric = metric + self._mode = mode + self._sort_by_metric = sort_by_metric + + def setup( + self, + start_time: Optional[float] = None, + total_samples: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + **kwargs, + ): + self.set_start_time(start_time) + self.set_total_samples(total_samples) + self.set_search_properties(metric=metric, mode=mode) + + def set_search_properties(self, metric: Optional[str], mode: Optional[str]): + if (self._metric and metric) or (self._mode and mode): + raise ValueError( + "You passed a `metric` or `mode` argument to `tune.TuneConfig()`, but " + "the reporter you are using was already instantiated with their " + "own `metric` and `mode` parameters. Either remove the arguments " + "from your reporter or from your call to `tune.TuneConfig()`" + ) + + if metric: + self._metric = metric + if mode: + self._mode = mode + + if self._metric is None and self._mode: + # If only a mode was passed, use anonymous metric + self._metric = DEFAULT_METRIC + + return True + + def set_total_samples(self, total_samples: int): + self._total_samples = total_samples + + def set_start_time(self, timestamp: Optional[float] = None): + if timestamp is not None: + self._start_time = time.time() + else: + self._start_time = timestamp + + def should_report(self, trials: List[Trial], done: bool = False): + if time.time() - self._last_report_time > self._max_report_freqency: + self._last_report_time = time.time() + return True + return done + + def add_metric_column(self, metric: str, representation: Optional[str] = None): + """Adds a metric to the existing columns. + + Args: + metric: Metric to add. This must be a metric being returned + in training step results. + representation: Representation to use in table. Defaults to + `metric`. + """ + self._metrics_override = True + if metric in self._metric_columns: + raise ValueError("Column {} already exists.".format(metric)) + + if isinstance(self._metric_columns, MutableMapping): + representation = representation or metric + self._metric_columns[metric] = representation + else: + if representation is not None and representation != metric: + raise ValueError( + "`representation` cannot differ from `metric` " + "if this reporter was initialized with a list " + "of metric columns." + ) + self._metric_columns.append(metric) + + def add_parameter_column( + self, parameter: str, representation: Optional[str] = None + ): + """Adds a parameter to the existing columns. + + Args: + parameter: Parameter to add. This must be a parameter + specified in the configuration. + representation: Representation to use in table. Defaults to + `parameter`. + """ + if parameter in self._parameter_columns: + raise ValueError("Column {} already exists.".format(parameter)) + + if isinstance(self._parameter_columns, MutableMapping): + representation = representation or parameter + self._parameter_columns[parameter] = representation + else: + if representation is not None and representation != parameter: + raise ValueError( + "`representation` cannot differ from `parameter` " + "if this reporter was initialized with a list " + "of metric columns." + ) + self._parameter_columns.append(parameter) + + def _progress_str( + self, + trials: List[Trial], + done: bool, + *sys_info: Dict, + fmt: str = "psql", + delim: str = "\n", + ): + """Returns full progress string. + + This string contains a progress table and error table. The progress + table describes the progress of each trial. The error table lists + the error file, if any, corresponding to each trial. The latter only + exists if errors have occurred. + + Args: + trials: Trials to report on. + done: Whether this is the last progress report attempt. + fmt: Table format. See `tablefmt` in tabulate API. + delim: Delimiter between messages. + """ + if self._sort_by_metric and (self._metric is None or self._mode is None): + self._sort_by_metric = False + warnings.warn( + "Both 'metric' and 'mode' must be set to be able " + "to sort by metric. No sorting is performed." + ) + if not self._metrics_override: + user_metrics = self._infer_user_metrics(trials, self._infer_limit) + self._metric_columns.update(user_metrics) + messages = [ + "== Status ==", + _time_passed_str(self._start_time, time.time()), + *sys_info, + ] + if done: + max_progress = None + max_error = None + else: + max_progress = self._max_progress_rows + max_error = self._max_error_rows + + current_best_trial, metric = self._current_best_trial(trials) + if current_best_trial: + messages.append( + _best_trial_str(current_best_trial, metric, self._parameter_columns) + ) + + if has_verbosity(Verbosity.V1_EXPERIMENT): + # Will filter the table in `trial_progress_str` + messages.append( + _trial_progress_str( + trials, + metric_columns=self._metric_columns, + parameter_columns=self._parameter_columns, + total_samples=self._total_samples, + force_table=self._print_intermediate_tables, + fmt=fmt, + max_rows=max_progress, + max_column_length=self._max_column_length, + done=done, + metric=self._metric, + mode=self._mode, + sort_by_metric=self._sort_by_metric, + ) + ) + messages.append(_trial_errors_str(trials, fmt=fmt, max_rows=max_error)) + + return delim.join(messages) + delim + + def _infer_user_metrics(self, trials: List[Trial], limit: int = 4): + """Try to infer the metrics to print out.""" + if len(self._inferred_metrics) >= limit: + return self._inferred_metrics + self._inferred_metrics = {} + for t in trials: + if not t.last_result: + continue + for metric, value in t.last_result.items(): + if metric not in self.DEFAULT_COLUMNS: + if metric not in AUTO_RESULT_KEYS: + if type(value) in self.VALID_SUMMARY_TYPES: + self._inferred_metrics[metric] = metric + + if len(self._inferred_metrics) >= limit: + return self._inferred_metrics + return self._inferred_metrics + + def _current_best_trial(self, trials: List[Trial]): + if not trials: + return None, None + + metric, mode = self._metric, self._mode + # If no metric has been set, see if exactly one has been reported + # and use that one. `mode` must still be set. + if not metric: + if len(self._inferred_metrics) == 1: + metric = list(self._inferred_metrics.keys())[0] + + if not metric or not mode: + return None, metric + + metric_op = 1.0 if mode == "max" else -1.0 + best_metric = float("-inf") + best_trial = None + for t in trials: + if not t.last_result: + continue + metric_value = unflattened_lookup(metric, t.last_result, default=None) + if pd.isnull(metric_value): + continue + if not best_trial or metric_value * metric_op > best_metric: + best_metric = metric_value * metric_op + best_trial = t + return best_trial, metric + + +@DeveloperAPI +class RemoteReporterMixin: + """Remote reporter abstract mixin class. + + Subclasses of this class will use a Ray Queue to display output + on the driver side when running Ray Client.""" + + @property + def output_queue(self) -> Queue: + return getattr(self, "_output_queue", None) + + @output_queue.setter + def output_queue(self, value: Queue): + self._output_queue = value + + def display(self, string: str) -> None: + """Display the progress string. + + Args: + string: String to display. + """ + raise NotImplementedError + + +@PublicAPI +class JupyterNotebookReporter(TuneReporterBase, RemoteReporterMixin): + """Jupyter notebook-friendly Reporter that can update display in-place. + + Args: + overwrite: Flag for overwriting the cell contents before initialization. + metric_columns: Names of metrics to + include in progress table. If this is a dict, the keys should + be metric names and the values should be the displayed names. + If this is a list, the metric name is used directly. + parameter_columns: Names of parameters to + include in progress table. If this is a dict, the keys should + be parameter names and the values should be the displayed names. + If this is a list, the parameter name is used directly. If empty, + defaults to all available parameters. + max_progress_rows: Maximum number of rows to print + in the progress table. The progress table describes the + progress of each trial. Defaults to 20. + max_error_rows: Maximum number of rows to print in the + error table. The error table lists the error file, if any, + corresponding to each trial. Defaults to 20. + max_column_length: Maximum column length (in characters). Column + headers and values longer than this will be abbreviated. + max_report_frequency: Maximum report frequency in seconds. + Defaults to 5s. + infer_limit: Maximum number of metrics to automatically infer + from tune results. + print_intermediate_tables: Print intermediate result + tables. If None (default), will be set to True for verbosity + levels above 3, otherwise False. If True, intermediate tables + will be printed with experiment progress. If False, tables + will only be printed at then end of the tuning run for verbosity + levels greater than 2. + metric: Metric used to determine best current trial. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + + def __init__( + self, + *, + overwrite: bool = True, + metric_columns: Optional[Union[List[str], Dict[str, str]]] = None, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: Optional[int] = None, + max_progress_rows: int = 20, + max_error_rows: int = 20, + max_column_length: int = 20, + max_report_frequency: int = 5, + infer_limit: int = 3, + print_intermediate_tables: Optional[bool] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + ): + super(JupyterNotebookReporter, self).__init__( + metric_columns=metric_columns, + parameter_columns=parameter_columns, + total_samples=total_samples, + max_progress_rows=max_progress_rows, + max_error_rows=max_error_rows, + max_column_length=max_column_length, + max_report_frequency=max_report_frequency, + infer_limit=infer_limit, + print_intermediate_tables=print_intermediate_tables, + metric=metric, + mode=mode, + sort_by_metric=sort_by_metric, + ) + + if not IS_NOTEBOOK: + warnings.warn( + "You are using the `JupyterNotebookReporter`, but not " + "IPython/Jupyter-compatible environment was detected. " + "If this leads to unformatted output (e.g. like " + "), consider passing " + "a `CLIReporter` as the `progress_reporter` argument " + "to `tune.RunConfig()` instead." + ) + + self._overwrite = overwrite + self._display_handle = None + self.display("") # initialize empty display to update later + + def report(self, trials: List[Trial], done: bool, *sys_info: Dict): + progress = self._progress_html(trials, done, *sys_info) + + if self.output_queue is not None: + # If an output queue is set, send string + self.output_queue.put(progress) + else: + # Else, output directly + self.display(progress) + + def display(self, string: str) -> None: + from IPython.display import HTML, clear_output, display + + if not self._display_handle: + if self._overwrite: + clear_output(wait=True) + self._display_handle = display(HTML(string), display_id=True) + else: + self._display_handle.update(HTML(string)) + + def _progress_html(self, trials: List[Trial], done: bool, *sys_info) -> str: + """Generate an HTML-formatted progress update. + + Args: + trials: List of trials for which progress should be + displayed + done: True if the trials are finished, False otherwise + *sys_info: System information to be displayed + + Returns: + Progress update to be rendered in a notebook, including HTML + tables and formatted error messages. Includes + - Duration of the tune job + - Memory consumption + - Trial progress table, with information about each experiment + """ + if not self._metrics_override: + user_metrics = self._infer_user_metrics(trials, self._infer_limit) + self._metric_columns.update(user_metrics) + + current_time, running_for = _get_time_str(self._start_time, time.time()) + used_gb, total_gb, memory_message = _get_memory_usage() + + status_table = tabulate( + [ + ("Current time:", current_time), + ("Running for:", running_for), + ("Memory:", f"{used_gb}/{total_gb} GiB"), + ], + tablefmt="html", + ) + trial_progress_data = _trial_progress_table( + trials=trials, + metric_columns=self._metric_columns, + parameter_columns=self._parameter_columns, + fmt="html", + max_rows=None if done else self._max_progress_rows, + metric=self._metric, + mode=self._mode, + sort_by_metric=self._sort_by_metric, + max_column_length=self._max_column_length, + ) + + trial_progress = trial_progress_data[0] + trial_progress_messages = trial_progress_data[1:] + trial_errors = _trial_errors_str( + trials, fmt="html", max_rows=None if done else self._max_error_rows + ) + + if any([memory_message, trial_progress_messages, trial_errors]): + msg = Template("tune_status_messages.html.j2").render( + memory_message=memory_message, + trial_progress_messages=trial_progress_messages, + trial_errors=trial_errors, + ) + else: + msg = None + + return Template("tune_status.html.j2").render( + status_table=status_table, + sys_info_message=_generate_sys_info_str(*sys_info), + trial_progress=trial_progress, + messages=msg, + ) + + +@PublicAPI +class CLIReporter(TuneReporterBase): + """Command-line reporter + + Args: + metric_columns: Names of metrics to + include in progress table. If this is a dict, the keys should + be metric names and the values should be the displayed names. + If this is a list, the metric name is used directly. + parameter_columns: Names of parameters to + include in progress table. If this is a dict, the keys should + be parameter names and the values should be the displayed names. + If this is a list, the parameter name is used directly. If empty, + defaults to all available parameters. + max_progress_rows: Maximum number of rows to print + in the progress table. The progress table describes the + progress of each trial. Defaults to 20. + max_error_rows: Maximum number of rows to print in the + error table. The error table lists the error file, if any, + corresponding to each trial. Defaults to 20. + max_column_length: Maximum column length (in characters). Column + headers and values longer than this will be abbreviated. + max_report_frequency: Maximum report frequency in seconds. + Defaults to 5s. + infer_limit: Maximum number of metrics to automatically infer + from tune results. + print_intermediate_tables: Print intermediate result + tables. If None (default), will be set to True for verbosity + levels above 3, otherwise False. If True, intermediate tables + will be printed with experiment progress. If False, tables + will only be printed at then end of the tuning run for verbosity + levels greater than 2. + metric: Metric used to determine best current trial. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + + def __init__( + self, + *, + metric_columns: Optional[Union[List[str], Dict[str, str]]] = None, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: Optional[int] = None, + max_progress_rows: int = 20, + max_error_rows: int = 20, + max_column_length: int = 20, + max_report_frequency: int = 5, + infer_limit: int = 3, + print_intermediate_tables: Optional[bool] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + ): + super(CLIReporter, self).__init__( + metric_columns=metric_columns, + parameter_columns=parameter_columns, + total_samples=total_samples, + max_progress_rows=max_progress_rows, + max_error_rows=max_error_rows, + max_column_length=max_column_length, + max_report_frequency=max_report_frequency, + infer_limit=infer_limit, + print_intermediate_tables=print_intermediate_tables, + metric=metric, + mode=mode, + sort_by_metric=sort_by_metric, + ) + + def _print(self, msg: str): + safe_print(msg) + + def report(self, trials: List[Trial], done: bool, *sys_info: Dict): + self._print(self._progress_str(trials, done, *sys_info)) + + +def _get_memory_usage() -> Tuple[float, float, Optional[str]]: + """Get the current memory consumption. + + Returns: + Memory used, memory available, and optionally a warning + message to be shown to the user when memory consumption is higher + than 90% or if `psutil` is not installed + """ + try: + import ray # noqa F401 + + import psutil + + total_gb = psutil.virtual_memory().total / (1024**3) + used_gb = total_gb - psutil.virtual_memory().available / (1024**3) + if used_gb > total_gb * 0.9: + message = ( + ": ***LOW MEMORY*** less than 10% of the memory on " + "this node is available for use. This can cause " + "unexpected crashes. Consider " + "reducing the memory used by your application " + "or reducing the Ray object store size by setting " + "`object_store_memory` when calling `ray.init`." + ) + else: + message = None + + return round(used_gb, 1), round(total_gb, 1), message + except ImportError: + return ( + np.nan, + np.nan, + "Unknown memory usage. Please run `pip install psutil` to resolve", + ) + + +def _get_time_str(start_time: float, current_time: float) -> Tuple[str, str]: + """Get strings representing the current and elapsed time. + + Args: + start_time: POSIX timestamp of the start of the tune run + current_time: POSIX timestamp giving the current time + + Returns: + Current time and elapsed time for the current run + """ + current_time_dt = datetime.datetime.fromtimestamp(current_time) + start_time_dt = datetime.datetime.fromtimestamp(start_time) + delta: datetime.timedelta = current_time_dt - start_time_dt + + rest = delta.total_seconds() + days = rest // (60 * 60 * 24) + + rest -= days * (60 * 60 * 24) + hours = rest // (60 * 60) + + rest -= hours * (60 * 60) + minutes = rest // 60 + + seconds = rest - minutes * 60 + + if days > 0: + running_for_str = f"{days:.0f} days, " + else: + running_for_str = "" + + running_for_str += f"{hours:02.0f}:{minutes:02.0f}:{seconds:05.2f}" + + return f"{current_time_dt:%Y-%m-%d %H:%M:%S}", running_for_str + + +def _time_passed_str(start_time: float, current_time: float) -> str: + """Generate a message describing the current and elapsed time in the run. + + Args: + start_time: POSIX timestamp of the start of the tune run + current_time: POSIX timestamp giving the current time + + Returns: + Message with the current and elapsed time for the current tune run, + formatted to be displayed to the user + """ + current_time_str, running_for_str = _get_time_str(start_time, current_time) + return f"Current time: {current_time_str} " f"(running for {running_for_str})" + + +def _get_trials_by_state(trials: List[Trial]): + trials_by_state = collections.defaultdict(list) + for t in trials: + trials_by_state[t.status].append(t) + return trials_by_state + + +def _trial_progress_str( + trials: List[Trial], + metric_columns: Union[List[str], Dict[str, str]], + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + total_samples: int = 0, + force_table: bool = False, + fmt: str = "psql", + max_rows: Optional[int] = None, + max_column_length: int = 20, + done: bool = False, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, +): + """Returns a human readable message for printing to the console. + + This contains a table where each row represents a trial, its parameters + and the current values of its metrics. + + Args: + trials: List of trials to get progress string for. + metric_columns: Names of metrics to include. + If this is a dict, the keys are metric names and the values are + the names to use in the message. If this is a list, the metric + name is used in the message directly. + parameter_columns: Names of parameters to + include. If this is a dict, the keys are parameter names and the + values are the names to use in the message. If this is a list, + the parameter name is used in the message directly. If this is + empty, all parameters are used in the message. + total_samples: Total number of trials that will be generated. + force_table: Force printing a table. If False, a table will + be printed only at the end of the training for verbosity levels + above `Verbosity.V2_TRIAL_NORM`. + fmt: Output format (see tablefmt in tabulate API). + max_rows: Maximum number of rows in the trial table. Defaults to + unlimited. + max_column_length: Maximum column length (in characters). + done: True indicates that the tuning run finished. + metric: Metric used to sort trials. + mode: One of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. + sort_by_metric: Sort terminated trials by metric in the + intermediate table. Defaults to False. + """ + messages = [] + delim = "
    " if fmt == "html" else "\n" + if len(trials) < 1: + return delim.join(messages) + + num_trials = len(trials) + trials_by_state = _get_trials_by_state(trials) + + for local_dir in sorted({t.local_experiment_path for t in trials}): + messages.append("Result logdir: {}".format(local_dir)) + + num_trials_strs = [ + "{} {}".format(len(trials_by_state[state]), state) + for state in sorted(trials_by_state) + ] + + if total_samples and total_samples >= sys.maxsize: + total_samples = "infinite" + + messages.append( + "Number of trials: {}{} ({})".format( + num_trials, + f"/{total_samples}" if total_samples else "", + ", ".join(num_trials_strs), + ) + ) + + if force_table or (has_verbosity(Verbosity.V2_TRIAL_NORM) and done): + messages += _trial_progress_table( + trials=trials, + metric_columns=metric_columns, + parameter_columns=parameter_columns, + fmt=fmt, + max_rows=max_rows, + metric=metric, + mode=mode, + sort_by_metric=sort_by_metric, + max_column_length=max_column_length, + ) + + return delim.join(messages) + + +def _max_len( + value: Any, max_len: int = 20, add_addr: bool = False, wrap: bool = False +) -> Any: + """Abbreviate a string representation of an object to `max_len` characters. + + For numbers, booleans and None, the original value will be returned for + correct rendering in the table formatting tool. + + Args: + value: Object to be represented as a string. + max_len: Maximum return string length. + add_addr: If True, will add part of the object address to the end of the + string, e.g. to identify different instances of the same class. If + False, three dots (``...``) will be used instead. + """ + if value is None or isinstance(value, (int, float, numbers.Number, bool)): + return value + + string = str(value) + if len(string) <= max_len: + return string + + if wrap: + # Maximum two rows. + # Todo: Make this configurable in the refactor + if len(value) > max_len * 2: + value = "..." + string[(3 - (max_len * 2)) :] + + wrapped = textwrap.wrap(value, width=max_len) + return "\n".join(wrapped) + + if add_addr and not isinstance(value, (int, float, bool)): + result = f"{string[: (max_len - 5)]}_{hex(id(value))[-4:]}" + return result + + result = "..." + string[(3 - max_len) :] + return result + + +def _get_progress_table_data( + trials: List[Trial], + metric_columns: Union[List[str], Dict[str, str]], + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + max_rows: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + max_column_length: int = 20, +) -> Tuple[List, List[str], Tuple[bool, str]]: + """Generate a table showing the current progress of tuning trials. + + Args: + trials: List of trials for which progress is to be shown. + metric_columns: Metrics to be displayed in the table. + parameter_columns: List of parameters to be included in the data + max_rows: Maximum number of rows to show. If there's overflow, a + message will be shown to the user indicating that some rows + are not displayed + metric: Metric which is being tuned + mode: Sort the table in descending order if mode is "max"; + ascending otherwise + sort_by_metric: If true, the table will be sorted by the metric + max_column_length: Max number of characters in each column + + Returns: + - Trial data + - List of column names + - Overflow tuple: + - boolean indicating whether the table has rows which are hidden + - string with info about the overflowing rows + """ + num_trials = len(trials) + trials_by_state = _get_trials_by_state(trials) + + # Sort terminated trials by metric and mode, descending if mode is "max" + if sort_by_metric: + trials_by_state[Trial.TERMINATED] = sorted( + trials_by_state[Trial.TERMINATED], + reverse=(mode == "max"), + key=lambda t: unflattened_lookup(metric, t.last_result, default=None), + ) + + state_tbl_order = [ + Trial.RUNNING, + Trial.PAUSED, + Trial.PENDING, + Trial.TERMINATED, + Trial.ERROR, + ] + max_rows = max_rows or float("inf") + if num_trials > max_rows: + # TODO(ujvl): suggestion for users to view more rows. + trials_by_state_trunc = _fair_filter_trials( + trials_by_state, max_rows, sort_by_metric + ) + trials = [] + overflow_strs = [] + for state in state_tbl_order: + if state not in trials_by_state: + continue + trials += trials_by_state_trunc[state] + num = len(trials_by_state[state]) - len(trials_by_state_trunc[state]) + if num > 0: + overflow_strs.append("{} {}".format(num, state)) + # Build overflow string. + overflow = num_trials - max_rows + overflow_str = ", ".join(overflow_strs) + else: + overflow = False + overflow_str = "" + trials = [] + for state in state_tbl_order: + if state not in trials_by_state: + continue + trials += trials_by_state[state] + + # Pre-process trials to figure out what columns to show. + if isinstance(metric_columns, Mapping): + metric_keys = list(metric_columns.keys()) + else: + metric_keys = metric_columns + + metric_keys = [ + k + for k in metric_keys + if any( + unflattened_lookup(k, t.last_result, default=None) is not None + for t in trials + ) + ] + + if not parameter_columns: + parameter_keys = sorted(set().union(*[t.evaluated_params for t in trials])) + elif isinstance(parameter_columns, Mapping): + parameter_keys = list(parameter_columns.keys()) + else: + parameter_keys = parameter_columns + + # Build trial rows. + trial_table = [ + _get_trial_info( + trial, parameter_keys, metric_keys, max_column_length=max_column_length + ) + for trial in trials + ] + # Format column headings + if isinstance(metric_columns, Mapping): + formatted_metric_columns = [ + _max_len( + metric_columns[k], max_len=max_column_length, add_addr=False, wrap=True + ) + for k in metric_keys + ] + else: + formatted_metric_columns = [ + _max_len(k, max_len=max_column_length, add_addr=False, wrap=True) + for k in metric_keys + ] + if isinstance(parameter_columns, Mapping): + formatted_parameter_columns = [ + _max_len( + parameter_columns[k], + max_len=max_column_length, + add_addr=False, + wrap=True, + ) + for k in parameter_keys + ] + else: + formatted_parameter_columns = [ + _max_len(k, max_len=max_column_length, add_addr=False, wrap=True) + for k in parameter_keys + ] + columns = ( + ["Trial name", "status", "loc"] + + formatted_parameter_columns + + formatted_metric_columns + ) + + return trial_table, columns, (overflow, overflow_str) + + +def _trial_progress_table( + trials: List[Trial], + metric_columns: Union[List[str], Dict[str, str]], + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, + fmt: str = "psql", + max_rows: Optional[int] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + sort_by_metric: bool = False, + max_column_length: int = 20, +) -> List[str]: + """Generate a list of trial progress table messages. + + Args: + trials: List of trials for which progress is to be shown. + metric_columns: Metrics to be displayed in the table. + parameter_columns: List of parameters to be included in the data + fmt: Format of the table; passed to tabulate as the fmtstr argument + max_rows: Maximum number of rows to show. If there's overflow, a + message will be shown to the user indicating that some rows + are not displayed + metric: Metric which is being tuned + mode: Sort the table in descenting order if mode is "max"; + ascending otherwise + sort_by_metric: If true, the table will be sorted by the metric + max_column_length: Max number of characters in each column + + Returns: + Messages to be shown to the user containing progress tables + """ + data, columns, (overflow, overflow_str) = _get_progress_table_data( + trials, + metric_columns, + parameter_columns, + max_rows, + metric, + mode, + sort_by_metric, + max_column_length, + ) + messages = [tabulate(data, headers=columns, tablefmt=fmt, showindex=False)] + if overflow: + messages.append(f"... {overflow} more trials not shown ({overflow_str})") + return messages + + +def _generate_sys_info_str(*sys_info) -> str: + """Format system info into a string. + *sys_info: System info strings to be included. + + Returns: + Formatted string containing system information. + """ + if sys_info: + return "
    ".join(sys_info).replace("\n", "
    ") + return "" + + +def _trial_errors_str( + trials: List[Trial], fmt: str = "psql", max_rows: Optional[int] = None +): + """Returns a readable message regarding trial errors. + + Args: + trials: List of trials to get progress string for. + fmt: Output format (see tablefmt in tabulate API). + max_rows: Maximum number of rows in the error table. Defaults to + unlimited. + """ + messages = [] + failed = [t for t in trials if t.error_file] + num_failed = len(failed) + if num_failed > 0: + messages.append("Number of errored trials: {}".format(num_failed)) + if num_failed > (max_rows or float("inf")): + messages.append( + "Table truncated to {} rows ({} overflow)".format( + max_rows, num_failed - max_rows + ) + ) + + fail_header = ["Trial name", "# failures", "error file"] + fail_table_data = [ + [ + str(trial), + str(trial.run_metadata.num_failures) + + ("" if trial.status == Trial.ERROR else "*"), + trial.error_file, + ] + for trial in failed[:max_rows] + ] + messages.append( + tabulate( + fail_table_data, + headers=fail_header, + tablefmt=fmt, + showindex=False, + colalign=("left", "right", "left"), + ) + ) + if any(trial.status == Trial.TERMINATED for trial in failed[:max_rows]): + messages.append("* The trial terminated successfully after retrying.") + + delim = "
    " if fmt == "html" else "\n" + return delim.join(messages) + + +def _best_trial_str( + trial: Trial, + metric: str, + parameter_columns: Optional[Union[List[str], Dict[str, str]]] = None, +): + """Returns a readable message stating the current best trial.""" + val = unflattened_lookup(metric, trial.last_result, default=None) + config = trial.last_result.get("config", {}) + parameter_columns = parameter_columns or list(config.keys()) + if isinstance(parameter_columns, Mapping): + parameter_columns = parameter_columns.keys() + params = {p: unflattened_lookup(p, config) for p in parameter_columns} + return ( + f"Current best trial: {trial.trial_id} with {metric}={val} and " + f"parameters={params}" + ) + + +def _fair_filter_trials( + trials_by_state: Dict[str, List[Trial]], + max_trials: int, + sort_by_metric: bool = False, +): + """Filters trials such that each state is represented fairly. + + The oldest trials are truncated if necessary. + + Args: + trials_by_state: Maximum number of trials to return. + Returns: + Dict mapping state to List of fairly represented trials. + """ + num_trials_by_state = collections.defaultdict(int) + no_change = False + # Determine number of trials to keep per state. + while max_trials > 0 and not no_change: + no_change = True + for state in sorted(trials_by_state): + if num_trials_by_state[state] < len(trials_by_state[state]): + no_change = False + max_trials -= 1 + num_trials_by_state[state] += 1 + # Sort by start time, descending if the trails is not sorted by metric. + sorted_trials_by_state = dict() + for state in sorted(trials_by_state): + if state == Trial.TERMINATED and sort_by_metric: + sorted_trials_by_state[state] = trials_by_state[state] + else: + sorted_trials_by_state[state] = sorted( + trials_by_state[state], reverse=False, key=lambda t: t.trial_id + ) + # Truncate oldest trials. + filtered_trials = { + state: sorted_trials_by_state[state][: num_trials_by_state[state]] + for state in sorted(trials_by_state) + } + return filtered_trials + + +def _get_trial_location(trial: Trial, result: dict) -> _Location: + # we get the location from the result, as the one in trial will be + # reset when trial terminates + node_ip, pid = result.get(NODE_IP, None), result.get(PID, None) + if node_ip and pid: + location = _Location(node_ip, pid) + else: + # fallback to trial location if there hasn't been a report yet + location = trial.temporary_state.location + return location + + +def _get_trial_info( + trial: Trial, parameters: List[str], metrics: List[str], max_column_length: int = 20 +): + """Returns the following information about a trial: + + name | status | loc | params... | metrics... + + Args: + trial: Trial to get information for. + parameters: Names of trial parameters to include. + metrics: Names of metrics to include. + max_column_length: Maximum column length (in characters). + """ + result = trial.last_result + config = trial.config + location = _get_trial_location(trial, result) + trial_info = [str(trial), trial.status, str(location)] + trial_info += [ + _max_len( + unflattened_lookup(param, config, default=None), + max_len=max_column_length, + add_addr=True, + ) + for param in parameters + ] + trial_info += [ + _max_len( + unflattened_lookup(metric, result, default=None), + max_len=max_column_length, + add_addr=True, + ) + for metric in metrics + ] + return trial_info + + +@DeveloperAPI +class TrialProgressCallback(Callback): + """Reports (prints) intermediate trial progress. + + This callback is automatically added to the callback stack. When a + result is obtained, this callback will print the results according to + the specified verbosity level. + + For ``Verbosity.V3_TRIAL_DETAILS``, a full result list is printed. + + For ``Verbosity.V2_TRIAL_NORM``, only one line is printed per received + result. + + All other verbosity levels do not print intermediate trial progress. + + Result printing is throttled on a per-trial basis. Per default, results are + printed only once every 30 seconds. Results are always printed when a trial + finished or errored. + + """ + + def __init__( + self, metric: Optional[str] = None, progress_metrics: Optional[List[str]] = None + ): + self._last_print = collections.defaultdict(float) + self._last_print_iteration = collections.defaultdict(int) + self._completed_trials = set() + self._last_result_str = {} + self._metric = metric + self._progress_metrics = set(progress_metrics or []) + + # Only use progress metrics if at least two metrics are in there + if self._metric and self._progress_metrics: + self._progress_metrics.add(self._metric) + self._last_result = {} + self._display_handle = None + + def _print(self, msg: str): + safe_print(msg) + + def on_trial_result( + self, + iteration: int, + trials: List["Trial"], + trial: "Trial", + result: Dict, + **info, + ): + self.log_result(trial, result, error=False) + + def on_trial_error( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + self.log_result(trial, trial.last_result, error=True) + + def on_trial_complete( + self, iteration: int, trials: List["Trial"], trial: "Trial", **info + ): + # Only log when we never logged that a trial was completed + if trial not in self._completed_trials: + self._completed_trials.add(trial) + + print_result_str = self._print_result(trial.last_result) + last_result_str = self._last_result_str.get(trial, "") + # If this is a new result, print full result string + if print_result_str != last_result_str: + self.log_result(trial, trial.last_result, error=False) + else: + self._print(f"Trial {trial} completed. Last result: {print_result_str}") + + def log_result(self, trial: "Trial", result: Dict, error: bool = False): + done = result.get("done", False) is True + last_print = self._last_print[trial] + should_print = done or error or time.time() - last_print > DEBUG_PRINT_INTERVAL + + if done and trial not in self._completed_trials: + self._completed_trials.add(trial) + + if should_print: + if IS_NOTEBOOK: + self.display_result(trial, result, error, done) + else: + self.print_result(trial, result, error, done) + + self._last_print[trial] = time.time() + if TRAINING_ITERATION in result: + self._last_print_iteration[trial] = result[TRAINING_ITERATION] + + def print_result(self, trial: Trial, result: Dict, error: bool, done: bool): + """Print the most recent results for the given trial to stdout. + + Args: + trial: Trial for which results are to be printed + result: Result to be printed + error: True if an error has occurred, False otherwise + done: True if the trial is finished, False otherwise + """ + last_print_iteration = self._last_print_iteration[trial] + + if has_verbosity(Verbosity.V3_TRIAL_DETAILS): + if result.get(TRAINING_ITERATION) != last_print_iteration: + self._print(f"Result for {trial}:") + self._print(" {}".format(pretty_print(result).replace("\n", "\n "))) + if done: + self._print(f"Trial {trial} completed.") + + elif has_verbosity(Verbosity.V2_TRIAL_NORM): + metric_name = self._metric or "_metric" + metric_value = result.get(metric_name, -99.0) + error_file = Path(trial.local_path, EXPR_ERROR_FILE).as_posix() + + info = "" + if done: + info = " This trial completed." + + print_result_str = self._print_result(result) + + self._last_result_str[trial] = print_result_str + + if error: + message = ( + f"The trial {trial} errored with " + f"parameters={trial.config}. " + f"Error file: {error_file}" + ) + elif self._metric: + message = ( + f"Trial {trial} reported " + f"{metric_name}={metric_value:.2f} " + f"with parameters={trial.config}.{info}" + ) + else: + message = ( + f"Trial {trial} reported " + f"{print_result_str} " + f"with parameters={trial.config}.{info}" + ) + + self._print(message) + + def generate_trial_table( + self, trials: Dict[Trial, Dict], columns: List[str] + ) -> str: + """Generate an HTML table of trial progress info. + + Trials (rows) are sorted by name; progress stats (columns) are sorted + as well. + + Args: + trials: Trials and their associated latest results + columns: Columns to show in the table; must be a list of valid + keys for each Trial result + + Returns: + HTML template containing a rendered table of progress info + """ + data = [] + columns = sorted(columns) + + sorted_trials = collections.OrderedDict( + sorted(self._last_result.items(), key=lambda item: str(item[0])) + ) + for trial, result in sorted_trials.items(): + data.append([str(trial)] + [result.get(col, "") for col in columns]) + + return Template("trial_progress.html.j2").render( + table=tabulate( + data, tablefmt="html", headers=["Trial name"] + columns, showindex=False + ) + ) + + def display_result(self, trial: Trial, result: Dict, error: bool, done: bool): + """Display a formatted HTML table of trial progress results. + + Trial progress is only shown if verbosity is set to level 2 or 3. + + Args: + trial: Trial for which results are to be printed + result: Result to be printed + error: True if an error has occurred, False otherwise + done: True if the trial is finished, False otherwise + """ + from IPython.display import HTML, display + + self._last_result[trial] = result + if has_verbosity(Verbosity.V3_TRIAL_DETAILS): + ignored_keys = { + "config", + "hist_stats", + } + + elif has_verbosity(Verbosity.V2_TRIAL_NORM): + ignored_keys = { + "config", + "hist_stats", + "trial_id", + "experiment_tag", + "done", + } | set(AUTO_RESULT_KEYS) + else: + return + + table = self.generate_trial_table( + self._last_result, set(result.keys()) - ignored_keys + ) + if not self._display_handle: + self._display_handle = display(HTML(table), display_id=True) + else: + self._display_handle.update(HTML(table)) + + def _print_result(self, result: Dict): + if self._progress_metrics: + # If progress metrics are given, only report these + flat_result = flatten_dict(result) + + print_result = {} + for metric in self._progress_metrics: + print_result[metric] = flat_result.get(metric) + + else: + # Else, skip auto populated results + print_result = result.copy() + + for skip_result in SKIP_RESULTS_IN_REPORT: + print_result.pop(skip_result, None) + + for auto_result in AUTO_RESULT_KEYS: + print_result.pop(auto_result, None) + + print_result_str = ",".join( + [f"{k}={v}" for k, v in print_result.items() if v is not None] + ) + return print_result_str + + +def _detect_reporter(_trainer_api: bool = False, **kwargs) -> TuneReporterBase: + """Detect progress reporter class. + + Will return a :class:`JupyterNotebookReporter` if a IPython/Jupyter-like + session was detected, and a :class:`CLIReporter` otherwise. + + Keyword arguments are passed on to the reporter class. + """ + if IS_NOTEBOOK and not _trainer_api: + kwargs.setdefault("overwrite", not has_verbosity(Verbosity.V2_TRIAL_NORM)) + progress_reporter = JupyterNotebookReporter(**kwargs) + else: + progress_reporter = CLIReporter(**kwargs) + return progress_reporter + + +def _detect_progress_metrics( + trainable: Optional[Union["Trainable", Callable]] +) -> Optional[Collection[str]]: + """Detect progress metrics to report.""" + if not trainable: + return None + + return getattr(trainable, "_progress_metrics", None) + + +def _prepare_progress_reporter_for_ray_client( + progress_reporter: ProgressReporter, + verbosity: Union[int, Verbosity], + string_queue: Optional[Queue] = None, +) -> Tuple[ProgressReporter, Queue]: + """Prepares progress reported for Ray Client by setting the string queue. + + The string queue will be created if it's None.""" + set_verbosity(verbosity) + progress_reporter = progress_reporter or _detect_reporter() + + # JupyterNotebooks don't work with remote tune runs out of the box + # (e.g. via Ray client) as they don't have access to the main + # process stdout. So we introduce a queue here that accepts + # strings, which will then be displayed on the driver side. + if isinstance(progress_reporter, RemoteReporterMixin): + if string_queue is None: + string_queue = Queue( + actor_options={"num_cpus": 0, **_force_on_current_node(None)} + ) + progress_reporter.output_queue = string_queue + + return progress_reporter, string_queue + + +def _stream_client_output( + remote_future: ray.ObjectRef, + progress_reporter: ProgressReporter, + string_queue: Queue, +) -> Any: + """ + Stream items from string queue to progress_reporter until remote_future resolves + """ + if string_queue is None: + return + + def get_next_queue_item(): + try: + return string_queue.get(block=False) + except Empty: + return None + + def _handle_string_queue(): + string_item = get_next_queue_item() + while string_item is not None: + # This happens on the driver side + progress_reporter.display(string_item) + string_item = get_next_queue_item() + + # ray.wait(...)[1] returns futures that are not ready, yet + while ray.wait([remote_future], timeout=0.2)[1]: + # Check if we have items to execute + _handle_string_queue() + + # Handle queue one last time + _handle_string_queue() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/registry.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..b713e2902151ee50dee5b2fc5358a5695a43e839 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/registry.py @@ -0,0 +1,319 @@ +import atexit +import logging +from functools import partial +from types import FunctionType +from typing import Callable, Optional, Type, Union + +import ray +import ray.cloudpickle as pickle +from ray.experimental.internal_kv import ( + _internal_kv_del, + _internal_kv_get, + _internal_kv_initialized, + _internal_kv_put, +) +from ray.tune.error import TuneError +from ray.util.annotations import DeveloperAPI + +TRAINABLE_CLASS = "trainable_class" +ENV_CREATOR = "env_creator" +RLLIB_MODEL = "rllib_model" +RLLIB_PREPROCESSOR = "rllib_preprocessor" +RLLIB_ACTION_DIST = "rllib_action_dist" +RLLIB_INPUT = "rllib_input" +RLLIB_CONNECTOR = "rllib_connector" +TEST = "__test__" +KNOWN_CATEGORIES = [ + TRAINABLE_CLASS, + ENV_CREATOR, + RLLIB_MODEL, + RLLIB_PREPROCESSOR, + RLLIB_ACTION_DIST, + RLLIB_INPUT, + RLLIB_CONNECTOR, + TEST, +] + +logger = logging.getLogger(__name__) + + +def _has_trainable(trainable_name): + return _global_registry.contains(TRAINABLE_CLASS, trainable_name) + + +@DeveloperAPI +def get_trainable_cls(trainable_name): + validate_trainable(trainable_name) + return _global_registry.get(TRAINABLE_CLASS, trainable_name) + + +@DeveloperAPI +def validate_trainable(trainable_name: str): + if not _has_trainable(trainable_name) and not _has_rllib_trainable(trainable_name): + raise TuneError(f"Unknown trainable: {trainable_name}") + + +def _has_rllib_trainable(trainable_name: str) -> bool: + try: + # Make sure everything rllib-related is registered. + from ray.rllib import _register_all + except (ImportError, ModuleNotFoundError): + return False + + _register_all() + return _has_trainable(trainable_name) + + +@DeveloperAPI +def is_function_trainable(trainable: Union[str, Callable, Type]) -> bool: + """Check if a given trainable is a function trainable. + Either the trainable has been wrapped as a FunctionTrainable class already, + or it's still a FunctionType/partial/callable.""" + from ray.tune.trainable import FunctionTrainable + + if isinstance(trainable, str): + trainable = get_trainable_cls(trainable) + + is_wrapped_func = isinstance(trainable, type) and issubclass( + trainable, FunctionTrainable + ) + return is_wrapped_func or ( + not isinstance(trainable, type) + and ( + isinstance(trainable, FunctionType) + or isinstance(trainable, partial) + or callable(trainable) + ) + ) + + +@DeveloperAPI +def register_trainable(name: str, trainable: Union[Callable, Type], warn: bool = True): + """Register a trainable function or class. + + This enables a class or function to be accessed on every Ray process + in the cluster. + + Args: + name: Name to register. + trainable: Function or tune.Trainable class. Functions must + take (config, status_reporter) as arguments and will be + automatically converted into a class during registration. + """ + + from ray.tune.trainable import Trainable, wrap_function + + if isinstance(trainable, type): + logger.debug("Detected class for trainable.") + elif isinstance(trainable, FunctionType) or isinstance(trainable, partial): + logger.debug("Detected function for trainable.") + trainable = wrap_function(trainable) + elif callable(trainable): + logger.info("Detected unknown callable for trainable. Converting to class.") + trainable = wrap_function(trainable) + + if not issubclass(trainable, Trainable): + raise TypeError("Second argument must be convertable to Trainable", trainable) + _global_registry.register(TRAINABLE_CLASS, name, trainable) + + +def _unregister_trainables(): + _global_registry.unregister_all(TRAINABLE_CLASS) + + +@DeveloperAPI +def register_env(name: str, env_creator: Callable): + """Register a custom environment for use with RLlib. + + This enables the environment to be accessed on every Ray process + in the cluster. + + Args: + name: Name to register. + env_creator: Callable that creates an env. + """ + + if not callable(env_creator): + raise TypeError("Second argument must be callable.", env_creator) + _global_registry.register(ENV_CREATOR, name, env_creator) + + +def _unregister_envs(): + _global_registry.unregister_all(ENV_CREATOR) + + +@DeveloperAPI +def register_input(name: str, input_creator: Callable): + """Register a custom input api for RLlib. + + Args: + name: Name to register. + input_creator: Callable that creates an + input reader. + """ + if not callable(input_creator): + raise TypeError("Second argument must be callable.", input_creator) + _global_registry.register(RLLIB_INPUT, name, input_creator) + + +def _unregister_inputs(): + _global_registry.unregister_all(RLLIB_INPUT) + + +@DeveloperAPI +def registry_contains_input(name: str) -> bool: + return _global_registry.contains(RLLIB_INPUT, name) + + +@DeveloperAPI +def registry_get_input(name: str) -> Callable: + return _global_registry.get(RLLIB_INPUT, name) + + +def _unregister_all(): + _unregister_inputs() + _unregister_envs() + _unregister_trainables() + + +def _check_serializability(key, value): + _global_registry.register(TEST, key, value) + + +def _make_key(prefix: str, category: str, key: str): + """Generate a binary key for the given category and key. + + Args: + prefix: Prefix + category: The category of the item + key: The unique identifier for the item + + Returns: + The key to use for storing a the value. + """ + return ( + b"TuneRegistry:" + + prefix.encode("ascii") + + b":" + + category.encode("ascii") + + b"/" + + key.encode("ascii") + ) + + +class _Registry: + def __init__(self, prefix: Optional[str] = None): + """If no prefix is given, use runtime context job ID.""" + self._to_flush = {} + self._prefix = prefix + self._registered = set() + self._atexit_handler_registered = False + + @property + def prefix(self): + if not self._prefix: + self._prefix = ray.get_runtime_context().get_job_id() + return self._prefix + + def _register_atexit(self): + if self._atexit_handler_registered: + # Already registered + return + + if ray._private.worker.global_worker.mode != ray.SCRIPT_MODE: + # Only cleanup on the driver + return + + atexit.register(_unregister_all) + self._atexit_handler_registered = True + + def register(self, category, key, value): + """Registers the value with the global registry. + + Args: + category: The category to register under. + key: The key to register under. + value: The value to register. + + Raises: + PicklingError: If unable to pickle to provided file. + """ + if category not in KNOWN_CATEGORIES: + from ray.tune import TuneError + + raise TuneError( + "Unknown category {} not among {}".format(category, KNOWN_CATEGORIES) + ) + self._to_flush[(category, key)] = pickle.dumps_debug(value) + if _internal_kv_initialized(): + self.flush_values() + + def unregister(self, category, key): + if _internal_kv_initialized(): + _internal_kv_del(_make_key(self.prefix, category, key)) + else: + self._to_flush.pop((category, key), None) + + def unregister_all(self, category: Optional[str] = None): + remaining = set() + for cat, key in self._registered: + if category and category == cat: + self.unregister(cat, key) + else: + remaining.add((cat, key)) + self._registered = remaining + + def contains(self, category, key): + if _internal_kv_initialized(): + value = _internal_kv_get(_make_key(self.prefix, category, key)) + return value is not None + else: + return (category, key) in self._to_flush + + def get(self, category, key): + if _internal_kv_initialized(): + value = _internal_kv_get(_make_key(self.prefix, category, key)) + if value is None: + raise ValueError( + "Registry value for {}/{} doesn't exist.".format(category, key) + ) + return pickle.loads(value) + else: + return pickle.loads(self._to_flush[(category, key)]) + + def flush_values(self): + self._register_atexit() + for (category, key), value in self._to_flush.items(): + _internal_kv_put( + _make_key(self.prefix, category, key), value, overwrite=True + ) + self._registered.add((category, key)) + self._to_flush.clear() + + +_global_registry = _Registry() +ray._private.worker._post_init_hooks.append(_global_registry.flush_values) + + +class _ParameterRegistry: + def __init__(self): + self.to_flush = {} + self.references = {} + + def put(self, k, v): + self.to_flush[k] = v + if ray.is_initialized(): + self.flush() + + def get(self, k): + if not ray.is_initialized(): + return self.to_flush[k] + return ray.get(self.references[k]) + + def flush(self): + for k, v in self.to_flush.items(): + if isinstance(v, ray.ObjectRef): + self.references[k] = v + else: + self.references[k] = ray.put(v) + self.to_flush.clear() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/resources.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/resources.py new file mode 100644 index 0000000000000000000000000000000000000000..6c6113ceac03b8d554c8cdca962ddf23ec487c10 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/resources.py @@ -0,0 +1,92 @@ +import json +import logging +from collections import namedtuple + +# For compatibility under py2 to consider unicode as str +from typing import Optional + +from ray.tune.error import TuneError +from ray.tune.execution.placement_groups import ( + PlacementGroupFactory, + resource_dict_to_pg_factory, +) +from ray.tune.utils.resource_updater import _Resources +from ray.util.annotations import Deprecated, DeveloperAPI + +logger = logging.getLogger(__name__) + + +@Deprecated +class Resources( + namedtuple( + "Resources", + [ + "cpu", + "gpu", + "memory", + "object_store_memory", + "extra_cpu", + "extra_gpu", + "extra_memory", + "extra_object_store_memory", + "custom_resources", + "extra_custom_resources", + "has_placement_group", + ], + ) +): + __slots__ = () + + def __new__( + cls, + cpu: float, + gpu: float, + memory: float = 0, + object_store_memory: float = 0.0, + extra_cpu: float = 0.0, + extra_gpu: float = 0.0, + extra_memory: float = 0.0, + extra_object_store_memory: float = 0.0, + custom_resources: Optional[dict] = None, + extra_custom_resources: Optional[dict] = None, + has_placement_group: bool = False, + ): + raise DeprecationWarning( + "tune.Resources is depracted. Use tune.PlacementGroupFactory instead." + ) + + +@DeveloperAPI +def json_to_resources(data: Optional[str]) -> Optional[PlacementGroupFactory]: + if data is None or data == "null": + return None + if isinstance(data, str): + data = json.loads(data) + + for k in data: + if k in ["driver_cpu_limit", "driver_gpu_limit"]: + raise TuneError( + "The field `{}` is no longer supported. Use `extra_cpu` " + "or `extra_gpu` instead.".format(k) + ) + if k not in _Resources._fields: + raise ValueError( + "Unknown resource field {}, must be one of {}".format( + k, Resources._fields + ) + ) + resource_dict_to_pg_factory( + dict( + cpu=data.get("cpu", 1), + gpu=data.get("gpu", 0), + memory=data.get("memory", 0), + custom_resources=data.get("custom_resources"), + ) + ) + + +@Deprecated +def resources_to_json(*args, **kwargs): + raise DeprecationWarning( + "tune.Resources is depracted. Use tune.PlacementGroupFactory instead." + ) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/result.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/result.py new file mode 100644 index 0000000000000000000000000000000000000000..b4e966386a12743df99f3bb9aa243a07ce8b1409 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/result.py @@ -0,0 +1,133 @@ +# Importing for Backward Compatibility +from ray.air.constants import ( # noqa: F401 + EXPR_ERROR_FILE, + EXPR_ERROR_PICKLE_FILE, + EXPR_PARAM_FILE, + EXPR_PARAM_PICKLE_FILE, + EXPR_PROGRESS_FILE, + EXPR_RESULT_FILE, + TIME_THIS_ITER_S, + TIMESTAMP, + TRAINING_ITERATION, +) + +# fmt: off +# __sphinx_doc_begin__ +# (Optional/Auto-filled) training is terminated. Filled only if not provided. +DONE = "done" + +# (Optional) Enum for user controlled checkpoint +SHOULD_CHECKPOINT = "should_checkpoint" + +# (Auto-filled) The hostname of the machine hosting the training process. +HOSTNAME = "hostname" + +# (Auto-filled) The auto-assigned id of the trial. +TRIAL_ID = "trial_id" + +# (Auto-filled) The auto-assigned id of the trial. +EXPERIMENT_TAG = "experiment_tag" + +# (Auto-filled) The node ip of the machine hosting the training process. +NODE_IP = "node_ip" + +# (Auto-filled) The pid of the training process. +PID = "pid" + +# (Optional) Default (anonymous) metric when using tune.report(x) +DEFAULT_METRIC = "_metric" + +# (Optional) Mean reward for current training iteration +EPISODE_REWARD_MEAN = "episode_reward_mean" + +# (Optional) Mean loss for training iteration +MEAN_LOSS = "mean_loss" + +# (Optional) Mean accuracy for training iteration +MEAN_ACCURACY = "mean_accuracy" + +# Number of episodes in this iteration. +EPISODES_THIS_ITER = "episodes_this_iter" + +# (Optional/Auto-filled) Accumulated number of episodes for this trial. +EPISODES_TOTAL = "episodes_total" + +# Number of timesteps in this iteration. +TIMESTEPS_THIS_ITER = "timesteps_this_iter" + +# (Auto-filled) Accumulated number of timesteps for this entire trial. +TIMESTEPS_TOTAL = "timesteps_total" + +# (Auto-filled) Accumulated time in seconds for this entire trial. +TIME_TOTAL_S = "time_total_s" + +# __sphinx_doc_end__ +# fmt: on + +DEFAULT_EXPERIMENT_INFO_KEYS = ("trainable_name", EXPERIMENT_TAG, TRIAL_ID) + +DEFAULT_RESULT_KEYS = ( + TRAINING_ITERATION, + TIME_TOTAL_S, + MEAN_ACCURACY, + MEAN_LOSS, +) + +# Metrics that don't require at least one iteration to complete +DEBUG_METRICS = ( + TRIAL_ID, + "experiment_id", + "date", + TIMESTAMP, + PID, + HOSTNAME, + NODE_IP, + "config", +) + +# Make sure this doesn't regress +AUTO_RESULT_KEYS = ( + TRAINING_ITERATION, + TIME_TOTAL_S, + EPISODES_TOTAL, + TIMESTEPS_TOTAL, + NODE_IP, + HOSTNAME, + PID, + TIME_TOTAL_S, + TIME_THIS_ITER_S, + TIMESTAMP, + "date", + "time_since_restore", + "timesteps_since_restore", + "iterations_since_restore", + "config", + # TODO(justinvyu): Move this stuff to train to avoid cyclical dependency. + "checkpoint_dir_name", +) + +# __duplicate__ is a magic keyword used internally to +# avoid double-logging results when using the Function API. +RESULT_DUPLICATE = "__duplicate__" + +# __trial_info__ is a magic keyword used internally to pass trial_info +# to the Trainable via the constructor. +TRIAL_INFO = "__trial_info__" + +# __stdout_file__/__stderr_file__ are magic keywords used internally +# to pass log file locations to the Trainable via the constructor. +STDOUT_FILE = "__stdout_file__" +STDERR_FILE = "__stderr_file__" + +DEFAULT_EXPERIMENT_NAME = "default" + +# Meta file about status under each experiment directory, can be +# parsed by automlboard if exists. +JOB_META_FILE = "job_status.json" + +# Meta file about status under each trial directory, can be parsed +# by automlboard if exists. +EXPR_META_FILE = "trial_status.json" + +# Config prefix when using ExperimentAnalysis. +CONFIG_PREFIX = "config" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/result_grid.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/result_grid.py new file mode 100644 index 0000000000000000000000000000000000000000..07e236f06833670efe1e19fd001b5e147e75581b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/result_grid.py @@ -0,0 +1,283 @@ +from typing import Optional, Union + +import pandas as pd +import pyarrow + +from ray.air.result import Result +from ray.exceptions import RayTaskError +from ray.tune.analysis import ExperimentAnalysis +from ray.tune.error import TuneError +from ray.tune.experiment import Trial +from ray.util import PublicAPI + + +@PublicAPI(stability="beta") +class ResultGrid: + """A set of ``Result`` objects for interacting with Ray Tune results. + + You can use it to inspect the trials and obtain the best result. + + The constructor is a private API. This object can only be created as a result of + ``Tuner.fit()``. + + Example: + .. testcode:: + + import random + from ray import tune + def random_error_trainable(config): + if random.random() < 0.5: + return {"loss": 0.0} + else: + raise ValueError("This is an error") + tuner = tune.Tuner( + random_error_trainable, + run_config=tune.RunConfig(name="example-experiment"), + tune_config=tune.TuneConfig(num_samples=10), + ) + try: + result_grid = tuner.fit() + except ValueError: + pass + for i in range(len(result_grid)): + result = result_grid[i] + if not result.error: + print(f"Trial finishes successfully with metrics" + f"{result.metrics}.") + else: + print(f"Trial failed with error {result.error}.") + + .. testoutput:: + :hide: + + ... + + You can also use ``result_grid`` for more advanced analysis. + + >>> # Get the best result based on a particular metric. + >>> best_result = result_grid.get_best_result( # doctest: +SKIP + ... metric="loss", mode="min") + >>> # Get the best checkpoint corresponding to the best result. + >>> best_checkpoint = best_result.checkpoint # doctest: +SKIP + >>> # Get a dataframe for the last reported results of all of the trials + >>> df = result_grid.get_dataframe() # doctest: +SKIP + >>> # Get a dataframe for the minimum loss seen for each trial + >>> df = result_grid.get_dataframe(metric="loss", mode="min") # doctest: +SKIP + + Note that trials of all statuses are included in the final result grid. + If a trial is not in terminated state, its latest result and checkpoint as + seen by Tune will be provided. + + See :doc:`/tune/examples/tune_analyze_results` for more usage examples. + """ + + def __init__( + self, + experiment_analysis: ExperimentAnalysis, + ): + self._experiment_analysis = experiment_analysis + self._results = [ + self._trial_to_result(trial) for trial in self._experiment_analysis.trials + ] + + @property + def experiment_path(self) -> str: + """Path pointing to the experiment directory on persistent storage. + + This can point to a remote storage location (e.g. S3) or to a local + location (path on the head node).""" + return self._experiment_analysis.experiment_path + + @property + def filesystem(self) -> pyarrow.fs.FileSystem: + """Return the filesystem that can be used to access the experiment path. + + Returns: + pyarrow.fs.FileSystem implementation. + """ + return self._experiment_analysis._fs + + def get_best_result( + self, + metric: Optional[str] = None, + mode: Optional[str] = None, + scope: str = "last", + filter_nan_and_inf: bool = True, + ) -> Result: + """Get the best result from all the trials run. + + Args: + metric: Key for trial info to order on. Defaults to + the metric specified in your Tuner's ``TuneConfig``. + mode: One of [min, max]. Defaults to the mode specified + in your Tuner's ``TuneConfig``. + scope: One of [all, last, avg, last-5-avg, last-10-avg]. + If `scope=last`, only look at each trial's final step for + `metric`, and compare across trials based on `mode=[min,max]`. + If `scope=avg`, consider the simple average over all steps + for `metric` and compare across trials based on + `mode=[min,max]`. If `scope=last-5-avg` or `scope=last-10-avg`, + consider the simple average over the last 5 or 10 steps for + `metric` and compare across trials based on `mode=[min,max]`. + If `scope=all`, find each trial's min/max score for `metric` + based on `mode`, and compare trials based on `mode=[min,max]`. + filter_nan_and_inf: If True (default), NaN or infinite + values are disregarded and these trials are never selected as + the best trial. + """ + if len(self._experiment_analysis.trials) == 1: + return self._trial_to_result(self._experiment_analysis.trials[0]) + if not metric and not self._experiment_analysis.default_metric: + raise ValueError( + "No metric is provided. Either pass in a `metric` arg to " + "`get_best_result` or specify a metric in the " + "`TuneConfig` of your `Tuner`." + ) + if not mode and not self._experiment_analysis.default_mode: + raise ValueError( + "No mode is provided. Either pass in a `mode` arg to " + "`get_best_result` or specify a mode in the " + "`TuneConfig` of your `Tuner`." + ) + + best_trial = self._experiment_analysis.get_best_trial( + metric=metric, + mode=mode, + scope=scope, + filter_nan_and_inf=filter_nan_and_inf, + ) + if not best_trial: + error_msg = ( + "No best trial found for the given metric: " + f"{metric or self._experiment_analysis.default_metric}. " + "This means that no trial has reported this metric" + ) + error_msg += ( + ", or all values reported for this metric are NaN. To not ignore NaN " + "values, you can set the `filter_nan_and_inf` arg to False." + if filter_nan_and_inf + else "." + ) + raise RuntimeError(error_msg) + + return self._trial_to_result(best_trial) + + def get_dataframe( + self, + filter_metric: Optional[str] = None, + filter_mode: Optional[str] = None, + ) -> pd.DataFrame: + """Return dataframe of all trials with their configs and reported results. + + Per default, this returns the last reported results for each trial. + + If ``filter_metric`` and ``filter_mode`` are set, the results from each + trial are filtered for this metric and mode. For example, if + ``filter_metric="some_metric"`` and ``filter_mode="max"``, for each trial, + every received result is checked, and the one where ``some_metric`` is + maximal is returned. + + + Example: + + .. testcode:: + + import ray.tune + + def training_loop_per_worker(config): + ray.tune.report({"accuracy": 0.8}) + + result_grid = ray.tune.Tuner( + trainable=training_loop_per_worker, + run_config=ray.tune.RunConfig(name="my_tune_run") + ).fit() + + # Get last reported results per trial + df = result_grid.get_dataframe() + + # Get best ever reported accuracy per trial + df = result_grid.get_dataframe( + filter_metric="accuracy", filter_mode="max" + ) + + .. testoutput:: + :hide: + + ... + + Args: + filter_metric: Metric to filter best result for. + filter_mode: If ``filter_metric`` is given, one of ``["min", "max"]`` + to specify if we should find the minimum or maximum result. + + Returns: + Pandas DataFrame with each trial as a row and their results as columns. + """ + return self._experiment_analysis.dataframe( + metric=filter_metric, mode=filter_mode + ) + + def __len__(self) -> int: + return len(self._results) + + def __getitem__(self, i: int) -> Result: + """Returns the i'th result in the grid.""" + return self._results[i] + + @property + def errors(self): + """Returns the exceptions of errored trials.""" + return [result.error for result in self if result.error] + + @property + def num_errors(self): + """Returns the number of errored trials.""" + return len( + [t for t in self._experiment_analysis.trials if t.status == Trial.ERROR] + ) + + @property + def num_terminated(self): + """Returns the number of terminated (but not errored) trials.""" + return len( + [ + t + for t in self._experiment_analysis.trials + if t.status == Trial.TERMINATED + ] + ) + + @staticmethod + def _populate_exception(trial: Trial) -> Optional[Union[TuneError, RayTaskError]]: + if trial.status == Trial.TERMINATED: + return None + return trial.get_pickled_error() or trial.get_error() + + def _trial_to_result(self, trial: Trial) -> Result: + cpm = trial.run_metadata.checkpoint_manager + checkpoint = None + if cpm.latest_checkpoint_result: + checkpoint = cpm.latest_checkpoint_result.checkpoint + best_checkpoint_results = cpm.best_checkpoint_results + best_checkpoints = [ + (checkpoint_result.checkpoint, checkpoint_result.metrics) + for checkpoint_result in best_checkpoint_results + ] + + metrics_df = self._experiment_analysis.trial_dataframes.get(trial.trial_id) + + result = Result( + checkpoint=checkpoint, + metrics=trial.last_result.copy(), + error=self._populate_exception(trial), + path=trial.path, + _storage_filesystem=self._experiment_analysis._fs, + metrics_dataframe=metrics_df, + best_checkpoints=best_checkpoints, + ) + return result + + def __repr__(self) -> str: + all_results_repr = [result._repr(indent=2) for result in self] + all_results_repr = ",\n".join(all_results_repr) + return f"ResultGrid<[\n{all_results_repr}\n]>" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/syncer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/syncer.py new file mode 100644 index 0000000000000000000000000000000000000000..890d06593b582204c4ddfd7c46a928a20208d55f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/syncer.py @@ -0,0 +1,46 @@ +import logging +from dataclasses import dataclass + +from ray.train._internal.syncer import SyncConfig as TrainSyncConfig +from ray.util.annotations import PublicAPI + +logger = logging.getLogger(__name__) + + +@PublicAPI(stability="beta") +@dataclass +class SyncConfig(TrainSyncConfig): + """Configuration object for Tune file syncing to `RunConfig(storage_path)`. + + In Ray Tune, here is where syncing (mainly uploading) happens: + + The experiment driver (on the head node) syncs the experiment directory to storage + (which includes experiment state such as searcher state, the list of trials + and their statuses, and trial metadata). + + It's also possible to sync artifacts from the trial directory to storage + by setting `sync_artifacts=True`. + For a Ray Tune run with many trials, each trial will upload its trial directory + to storage, which includes arbitrary files that you dumped during the run. + + Args: + sync_period: Minimum time in seconds to wait between two sync operations. + A smaller ``sync_period`` will have the data in storage updated more often + but introduces more syncing overhead. Defaults to 5 minutes. + sync_timeout: Maximum time in seconds to wait for a sync process + to finish running. A sync operation will run for at most this long + before raising a `TimeoutError`. Defaults to 30 minutes. + sync_artifacts: [Beta] Whether or not to sync artifacts that are saved to the + trial directory (accessed via `ray.tune.get_context().get_trial_dir()`) + to the persistent storage configured via `tune.RunConfig(storage_path)`. + The trial or remote worker will try to launch an artifact syncing + operation every time `tune.report` happens, subject to `sync_period` + and `sync_artifacts_on_checkpoint`. + Defaults to False -- no artifacts are persisted by default. + sync_artifacts_on_checkpoint: If True, trial/worker artifacts are + forcefully synced on every reported checkpoint. + This only has an effect if `sync_artifacts` is True. + Defaults to True. + """ + + pass diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tune.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tune.py new file mode 100644 index 0000000000000000000000000000000000000000..ac61a9ddacf81b983b98b7413311a0f312671ad4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tune.py @@ -0,0 +1,1161 @@ +import abc +import copy +import datetime +import logging +import os +import signal +import sys +import threading +import time +import warnings +from typing import ( + TYPE_CHECKING, + Any, + Callable, + Dict, + Mapping, + Optional, + Sequence, + Type, + Union, +) + +import ray +from ray.air._internal import usage as air_usage +from ray.air._internal.usage import AirEntrypoint +from ray.air.util.node import _force_on_current_node +from ray.train.constants import _DEPRECATED_VALUE, RAY_CHDIR_TO_TRIAL_DIR +from ray.tune import CheckpointConfig, SyncConfig +from ray.tune.analysis import ExperimentAnalysis +from ray.tune.callback import Callback +from ray.tune.error import TuneError +from ray.tune.execution.placement_groups import PlacementGroupFactory +from ray.tune.execution.tune_controller import TuneController +from ray.tune.experiment import Experiment, Trial, _convert_to_experiment_list +from ray.tune.experimental.output import IS_NOTEBOOK, AirVerbosity, get_air_verbosity +from ray.tune.impl.placeholder import create_resolvers_map, inject_placeholders +from ray.tune.logger import TBXLoggerCallback +from ray.tune.progress_reporter import ( + ProgressReporter, + _detect_progress_metrics, + _detect_reporter, + _prepare_progress_reporter_for_ray_client, + _stream_client_output, +) +from ray.tune.registry import get_trainable_cls + +# Must come last to avoid circular imports +from ray.tune.schedulers import ( + FIFOScheduler, + PopulationBasedTraining, + PopulationBasedTrainingReplay, + TrialScheduler, +) +from ray.tune.schedulers.util import ( + _set_search_properties_backwards_compatible as scheduler_set_search_props, +) +from ray.tune.search import ( + BasicVariantGenerator, + ConcurrencyLimiter, + SearchAlgorithm, + Searcher, + SearchGenerator, + create_searcher, +) +from ray.tune.search.util import ( + _set_search_properties_backwards_compatible as searcher_set_search_props, +) +from ray.tune.search.variant_generator import _has_unresolved_values +from ray.tune.stopper import Stopper +from ray.tune.trainable import Trainable +from ray.tune.tune_config import ResumeConfig +from ray.tune.utils.callback import _create_default_callbacks +from ray.tune.utils.log import Verbosity, has_verbosity, set_verbosity +from ray.util.annotations import PublicAPI +from ray.util.queue import Queue + +if TYPE_CHECKING: + import pyarrow.fs + + from ray.tune.experimental.output import ProgressReporter as AirProgressReporter + +logger = logging.getLogger(__name__) + + +def _get_trainable( + run_identifier: Union[Experiment, str, Type, Callable] +) -> Optional[Type[Trainable]]: + if isinstance(run_identifier, Experiment): + run_identifier = run_identifier.run_identifier + + if isinstance(run_identifier, type): + if not issubclass(run_identifier, Trainable): + # If obscure dtype, assume it is overridden. + return None + trainable_cls = run_identifier + elif callable(run_identifier): + trainable_cls = run_identifier + elif isinstance(run_identifier, str): + trainable_cls = get_trainable_cls(run_identifier) + else: + return None + + return trainable_cls + + +def _build_resume_config_from_legacy_config( + resume: Union[str, bool] +) -> Optional[ResumeConfig]: + """Converts the legacy resume (str, bool) to a ResumeConfig object. + Returns None if resume is False. + """ + if resume is False: + return None + if resume is True: + return ResumeConfig() + + # Parse resume string, e.g. AUTO+ERRORED + resume_settings = resume.split("+") + resume_str = resume_settings[0] + + if resume_str in ("LOCAL", "REMOTE", "PROMPT", "ERRORED_ONLY"): + raise DeprecationWarning( + f"'{resume_str}' is deprecated. " + "Please pass in one of (True, False, 'AUTO')." + ) + + resume_config = ResumeConfig() + for setting in resume_settings[1:]: + if setting == "ERRORED": + resume_config = ResumeConfig(errored=ResumeConfig.ResumeType.RESUME) + elif setting == "RESTART_ERRORED": + resume_config = ResumeConfig(errored=ResumeConfig.ResumeType.RESTART) + elif setting == "ERRORED_ONLY": + resume_config = ResumeConfig( + unfinished=ResumeConfig.ResumeType.SKIP, + errored=ResumeConfig.ResumeType.RESUME, + ) + elif setting == "RESTART_ERRORED_ONLY": + resume_config = ResumeConfig( + unfinished=ResumeConfig.ResumeType.SKIP, + errored=ResumeConfig.ResumeType.RESTART, + ) + else: + raise ValueError(f"Invalid resume setting: '{setting}'") + + return resume_config + + +def _check_default_resources_override( + run_identifier: Union[Experiment, str, Type, Callable] +) -> bool: + trainable_cls = _get_trainable(run_identifier) + if not trainable_cls: + # If no trainable, assume override + return True + + return hasattr(trainable_cls, "default_resource_request") and ( + trainable_cls.default_resource_request.__code__ + != Trainable.default_resource_request.__code__ + ) + + +def _check_mixin(run_identifier: Union[Experiment, str, Type, Callable]) -> bool: + trainable_cls = _get_trainable(run_identifier) + if not trainable_cls: + # Default to True + return True + + return hasattr(trainable_cls, "__mixins__") or getattr( + trainable_cls, "_is_mixin", False + ) + + +def _check_gpus_in_resources( + resources: Optional[Union[Dict, PlacementGroupFactory]] +) -> bool: + if not resources: + return False + + if isinstance(resources, PlacementGroupFactory): + return bool(resources.required_resources.get("GPU", None)) + + if isinstance(resources, dict): + return bool(resources.get("gpu", None)) + + +def _report_progress( + runner: TuneController, reporter: ProgressReporter, done: bool = False +): + """Reports experiment progress. + + Args: + runner: Trial runner to report on. + reporter: Progress reporter. + done: Whether this is the last progress report attempt. + """ + trials = runner.get_trials() + if reporter.should_report(trials, done=done): + sched_debug_str = runner.scheduler_alg.debug_string() + used_resources_str = runner._used_resources_string() + reporter.report(trials, done, sched_debug_str, used_resources_str) + + +def _report_air_progress( + runner: TuneController, reporter: "AirProgressReporter", force: bool = False +): + trials = runner.get_trials() + reporter_args = [] + used_resources_string = runner._used_resources_string() + reporter_args.append(used_resources_string) + reporter.print_heartbeat(trials, *reporter_args, force=force) + + +def _setup_signal_catching() -> threading.Event: + original_handler = signal.getsignal(signal.SIGINT) + experiment_interrupted_event = threading.Event() + + def signal_interrupt_tune_run(sig: int, frame): + logger.warning( + "Stop signal received (e.g. via SIGINT/Ctrl+C), ending Ray Tune run. " + "This will try to checkpoint the experiment state one last time. " + "Press CTRL+C (or send SIGINT/SIGKILL/SIGTERM) " + "to skip. " + ) + experiment_interrupted_event.set() + # Restore original signal handler to react to future SIGINT signals. + signal.signal(signal.SIGINT, original_handler) + + # We should only install the handler when it is safe to do so. + # When tune.run() is called from worker thread, signal.signal will + # fail. + allow_signal_catching = True + if threading.current_thread() != threading.main_thread(): + allow_signal_catching = False + + if allow_signal_catching: + if not int(os.getenv("TUNE_DISABLE_SIGINT_HANDLER", "0")): + signal.signal(signal.SIGINT, signal_interrupt_tune_run) + + # Always register SIGUSR1 if available (not available e.g. on Windows) + if hasattr(signal, "SIGUSR1"): + signal.signal(signal.SIGUSR1, signal_interrupt_tune_run) + + return experiment_interrupted_event + + +def _ray_auto_init(entrypoint: str): + """Initialize Ray unless already configured.""" + if os.environ.get("TUNE_DISABLE_AUTO_INIT") == "1": + logger.info("'TUNE_DISABLE_AUTO_INIT=1' detected.") + elif not ray.is_initialized(): + ray.init() + logger.info( + "Initializing Ray automatically. " + "For cluster usage or custom Ray initialization, " + f"call `ray.init(...)` before `{entrypoint}`." + ) + + +class _Config(abc.ABC): + def to_dict(self) -> dict: + """Converts this configuration to a dict format.""" + raise NotImplementedError + + +@PublicAPI +def run( + run_or_experiment: Union[str, Callable, Type], + *, + name: Optional[str] = None, + metric: Optional[str] = None, + mode: Optional[str] = None, + stop: Optional[Union[Mapping, Stopper, Callable[[str, Mapping], bool]]] = None, + time_budget_s: Optional[Union[int, float, datetime.timedelta]] = None, + config: Optional[Dict[str, Any]] = None, + resources_per_trial: Union[ + None, Mapping[str, Union[float, int, Mapping]], PlacementGroupFactory + ] = None, + num_samples: int = 1, + storage_path: Optional[str] = None, + storage_filesystem: Optional["pyarrow.fs.FileSystem"] = None, + search_alg: Optional[Union[Searcher, SearchAlgorithm, str]] = None, + scheduler: Optional[Union[TrialScheduler, str]] = None, + checkpoint_config: Optional[CheckpointConfig] = None, + verbose: Optional[Union[int, AirVerbosity, Verbosity]] = None, + progress_reporter: Optional[ProgressReporter] = None, + log_to_file: bool = False, + trial_name_creator: Optional[Callable[[Trial], str]] = None, + trial_dirname_creator: Optional[Callable[[Trial], str]] = None, + sync_config: Optional[SyncConfig] = None, + export_formats: Optional[Sequence] = None, + max_failures: int = 0, + fail_fast: bool = False, + restore: Optional[str] = None, + resume: Optional[Union[bool, str]] = None, + resume_config: Optional[ResumeConfig] = None, + reuse_actors: bool = False, + raise_on_failed_trial: bool = True, + callbacks: Optional[Sequence[Callback]] = None, + max_concurrent_trials: Optional[int] = None, + # Deprecated + keep_checkpoints_num: Optional[int] = None, # Deprecated (2.7) + checkpoint_score_attr: Optional[str] = None, # Deprecated (2.7) + checkpoint_freq: int = 0, # Deprecated (2.7) + checkpoint_at_end: bool = False, # Deprecated (2.7) + chdir_to_trial_dir: bool = _DEPRECATED_VALUE, # Deprecated (2.8) + local_dir: Optional[str] = None, + # == internal only == + _remote: Optional[bool] = None, + # Passed by the Tuner. + _remote_string_queue: Optional[Queue] = None, + # Todo (krfricke): Find a better way to pass entrypoint information, e.g. + # a context object or similar. + _entrypoint: AirEntrypoint = AirEntrypoint.TUNE_RUN, +) -> ExperimentAnalysis: + """Executes training. + + When a SIGINT signal is received (e.g. through Ctrl+C), the tuning run + will gracefully shut down and checkpoint the latest experiment state. + Sending SIGINT again (or SIGKILL/SIGTERM instead) will skip this step. + + Many aspects of Tune, such as the frequency of global checkpointing, + maximum pending placement group trials and the path of the result + directory be configured through environment variables. Refer to + :ref:`tune-env-vars` for a list of environment variables available. + + Examples: + + .. code-block:: python + + # Run 10 trials (each trial is one instance of a Trainable). Tune runs + # in parallel and automatically determines concurrency. + tune.run(trainable, num_samples=10) + + # Run 1 trial, stop when trial has reached 10 iterations + tune.run(my_trainable, stop={"training_iteration": 10}) + + # automatically retry failed trials up to 3 times + tune.run(my_trainable, stop={"training_iteration": 10}, max_failures=3) + + # Run 1 trial, search over hyperparameters, stop after 10 iterations. + space = {"lr": tune.uniform(0, 1), "momentum": tune.uniform(0, 1)} + tune.run(my_trainable, config=space, stop={"training_iteration": 10}) + + # Resumes training if a previous machine crashed + tune.run( + my_trainable, config=space, + storage_path=, name=, resume=True + ) + + Args: + run_or_experiment: If function|class|str, this is the algorithm or + model to train. This may refer to the name of a built-on algorithm + (e.g. RLlib's DQN or PPO), a user-defined trainable + function or class, or the string identifier of a + trainable function or class registered in the tune registry. + If Experiment, then Tune will execute training based on + Experiment.spec. If you want to pass in a Python lambda, you + will need to first register the function: + ``tune.register_trainable("lambda_id", lambda x: ...)``. You can + then use ``tune.run("lambda_id")``. + metric: Metric to optimize. This metric should be reported + with `tune.report()`. If set, will be passed to the search + algorithm and scheduler. + mode: Must be one of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. If set, will be + passed to the search algorithm and scheduler. + name: Name of experiment. + stop: Stopping criteria. If dict, + the keys may be any field in the return result of 'train()', + whichever is reached first. If function, it must take (trial_id, + result) as arguments and return a boolean (True if trial should be + stopped, False otherwise). This can also be a subclass of + ``ray.tune.Stopper``, which allows users to implement + custom experiment-wide stopping (i.e., stopping an entire Tune + run based on some time constraint). + time_budget_s: Global time budget in + seconds after which all trials are stopped. Can also be a + ``datetime.timedelta`` object. + config: Algorithm-specific configuration for Tune variant + generation (e.g. env, hyperparams). Defaults to empty dict. + Custom search algorithms may ignore this. + resources_per_trial: Machine resources + to allocate per trial, e.g. ``{"cpu": 64, "gpu": 8}``. + Note that GPUs will not be assigned unless you specify them here. + Defaults to 1 CPU and 0 GPUs in + ``Trainable.default_resource_request()``. This can also + be a PlacementGroupFactory object wrapping arguments to create a + per-trial placement group. + num_samples: Number of times to sample from the + hyperparameter space. Defaults to 1. If `grid_search` is + provided as an argument, the grid will be repeated + `num_samples` of times. If this is -1, (virtually) infinite + samples are generated until a stopping condition is met. + storage_path: Path to store results at. Can be a local directory or + a destination on cloud storage. Defaults to + the local ``~/ray_results`` directory. + search_alg: Search algorithm for + optimization. You can also use the name of the algorithm. + scheduler: Scheduler for executing + the experiment. Choose among FIFO (default), MedianStopping, + AsyncHyperBand, HyperBand and PopulationBasedTraining. Refer to + ray.tune.schedulers for more options. You can also use the + name of the scheduler. + verbose: 0, 1, or 2. Verbosity mode. + 0 = silent, 1 = default, 2 = verbose. Defaults to 1. + If the ``RAY_AIR_NEW_OUTPUT=1`` environment variable is set, + uses the old verbosity settings: + 0 = silent, 1 = only status updates, 2 = status and brief + results, 3 = status and detailed results. + progress_reporter: Progress reporter for reporting + intermediate experiment progress. Defaults to CLIReporter if + running in command-line, or JupyterNotebookReporter if running in + a Jupyter notebook. + log_to_file: Log stdout and stderr to files in + Tune's trial directories. If this is `False` (default), no files + are written. If `true`, outputs are written to `trialdir/stdout` + and `trialdir/stderr`, respectively. If this is a single string, + this is interpreted as a file relative to the trialdir, to which + both streams are written. If this is a Sequence (e.g. a Tuple), + it has to have length 2 and the elements indicate the files to + which stdout and stderr are written, respectively. + trial_name_creator: Optional function that takes in a Trial and returns + its name (i.e. its string representation). Be sure to include some unique + identifier (such as `Trial.trial_id`) in each trial's name. + trial_dirname_creator: Optional function that takes in a trial and + generates its trial directory name as a string. Be sure to include some + unique identifier (such as `Trial.trial_id`) is used in each trial's + directory name. Otherwise, trials could overwrite artifacts and checkpoints + of other trials. The return value cannot be a path. + chdir_to_trial_dir: Deprecated. Set the `RAY_CHDIR_TO_TRIAL_DIR` env var instead + sync_config: Configuration object for syncing. See tune.SyncConfig. + export_formats: List of formats that exported at the end of + the experiment. Default is None. + max_failures: Try to recover a trial at least this many times. + Ray will recover from the latest checkpoint if present. + Setting to -1 will lead to infinite recovery retries. + Setting to 0 will disable retries. Defaults to 0. + fail_fast: Whether to fail upon the first error. + If fail_fast='raise' provided, Tune will automatically + raise the exception received by the Trainable. fail_fast='raise' + can easily leak resources and should be used with caution (it + is best used with `ray.init(local_mode=True)`). + restore: Path to checkpoint. Only makes sense to set if + running 1 trial. Defaults to None. + resume: One of [True, False, "AUTO"]. Can + be suffixed with one or more of ["+ERRORED", "+ERRORED_ONLY", + "+RESTART_ERRORED", "+RESTART_ERRORED_ONLY"] (e.g. ``AUTO+ERRORED``). + `resume=True` and `resume="AUTO"` will attempt to resume from a + checkpoint and otherwise start a new experiment. + The suffix "+ERRORED" resets and reruns errored trials upon resume - + previous trial artifacts will be left untouched. It will try to continue + from the last observed checkpoint. + The suffix "+RESTART_ERRORED" will instead start the errored trials from + scratch. "+ERRORED_ONLY" and "+RESTART_ERRORED_ONLY" will disable + resuming non-errored trials - they will be added as finished instead. New + trials can still be generated by the search algorithm. + resume_config: [Experimental] Config object that controls how to resume + trials of different statuses. Can be used as a substitute to the + `resume` suffixes described above. + reuse_actors: Whether to reuse actors between different trials + when possible. This can drastically speed up experiments that start + and stop actors often (e.g., PBT in time-multiplexing mode). This + requires trials to have the same resource requirements. + Defaults to ``False``. + raise_on_failed_trial: Raise TuneError if there exists failed + trial (of ERROR state) when the experiments complete. + callbacks: List of callbacks that will be called at different + times in the training loop. Must be instances of the + ``ray.tune.callback.Callback`` class. If not passed, + `LoggerCallback` (json/csv/tensorboard) callbacks are automatically added. + max_concurrent_trials: Maximum number of trials to run + concurrently. Must be non-negative. If None or 0, no limit will + be applied. This is achieved by wrapping the ``search_alg`` in + a :class:`ConcurrencyLimiter`, and thus setting this argument + will raise an exception if the ``search_alg`` is already a + :class:`ConcurrencyLimiter`. Defaults to None. + _remote: Whether to run the Tune driver in a remote function. + This is disabled automatically if a custom trial executor is + passed in. This is enabled by default in Ray client mode. + local_dir: Deprecated. Use `storage_path` instead. + keep_checkpoints_num: Deprecated. use checkpoint_config instead. + checkpoint_score_attr: Deprecated. use checkpoint_config instead. + checkpoint_freq: Deprecated. use checkpoint_config instead. + checkpoint_at_end: Deprecated. use checkpoint_config instead. + checkpoint_keep_all_ranks: Deprecated. use checkpoint_config instead. + checkpoint_upload_from_workers: Deprecated. use checkpoint_config instead. + + Returns: + ExperimentAnalysis: Object for experiment analysis. + + Raises: + TuneError: Any trials failed and `raise_on_failed_trial` is True. + """ + # NO CODE IS TO BE ADDED ABOVE THIS COMMENT + # remote_run_kwargs must be defined before any other + # code is ran to ensure that at this point, + # `locals()` is equal to args and kwargs + remote_run_kwargs = locals().copy() + remote_run_kwargs.pop("_remote") + + if _entrypoint == AirEntrypoint.TRAINER: + error_message_map = { + "entrypoint": "(...)", + "search_space_arg": "param_space", + "restore_entrypoint": '.restore(path="{path}", ...)', + } + elif _entrypoint == AirEntrypoint.TUNER: + error_message_map = { + "entrypoint": "Tuner(...)", + "search_space_arg": "param_space", + "restore_entrypoint": 'Tuner.restore(path="{path}", trainable=...)', + } + elif _entrypoint == AirEntrypoint.TUNE_RUN_EXPERIMENTS: + error_message_map = { + "entrypoint": "tune.run_experiments(...)", + "search_space_arg": "experiment=Experiment(config)", + "restore_entrypoint": "tune.run_experiments(..., resume=True)", + } + else: + error_message_map = { + "entrypoint": "tune.run(...)", + "search_space_arg": "config", + "restore_entrypoint": "tune.run(..., resume=True)", + } + + _ray_auto_init(entrypoint=error_message_map["entrypoint"]) + + if _remote is None: + _remote = ray.util.client.ray.is_connected() + + if verbose is None: + # Default `verbose` value. For new output engine, this is AirVerbosity.VERBOSE. + # For old output engine, this is Verbosity.V3_TRIAL_DETAILS + verbose = get_air_verbosity(AirVerbosity.VERBOSE) or Verbosity.V3_TRIAL_DETAILS + + if _remote: + if get_air_verbosity(verbose) is not None: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Ray client is not supported by the new engine. " + "For more information, see " + "https://github.com/ray-project/ray/issues/36949" + ) + + remote_run = ray.remote(num_cpus=0)(run) + + # Make sure tune.run is called on the sever node. + remote_run = _force_on_current_node(remote_run) + + progress_reporter, string_queue = _prepare_progress_reporter_for_ray_client( + progress_reporter, verbose, _remote_string_queue + ) + + # Override with detected progress reporter + remote_run_kwargs["progress_reporter"] = progress_reporter + + remote_future = remote_run.remote(_remote=False, **remote_run_kwargs) + + _stream_client_output( + remote_future, + progress_reporter, + string_queue, + ) + return ray.get(remote_future) + + del remote_run_kwargs + + # TODO(justinvyu): [Deprecated] Remove in 2.30 + ENV_VAR_DEPRECATION_MESSAGE = ( + "The environment variable `{}` is deprecated. " + "It is no longer used and will not have any effect. " + "You should set the `storage_path` instead. Files will no longer be " + "written to `~/ray_results` as long as `storage_path` is set." + "See the docs: https://docs.ray.io/en/latest/train/user-guides/" + "persistent-storage.html#setting-the-local-staging-directory" + ) + if os.environ.get("TUNE_RESULT_DIR"): + raise DeprecationWarning(ENV_VAR_DEPRECATION_MESSAGE.format("TUNE_RESULT_DIR")) + + if os.environ.get("RAY_AIR_LOCAL_CACHE_DIR"): + raise DeprecationWarning( + ENV_VAR_DEPRECATION_MESSAGE.format("RAY_AIR_LOCAL_CACHE_DIR") + ) + + if local_dir is not None: + raise DeprecationWarning( + "The `local_dir` argument is deprecated. " + "You should set the `storage_path` instead. " + "See the docs: https://docs.ray.io/en/latest/train/user-guides/" + "persistent-storage.html#setting-the-local-staging-directory" + ) + + ray._private.usage.usage_lib.record_library_usage("tune") + + # Tracking environment variable usage here will also catch: + # 1.) Tuner.fit() usage + # 2.) Trainer.fit() usage + # 3.) Ray client usage (env variables are inherited by the Ray runtime env) + air_usage.tag_ray_air_env_vars() + + # Track the entrypoint to AIR: + # Tuner.fit / Trainer.fit / tune.run / tune.run_experiments + air_usage.tag_air_entrypoint(_entrypoint) + + all_start = time.time() + + if mode and mode not in ["min", "max"]: + raise ValueError( + f"The `mode` parameter passed to `{error_message_map['entrypoint']}` " + "must be one of ['min', 'max']" + ) + + air_verbosity = get_air_verbosity(verbose) + if air_verbosity is not None and IS_NOTEBOOK: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Jupyter notebooks are not supported by the new engine, yet. " + "For more information, please see " + "https://github.com/ray-project/ray/issues/36949" + ) + air_verbosity = None + + if air_verbosity is not None: + # Disable old output engine + set_verbosity(0) + else: + # Use old output engine + set_verbosity(verbose) + + config = config or {} + if isinstance(config, _Config): + config = config.to_dict() + if not isinstance(config, dict): + raise ValueError( + f"The `{error_message_map['search_space_arg']}` passed to " + f"`{error_message_map['entrypoint']}` must be a dict. " + f"Got '{type(config)}' instead." + ) + + sync_config = sync_config or SyncConfig() + checkpoint_config = checkpoint_config or CheckpointConfig() + + # For backward compatibility + # TODO(jungong): remove after 2.7 release. + if keep_checkpoints_num is not None: + warnings.warn( + "keep_checkpoints_num is deprecated and will be removed. " + "use checkpoint_config.num_to_keep instead.", + DeprecationWarning, + ) + checkpoint_config.num_to_keep = keep_checkpoints_num + if checkpoint_score_attr is not None: + warnings.warn( + "checkpoint_score_attr is deprecated and will be removed. " + "use checkpoint_config.checkpoint_score_attribute instead.", + DeprecationWarning, + ) + + if checkpoint_score_attr.startswith("min-"): + warnings.warn( + "using min- and max- prefixes to specify checkpoint score " + "order is deprecated. Use CheckpointConfig.checkpoint_score_order " + "instead", + DeprecationWarning, + ) + checkpoint_config.checkpoint_score_attribute = checkpoint_score_attr[4:] + checkpoint_config.checkpoint_score_order = "min" + else: + checkpoint_config.checkpoint_score_attribute = checkpoint_score_attr + checkpoint_config.checkpoint_score_order = "max" + + checkpoint_config.score_attr = checkpoint_score_attr + if checkpoint_freq > 0: + warnings.warn( + "checkpoint_freq is deprecated and will be removed. " + "use checkpoint_config.checkpoint_frequency instead.", + DeprecationWarning, + ) + checkpoint_config.checkpoint_frequency = checkpoint_freq + if checkpoint_at_end: + warnings.warn( + "checkpoint_at_end is deprecated and will be removed. " + "use checkpoint_config.checkpoint_at_end instead.", + DeprecationWarning, + ) + checkpoint_config.checkpoint_at_end = checkpoint_at_end + + # TODO(justinvyu): [Deprecated] Remove in 2.11. + if chdir_to_trial_dir != _DEPRECATED_VALUE: + raise DeprecationWarning( + "`chdir_to_trial_dir` is deprecated. " + f"Use the {RAY_CHDIR_TO_TRIAL_DIR} environment variable instead. " + "Set it to 0 to disable the default behavior of changing the " + "working directory.", + DeprecationWarning, + ) + + if num_samples == -1: + num_samples = sys.maxsize + + # Create scheduler here as we need access to some of its properties + if isinstance(scheduler, str): + # importing at top level causes a recursive dependency + from ray.tune.schedulers import create_scheduler + + scheduler = create_scheduler(scheduler) + scheduler = scheduler or FIFOScheduler() + + if not scheduler.supports_buffered_results: + # Result buffering with e.g. a Hyperband scheduler is a bad idea, as + # hyperband tries to stop trials when processing brackets. With result + # buffering, we might trigger this multiple times when evaluating + # a single trial, which leads to unexpected behavior. + env_result_buffer_length = os.getenv("TUNE_RESULT_BUFFER_LENGTH", "") + if env_result_buffer_length: + warnings.warn( + f"You are using a {type(scheduler)} scheduler, but " + f"TUNE_RESULT_BUFFER_LENGTH is set " + f"({env_result_buffer_length}). This can lead to undesired " + f"and faulty behavior, so the buffer length was forcibly set " + f"to 1 instead." + ) + os.environ["TUNE_RESULT_BUFFER_LENGTH"] = "1" + + if ( + isinstance(scheduler, (PopulationBasedTraining, PopulationBasedTrainingReplay)) + and not reuse_actors + ): + warnings.warn( + "Consider boosting PBT performance by enabling `reuse_actors` as " + "well as implementing `reset_config` for Trainable." + ) + + # Before experiments are created, we first clean up the passed in + # Config dictionary by replacing all the non-primitive config values + # with placeholders. This serves two purposes: + # 1. we can replace and "fix" these objects if a Trial is restored. + # 2. the config dictionary will then be compatible with all supported + # search algorithms, since a lot of them do not support non-primitive + # config values. + placeholder_resolvers = create_resolvers_map() + config = inject_placeholders( + # Make a deep copy here to avoid modifying the original config dict. + copy.deepcopy(config), + placeholder_resolvers, + ) + + # TODO(justinvyu): We should remove the ability to pass a list of + # trainables to tune.run. + if isinstance(run_or_experiment, list): + experiments = run_or_experiment + else: + experiments = [run_or_experiment] + + for i, exp in enumerate(experiments): + if not isinstance(exp, Experiment): + experiments[i] = Experiment( + name=name, + run=exp, + stop=stop, + time_budget_s=time_budget_s, + config=config, + resources_per_trial=resources_per_trial, + num_samples=num_samples, + storage_path=storage_path, + storage_filesystem=storage_filesystem, + sync_config=sync_config, + checkpoint_config=checkpoint_config, + trial_name_creator=trial_name_creator, + trial_dirname_creator=trial_dirname_creator, + log_to_file=log_to_file, + export_formats=export_formats, + max_failures=max_failures, + restore=restore, + ) + + if fail_fast and max_failures != 0: + raise ValueError("max_failures must be 0 if fail_fast=True.") + + if isinstance(search_alg, str): + search_alg = create_searcher(search_alg) + + # if local_mode=True is set during ray.init(). + is_local_mode = ray._private.worker._mode() == ray._private.worker.LOCAL_MODE + + if is_local_mode: + max_concurrent_trials = 1 + + if not search_alg: + search_alg = BasicVariantGenerator(max_concurrent=max_concurrent_trials or 0) + elif max_concurrent_trials or is_local_mode: + if isinstance(search_alg, ConcurrencyLimiter): + if not is_local_mode: + if search_alg.max_concurrent != max_concurrent_trials: + raise ValueError( + "You have specified `max_concurrent_trials=" + f"{max_concurrent_trials}`, but the `search_alg` is " + "already a `ConcurrencyLimiter` with `max_concurrent=" + f"{search_alg.max_concurrent}. FIX THIS by setting " + "`max_concurrent_trials=None`." + ) + else: + logger.warning( + "You have specified `max_concurrent_trials=" + f"{max_concurrent_trials}`, but the `search_alg` is " + "already a `ConcurrencyLimiter`. " + "`max_concurrent_trials` will be ignored." + ) + else: + if max_concurrent_trials < 1: + raise ValueError( + "`max_concurrent_trials` must be greater or equal than 1, " + f"got {max_concurrent_trials}." + ) + if isinstance(search_alg, Searcher): + search_alg = ConcurrencyLimiter( + search_alg, max_concurrent=max_concurrent_trials + ) + elif not is_local_mode: + logger.warning( + "You have passed a `SearchGenerator` instance as the " + "`search_alg`, but `max_concurrent_trials` requires a " + "`Searcher` instance`. `max_concurrent_trials` " + "will be ignored." + ) + + if isinstance(search_alg, Searcher): + search_alg = SearchGenerator(search_alg) + + if config and not searcher_set_search_props( + search_alg.set_search_properties, + metric, + mode, + config, + **experiments[0].public_spec, + ): + if _has_unresolved_values(config): + raise ValueError( + f"You passed a `{error_message_map['search_space_arg']}` parameter to " + f"`{error_message_map['entrypoint']}` with " + "unresolved parameters, but the search algorithm was already " + "instantiated with a search space. Make sure that `config` " + "does not contain any more parameter definitions - include " + "them in the search algorithm's search space if necessary." + ) + + if not scheduler_set_search_props( + scheduler.set_search_properties, metric, mode, **experiments[0].public_spec + ): + raise ValueError( + "You passed a `metric` or `mode` argument to " + f"`{error_message_map['entrypoint']}`, but " + "the scheduler you are using was already instantiated with their " + "own `metric` and `mode` parameters. Either remove the arguments " + f"from your scheduler or from `{error_message_map['entrypoint']}` args." + ) + + progress_metrics = _detect_progress_metrics(_get_trainable(run_or_experiment)) + + air_usage.tag_storage_type(experiments[0].storage) + + # NOTE: Report callback telemetry before populating the list with default callbacks. + # This tracks user-specified callback usage. + air_usage.tag_callbacks(callbacks) + + # Create default logging + syncer callbacks + callbacks = _create_default_callbacks( + callbacks, + air_verbosity=air_verbosity, + entrypoint=_entrypoint, + config=config, + metric=metric, + mode=mode, + progress_metrics=progress_metrics, + ) + + # User Warning for GPUs + if ray.cluster_resources().get("GPU", 0): + if _check_gpus_in_resources(resources=resources_per_trial): + # "gpu" is manually set. + pass + elif _check_default_resources_override(experiments[0].run_identifier): + # "default_resources" is manually overridden. + pass + else: + logger.warning( + "Tune detects GPUs, but no trials are using GPUs. " + "To enable trials to use GPUs, wrap `train_func` with " + "`tune.with_resources(train_func, resources_per_trial={'gpu': 1})` " + "which allows Tune to expose 1 GPU to each trial. " + "For Ray Train Trainers, you can specify GPU resources " + "through `ScalingConfig(use_gpu=True)`. " + "You can also override " + "`Trainable.default_resource_request` if using the " + "Trainable API." + ) + + experiment_interrupted_event = _setup_signal_catching() + + if progress_reporter and air_verbosity is not None: + logger.warning( + "AIR_VERBOSITY is set, ignoring passed-in ProgressReporter for now." + ) + progress_reporter = None + + if air_verbosity is None: + is_trainer = _entrypoint == AirEntrypoint.TRAINER + progress_reporter = progress_reporter or _detect_reporter( + _trainer_api=is_trainer + ) + + if resume is not None: + resume_config = resume_config or _build_resume_config_from_legacy_config(resume) + + runner_kwargs = dict( + search_alg=search_alg, + placeholder_resolvers=placeholder_resolvers, + scheduler=scheduler, + stopper=experiments[0].stopper, + resume_config=resume_config, + fail_fast=fail_fast, + callbacks=callbacks, + metric=metric, + trial_checkpoint_config=experiments[0].checkpoint_config, + reuse_actors=reuse_actors, + storage=experiments[0].storage, + _trainer_api=_entrypoint == AirEntrypoint.TRAINER, + ) + + runner = TuneController(**runner_kwargs) + + if not runner.resumed: + for exp in experiments: + search_alg.add_configurations([exp]) + # search_alg.total_samples has been updated, so we should + # update the number of pending trials + runner.update_max_pending_trials() + else: + logger.debug( + "You have resumed the Tune run, which means that any newly specified " + "`Experiment`s will be ignored. " + "Tune will just continue what was previously running." + ) + if resources_per_trial: + runner.update_pending_trial_resources(resources_per_trial) + + # Calls setup on callbacks + runner.setup_experiments( + experiments=experiments, total_num_samples=search_alg.total_samples + ) + + tune_start = time.time() + + air_progress_reporter = None + if air_verbosity is None: + progress_reporter.setup( + start_time=tune_start, + total_samples=search_alg.total_samples, + metric=metric, + mode=mode, + ) + else: + from ray.tune.experimental.output import ProgressReporter as AirProgressReporter + + for callback in callbacks: + if isinstance(callback, AirProgressReporter): + air_progress_reporter = callback + air_progress_reporter.setup( + start_time=tune_start, total_samples=search_alg.total_samples + ) + break + + experiment_local_path = runner._storage.experiment_driver_staging_path + experiment_dir_name = runner._storage.experiment_dir_name + + if any(isinstance(cb, TBXLoggerCallback) for cb in callbacks): + tensorboard_path = experiment_local_path + else: + tensorboard_path = None + + if air_progress_reporter: + air_progress_reporter.experiment_started( + experiment_name=experiment_dir_name, + experiment_path=runner.experiment_path, + searcher_str=search_alg.__class__.__name__, + scheduler_str=scheduler.__class__.__name__, + total_num_samples=search_alg.total_samples, + tensorboard_path=tensorboard_path, + ) + + try: + while not runner.is_finished() and not experiment_interrupted_event.is_set(): + runner.step() + if has_verbosity(Verbosity.V1_EXPERIMENT): + _report_progress(runner, progress_reporter) + + if air_verbosity is not None: + _report_air_progress(runner, air_progress_reporter) + except Exception: + runner.cleanup() + raise + + tune_taken = time.time() - tune_start + + final_sync_start = time.time() + try: + runner.checkpoint(force=True, wait=True) + logger.info( + "Wrote the latest version of all result files and experiment state to " + f"'{runner.experiment_path}' in {time.time() - final_sync_start:.4f}s." + ) + except Exception: + logger.error( + "Experiment state snapshotting failed:", exc_info=True, stack_info=True + ) + + if has_verbosity(Verbosity.V1_EXPERIMENT): + _report_progress(runner, progress_reporter, done=True) + + if air_verbosity is not None: + _report_air_progress(runner, air_progress_reporter, force=True) + + all_trials = runner.get_trials() + + runner.cleanup() + + incomplete_trials = [] + for trial in all_trials: + if trial.status != Trial.TERMINATED: + incomplete_trials += [trial] + + if incomplete_trials: + if raise_on_failed_trial and not experiment_interrupted_event.is_set(): + raise TuneError("Trials did not complete", incomplete_trials) + else: + logger.error("Trials did not complete: %s", incomplete_trials) + + all_taken = time.time() - all_start + if has_verbosity(Verbosity.V1_EXPERIMENT): + logger.info( + f"Total run time: {all_taken:.2f} seconds " + f"({tune_taken:.2f} seconds for the tuning loop)." + ) + + if experiment_interrupted_event.is_set(): + restore_entrypoint = error_message_map["restore_entrypoint"].format( + path=runner.experiment_path, + ) + if _entrypoint == AirEntrypoint.TRAINER: + logger.warning( + f"Training has been interrupted, but the most recent state was saved.\n" + f"Resume training with: {restore_entrypoint}" + ) + else: + logger.warning( + f"Experiment has been interrupted, but the most recent state was " + f"saved.\nResume experiment with: {restore_entrypoint}" + ) + + return ExperimentAnalysis( + experiment_checkpoint_path=runner.experiment_path, + default_metric=metric, + default_mode=mode, + trials=all_trials, + storage_filesystem=experiments[0].storage.storage_filesystem, + ) + + +@PublicAPI +def run_experiments( + experiments: Union[Experiment, Mapping, Sequence[Union[Experiment, Mapping]]], + scheduler: Optional[TrialScheduler] = None, + verbose: Optional[Union[int, AirVerbosity, Verbosity]] = None, + progress_reporter: Optional[ProgressReporter] = None, + resume: Optional[Union[bool, str]] = None, + resume_config: Optional[ResumeConfig] = None, + reuse_actors: bool = False, + raise_on_failed_trial: bool = True, + concurrent: bool = True, + callbacks: Optional[Sequence[Callback]] = None, + _remote: Optional[bool] = None, +): + """Runs and blocks until all trials finish. + + Example: + >>> from ray.tune.experiment import Experiment + >>> from ray.tune.tune import run_experiments + >>> def my_func(config): return {"score": 0} + >>> experiment_spec = Experiment("experiment", my_func) # doctest: +SKIP + >>> run_experiments(experiments=experiment_spec) # doctest: +SKIP + >>> experiment_spec = {"experiment": {"run": my_func}} # doctest: +SKIP + >>> run_experiments(experiments=experiment_spec) # doctest: +SKIP + + Returns: + List of Trial objects, holding data for each executed trial. + + """ + if _remote is None: + _remote = ray.util.client.ray.is_connected() + + _ray_auto_init(entrypoint="tune.run_experiments(...)") + + if verbose is None: + # Default `verbose` value. For new output engine, this is AirVerbosity.VERBOSE. + # For old output engine, this is Verbosity.V3_TRIAL_DETAILS + verbose = get_air_verbosity(AirVerbosity.VERBOSE) or Verbosity.V3_TRIAL_DETAILS + + if _remote: + if get_air_verbosity(verbose) is not None: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Ray client is not supported by the new engine. " + "For more information, see " + "https://github.com/ray-project/ray/issues/36949" + ) + remote_run = ray.remote(num_cpus=0)(run_experiments) + + # Make sure tune.run_experiments is run on the server node. + remote_run = _force_on_current_node(remote_run) + + return ray.get( + remote_run.remote( + experiments, + scheduler, + verbose, + progress_reporter, + resume, + resume_config, + reuse_actors, + raise_on_failed_trial, + concurrent, + callbacks, + _remote=False, + ) + ) + + # This is important to do this here + # because it schematize the experiments + # and it conducts the implicit registration. + experiments = _convert_to_experiment_list(experiments) + + tune_run_params = dict( + verbose=verbose, + progress_reporter=progress_reporter, + resume=resume, + resume_config=resume_config, + reuse_actors=reuse_actors, + raise_on_failed_trial=raise_on_failed_trial, + scheduler=scheduler, + callbacks=callbacks, + _entrypoint=AirEntrypoint.TUNE_RUN_EXPERIMENTS, + ) + + if concurrent: + return run(experiments, **tune_run_params).trials + else: + trials = [] + for exp in experiments: + trials += run(exp, **tune_run_params).trials + return trials diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tune_config.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tune_config.py new file mode 100644 index 0000000000000000000000000000000000000000..ebaba70cdef8ee9495406bed1d6db30b74a1ac26 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tune_config.py @@ -0,0 +1,99 @@ +import datetime +from dataclasses import dataclass +from enum import Enum +from typing import Callable, Optional, Union + +from ray.train.constants import _DEPRECATED_VALUE +from ray.tune.experiment.trial import Trial +from ray.tune.schedulers import TrialScheduler +from ray.tune.search import SearchAlgorithm, Searcher +from ray.util.annotations import DeveloperAPI, PublicAPI + + +@dataclass +@PublicAPI(stability="beta") +class TuneConfig: + """Tune specific configs. + + Args: + metric: Metric to optimize. This metric should be reported + with `tune.report()`. If set, will be passed to the search + algorithm and scheduler. + mode: Must be one of [min, max]. Determines whether objective is + minimizing or maximizing the metric attribute. If set, will be + passed to the search algorithm and scheduler. + search_alg: Search algorithm for optimization. Default to + random search. + scheduler: Scheduler for executing the experiment. + Choose among FIFO (default), MedianStopping, + AsyncHyperBand, HyperBand and PopulationBasedTraining. Refer to + ray.tune.schedulers for more options. + num_samples: Number of times to sample from the + hyperparameter space. Defaults to 1. If `grid_search` is + provided as an argument, the grid will be repeated + `num_samples` of times. If this is -1, (virtually) infinite + samples are generated until a stopping condition is met. + max_concurrent_trials: Maximum number of trials to run + concurrently. Must be non-negative. If None or 0, no limit will + be applied. This is achieved by wrapping the ``search_alg`` in + a :class:`ConcurrencyLimiter`, and thus setting this argument + will raise an exception if the ``search_alg`` is already a + :class:`ConcurrencyLimiter`. Defaults to None. + time_budget_s: Global time budget in + seconds after which all trials are stopped. Can also be a + ``datetime.timedelta`` object. + reuse_actors: Whether to reuse actors between different trials + when possible. This can drastically speed up experiments that start + and stop actors often (e.g., PBT in time-multiplexing mode). This + requires trials to have the same resource requirements. + Defaults to ``False``. + trial_name_creator: Optional function that takes in a Trial and returns + its name (i.e. its string representation). Be sure to include some unique + identifier (such as `Trial.trial_id`) in each trial's name. + NOTE: This API is in alpha and subject to change. + trial_dirname_creator: Optional function that takes in a trial and + generates its trial directory name as a string. Be sure to include some + unique identifier (such as `Trial.trial_id`) is used in each trial's + directory name. Otherwise, trials could overwrite artifacts and checkpoints + of other trials. The return value cannot be a path. + NOTE: This API is in alpha and subject to change. + chdir_to_trial_dir: Deprecated. Set the `RAY_CHDIR_TO_TRIAL_DIR` env var instead + """ + + # Currently this is not at feature parity with `tune.run`, nor should it be. + # The goal is to reach a fine balance between API flexibility and conciseness. + # We should carefully introduce arguments here instead of just dumping everything. + mode: Optional[str] = None + metric: Optional[str] = None + search_alg: Optional[Union[Searcher, SearchAlgorithm]] = None + scheduler: Optional[TrialScheduler] = None + num_samples: int = 1 + max_concurrent_trials: Optional[int] = None + time_budget_s: Optional[Union[int, float, datetime.timedelta]] = None + reuse_actors: bool = False + trial_name_creator: Optional[Callable[[Trial], str]] = None + trial_dirname_creator: Optional[Callable[[Trial], str]] = None + chdir_to_trial_dir: bool = _DEPRECATED_VALUE + + +@DeveloperAPI +@dataclass +class ResumeConfig: + """[Experimental] This config is used to specify how to resume Tune trials.""" + + class ResumeType(Enum): + """An enumeration to define resume types for various trial states. + + Members: + RESUME: Resume from the latest checkpoint. + RESTART: Restart from the beginning (with no checkpoint). + SKIP: Skip this trial when resuming by treating it as terminated. + """ + + RESUME = "resume" + RESTART = "restart" + SKIP = "skip" + + finished: str = ResumeType.SKIP + unfinished: str = ResumeType.RESUME + errored: str = ResumeType.SKIP diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tuner.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tuner.py new file mode 100644 index 0000000000000000000000000000000000000000..b4012f93d56056e5f82c552ee39317ba77e65db1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/tune/tuner.py @@ -0,0 +1,402 @@ +import logging +import os +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Type, Union + +import pyarrow.fs + +import ray +from ray.air._internal.usage import AirEntrypoint +from ray.air.util.node import _force_on_current_node +from ray.train._internal.storage import _exists_at_fs_path, get_fs_and_path +from ray.tune import ResumeConfig, RunConfig +from ray.tune.experimental.output import get_air_verbosity +from ray.tune.impl.tuner_internal import _TUNER_PKL, TunerInternal +from ray.tune.progress_reporter import ( + _prepare_progress_reporter_for_ray_client, + _stream_client_output, +) +from ray.tune.result_grid import ResultGrid +from ray.tune.trainable import Trainable +from ray.tune.tune_config import TuneConfig +from ray.util import PublicAPI + +logger = logging.getLogger(__name__) + +if TYPE_CHECKING: + from ray.train.base_trainer import BaseTrainer + +ClientActorHandle = Any + +# try: +# # Breaks lint right now. +# from ray.util.client.common import ClientActorHandle +# except Exception: +# pass + +# The magic key that is used when instantiating Tuner during resume. +_TUNER_INTERNAL = "_tuner_internal" +_SELF = "self" + + +@PublicAPI(stability="beta") +class Tuner: + """Tuner is the recommended way of launching hyperparameter tuning jobs with Ray Tune. + + Args: + trainable: The trainable to be tuned. + param_space: Search space of the tuning job. See :ref:`tune-search-space-tutorial`. + tune_config: Tuning specific configs, such as setting custom + :ref:`search algorithms ` and + :ref:`trial scheduling algorithms `. + run_config: Job-level run configuration, which includes configs for + persistent storage, checkpointing, fault tolerance, etc. + + Usage pattern: + + .. code-block:: python + + import ray.tune + + def trainable(config): + # Your training logic here + ray.tune.report({"accuracy": 0.8}) + + tuner = Tuner( + trainable=trainable, + param_space={"lr": ray.tune.grid_search([0.001, 0.01])}, + run_config=ray.tune.RunConfig(name="my_tune_run"), + ) + results = tuner.fit() + + To retry a failed Tune run, you can then do + + .. code-block:: python + + tuner = Tuner.restore(results.experiment_path, trainable=trainable) + tuner.fit() + + ``results.experiment_path`` can be retrieved from the + :ref:`ResultGrid object `. It can + also be easily seen in the log output from your first run. + + """ + + # One of the following is assigned. + _local_tuner: Optional[TunerInternal] # Only used in none ray client mode. + _remote_tuner: Optional[ClientActorHandle] # Only used in ray client mode. + + def __init__( + self, + trainable: Optional[ + Union[str, Callable, Type[Trainable], "BaseTrainer"] + ] = None, + *, + param_space: Optional[Dict[str, Any]] = None, + tune_config: Optional[TuneConfig] = None, + run_config: Optional[RunConfig] = None, + # This is internal only arg. + # Only for dogfooding purposes. We can slowly promote these args + # to RunConfig or TuneConfig as needed. + # TODO(xwjiang): Remove this later. + _tuner_kwargs: Optional[Dict] = None, + _tuner_internal: Optional[TunerInternal] = None, + _entrypoint: AirEntrypoint = AirEntrypoint.TUNER, + ): + """Configure and construct a tune run.""" + kwargs = locals().copy() + self._is_ray_client = ray.util.client.ray.is_connected() + if self._is_ray_client: + _run_config = run_config or RunConfig() + if get_air_verbosity(_run_config.verbose) is not None: + logger.info( + "[output] This uses the legacy output and progress reporter, " + "as Ray client is not supported by the new engine. " + "For more information, see " + "https://github.com/ray-project/ray/issues/36949" + ) + + if _tuner_internal: + if not self._is_ray_client: + self._local_tuner = kwargs[_TUNER_INTERNAL] + else: + self._remote_tuner = kwargs[_TUNER_INTERNAL] + else: + kwargs.pop(_TUNER_INTERNAL, None) + kwargs.pop(_SELF, None) + if not self._is_ray_client: + self._local_tuner = TunerInternal(**kwargs) + else: + self._remote_tuner = _force_on_current_node( + ray.remote(num_cpus=0)(TunerInternal) + ).remote(**kwargs) + + @classmethod + def restore( + cls, + path: str, + trainable: Union[str, Callable, Type[Trainable], "BaseTrainer"], + resume_unfinished: bool = True, + resume_errored: bool = False, + restart_errored: bool = False, + param_space: Optional[Dict[str, Any]] = None, + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + _resume_config: Optional[ResumeConfig] = None, + ) -> "Tuner": + """Restores Tuner after a previously failed run. + + All trials from the existing run will be added to the result table. The + argument flags control how existing but unfinished or errored trials are + resumed. + + Finished trials are always added to the overview table. They will not be + resumed. + + Unfinished trials can be controlled with the ``resume_unfinished`` flag. + If ``True`` (default), they will be continued. If ``False``, they will + be added as terminated trials (even if they were only created and never + trained). + + Errored trials can be controlled with the ``resume_errored`` and + ``restart_errored`` flags. The former will resume errored trials from + their latest checkpoints. The latter will restart errored trials from + scratch and prevent loading their last checkpoints. + + .. note:: + + Restoring an experiment from a path that's pointing to a *different* + location than the original experiment path is supported. + However, Ray Tune assumes that the full experiment directory is available + (including checkpoints) so that it's possible to resume trials from their + latest state. + + For example, if the original experiment path was run locally, + then the results are uploaded to cloud storage, Ray Tune expects the full + contents to be available in cloud storage if attempting to resume + via ``Tuner.restore("s3://...")``. The restored run will continue + writing results to the same cloud storage location. + + Args: + path: The local or remote path of the experiment directory + for an interrupted or failed run. + Note that an experiment where all trials finished will not be resumed. + This information could be easily located near the end of the + console output of previous run. + trainable: The trainable to use upon resuming the experiment. + This should be the same trainable that was used to initialize + the original Tuner. + param_space: The same `param_space` that was passed to + the original Tuner. This can be optionally re-specified due + to the `param_space` potentially containing Ray object + references (tuning over Datasets or tuning over + several `ray.put` object references). **Tune expects the + `param_space` to be unmodified**, and the only part that + will be used during restore are the updated object references. + Changing the hyperparameter search space then resuming is NOT + supported by this API. + resume_unfinished: If True, will continue to run unfinished trials. + resume_errored: If True, will re-schedule errored trials and try to + restore from their latest checkpoints. + restart_errored: If True, will re-schedule errored trials but force + restarting them from scratch (no checkpoint will be loaded). + storage_filesystem: Custom ``pyarrow.fs.FileSystem`` + corresponding to the ``path``. This may be necessary if the original + experiment passed in a custom filesystem. + _resume_config: [Experimental] Config object that controls how to resume + trials of different statuses. Can be used as a substitute to + `resume_*` and `restart_*` flags above. + """ + unfinished = ( + ResumeConfig.ResumeType.RESUME + if resume_unfinished + else ResumeConfig.ResumeType.SKIP + ) + errored = ResumeConfig.ResumeType.SKIP + if resume_errored: + errored = ResumeConfig.ResumeType.RESUME + elif restart_errored: + errored = ResumeConfig.ResumeType.RESTART + + resume_config = _resume_config or ResumeConfig( + unfinished=unfinished, errored=errored + ) + + if not ray.util.client.ray.is_connected(): + tuner_internal = TunerInternal( + restore_path=path, + resume_config=resume_config, + trainable=trainable, + param_space=param_space, + storage_filesystem=storage_filesystem, + ) + return Tuner(_tuner_internal=tuner_internal) + else: + tuner_internal = _force_on_current_node( + ray.remote(num_cpus=0)(TunerInternal) + ).remote( + restore_path=path, + resume_config=resume_config, + trainable=trainable, + param_space=param_space, + storage_filesystem=storage_filesystem, + ) + return Tuner(_tuner_internal=tuner_internal) + + @classmethod + def can_restore( + cls, + path: Union[str, os.PathLike], + storage_filesystem: Optional[pyarrow.fs.FileSystem] = None, + ) -> bool: + """Checks whether a given directory contains a restorable Tune experiment. + + Usage Pattern: + + Use this utility to switch between starting a new Tune experiment + and restoring when possible. This is useful for experiment fault-tolerance + when re-running a failed tuning script. + + .. code-block:: python + + import os + + from ray.tune import Tuner, RunConfig + + def train_fn(config): + # Make sure to implement checkpointing so that progress gets + # saved on restore. + pass + + name = "exp_name" + storage_path = os.path.expanduser("~/ray_results") + exp_dir = os.path.join(storage_path, name) + + if Tuner.can_restore(exp_dir): + tuner = Tuner.restore( + exp_dir, + trainable=train_fn, + resume_errored=True, + ) + else: + tuner = Tuner( + train_fn, + run_config=RunConfig(name=name, storage_path=storage_path), + ) + tuner.fit() + + Args: + path: The path to the experiment directory of the Tune experiment. + This can be either a local directory or a remote URI + (e.g. s3://bucket/exp_name). + + Returns: + bool: True if this path exists and contains the Tuner state to resume from + """ + fs, fs_path = get_fs_and_path(path, storage_filesystem) + return _exists_at_fs_path(fs, Path(fs_path, _TUNER_PKL).as_posix()) + + def _prepare_remote_tuner_for_jupyter_progress_reporting(self): + run_config: RunConfig = ray.get(self._remote_tuner.get_run_config.remote()) + progress_reporter, string_queue = _prepare_progress_reporter_for_ray_client( + run_config.progress_reporter, run_config.verbose + ) + run_config.progress_reporter = progress_reporter + ray.get( + self._remote_tuner.set_run_config_and_remote_string_queue.remote( + run_config, string_queue + ) + ) + + return progress_reporter, string_queue + + def fit(self) -> ResultGrid: + """Executes hyperparameter tuning job as configured and returns result. + + Failure handling: + For the kind of exception that happens during the execution of a trial, + one may inspect it together with stacktrace through the returned result grid. + See ``ResultGrid`` for reference. Each trial may fail up to a certain number. + This is configured by ``RunConfig.FailureConfig.max_failures``. + + Exception that happens beyond trials will be thrown by this method as well. + In such cases, there will be instruction like the following printed out + at the end of console output to inform users on how to resume. + + Please use `Tuner.restore` to resume. + + .. code-block:: python + + import os + from ray.tune import Tuner + + trainable = ... + + tuner = Tuner.restore( + os.path.expanduser("~/ray_results/tuner_resume"), + trainable=trainable + ) + tuner.fit() + + Raises: + RayTaskError: If user-provided trainable raises an exception + """ + + if not self._is_ray_client: + return self._local_tuner.fit() + else: + ( + progress_reporter, + string_queue, + ) = self._prepare_remote_tuner_for_jupyter_progress_reporting() + fit_future = self._remote_tuner.fit.remote() + _stream_client_output( + fit_future, + progress_reporter, + string_queue, + ) + return ray.get(fit_future) + + def get_results(self) -> ResultGrid: + """Get results of a hyperparameter tuning run. + + This method returns the same results as :meth:`~ray.tune.Tuner.fit` + and can be used to retrieve the results after restoring a tuner without + calling ``fit()`` again. + + If the tuner has not been fit before, an error will be raised. + + .. code-block:: python + + from ray.tune import Tuner + + # `trainable` is what was passed in to the original `Tuner` + tuner = Tuner.restore("/path/to/experiment', trainable=trainable) + results = tuner.get_results() + + Returns: + Result grid of a previously fitted tuning run. + + """ + if not self._is_ray_client: + return self._local_tuner.get_results() + else: + ( + progress_reporter, + string_queue, + ) = self._prepare_remote_tuner_for_jupyter_progress_reporting() + get_results_future = self._remote_tuner.get_results.remote() + _stream_client_output( + get_results_future, + progress_reporter, + string_queue, + ) + return ray.get(get_results_future) + + def __getattribute__(self, item): + if item == "restore": + raise AttributeError( + "`Tuner.restore()` is a classmethod and cannot be called on an " + "instance. Use `tuner = Tuner.restore(...)` to instantiate the " + "Tuner instead." + ) + return super().__getattribute__(item) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8b6eae909ab8038a42cb99b9e750ee5fc4fd26 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/__init__.py @@ -0,0 +1,75 @@ +from typing import List + +import ray +from ray._private.client_mode_hook import client_mode_hook +from ray._private.auto_init_hook import wrap_auto_init +from ray._private.services import get_node_instance_id, get_node_ip_address +from ray.util import iter +from ray.util import rpdb as pdb +from ray.util import debugpy as ray_debugpy +from ray.util.actor_pool import ActorPool +from ray.util import accelerators +from ray.util.annotations import PublicAPI +from ray.util.check_serialize import inspect_serializability +from ray.util.client_connect import connect, disconnect +from ray.util.debug import disable_log_once_globally, enable_periodic_logging, log_once +from ray.util.placement_group import ( + get_current_placement_group, + get_placement_group, + placement_group, + placement_group_table, + remove_placement_group, +) +from ray.util.serialization import deregister_serializer, register_serializer + + +@PublicAPI(stability="beta") +@wrap_auto_init +@client_mode_hook +def list_named_actors(all_namespaces: bool = False) -> List[str]: + """List all named actors in the system. + + Actors must have been created with Actor.options(name="name").remote(). + This works for both detached & non-detached actors. + + By default, only actors in the current namespace will be returned + and the returned entries will simply be their name. + + If `all_namespaces` is set to True, all actors in the cluster will be + returned regardless of namespace, and the returned entries will be of the + form {"namespace": namespace, "name": name}. + """ + worker = ray._private.worker.global_worker + worker.check_connected() + + actors = worker.core_worker.list_named_actors(all_namespaces) + if all_namespaces: + return [{"name": name, "namespace": namespace} for namespace, name in actors] + else: + return [name for _, name in actors] + + +__all__ = [ + "accelerators", + "ActorPool", + "disable_log_once_globally", + "enable_periodic_logging", + "iter", + "log_once", + "pdb", + "placement_group", + "placement_group_table", + "get_placement_group", + "get_current_placement_group", + "get_node_instance_id", + "get_node_ip_address", + "remove_placement_group", + "ray_debugpy", + "inspect_serializability", + "collective", + "connect", + "disconnect", + "register_serializer", + "deregister_serializer", + "list_named_actors", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/actor_group.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/actor_group.py new file mode 100644 index 0000000000000000000000000000000000000000..03ffcb1184c29ca703b8639713df4eac745bf933 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/actor_group.py @@ -0,0 +1,230 @@ +import weakref +from dataclasses import dataclass +import logging +from typing import List, TypeVar, Optional, Dict, Type, Tuple + +import ray +from ray.actor import ActorHandle +from ray.util.annotations import Deprecated +from ray._private.utils import get_ray_doc_version + +T = TypeVar("T") +ActorMetadata = TypeVar("ActorMetadata") + +logger = logging.getLogger(__name__) + + +@dataclass +class ActorWrapper: + """Class containing an actor and its metadata.""" + + actor: ActorHandle + metadata: ActorMetadata + + +@dataclass +class ActorConfig: + num_cpus: float + num_gpus: float + resources: Optional[Dict[str, float]] + init_args: Tuple + init_kwargs: Dict + + +class ActorGroupMethod: + def __init__(self, actor_group: "ActorGroup", method_name: str): + self.actor_group = weakref.ref(actor_group) + self._method_name = method_name + + def __call__(self, *args, **kwargs): + raise TypeError( + "ActorGroup methods cannot be called directly. " + "Instead " + f"of running 'object.{self._method_name}()', try " + f"'object.{self._method_name}.remote()'." + ) + + def remote(self, *args, **kwargs): + return [ + getattr(a.actor, self._method_name).remote(*args, **kwargs) + for a in self.actor_group().actors + ] + + +@Deprecated( + message="For stateless/task processing, use ray.util.multiprocessing, see details " + f"in https://docs.ray.io/en/{get_ray_doc_version()}/ray-more-libs/multiprocessing.html. " # noqa: E501 + "For stateful/actor processing such as batch prediction, use " + "Datasets.map_batches(compute=ActorPoolStrategy, ...), see details in " + f"https://docs.ray.io/en/{get_ray_doc_version()}/data/api/dataset.html#ray.data.Dataset.map_batches.", # noqa: E501 + warning=True, +) +class ActorGroup: + """Group of Ray Actors that can execute arbitrary functions. + + ``ActorGroup`` launches Ray actors according to the given + specification. It can then execute arbitrary Python functions in each of + these actors. + + If not enough resources are available to launch the actors, the Ray + cluster will automatically scale up if autoscaling is enabled. + + Args: + actor_cls: The class to use as the remote actors. + num_actors: The number of the provided Ray actors to + launch. Defaults to 1. + num_cpus_per_actor: The number of CPUs to reserve for each + actor. Fractional values are allowed. Defaults to 1. + num_gpus_per_actor: The number of GPUs to reserve for each + actor. Fractional values are allowed. Defaults to 0. + resources_per_actor (Optional[Dict[str, float]]): + Dictionary specifying the resources that will be + requested for each actor in addition to ``num_cpus_per_actor`` + and ``num_gpus_per_actor``. + init_args, init_kwargs: If ``actor_cls`` is provided, + these args will be used for the actor initialization. + + """ + + def __init__( + self, + actor_cls: Type, + num_actors: int = 1, + num_cpus_per_actor: float = 1, + num_gpus_per_actor: float = 0, + resources_per_actor: Optional[Dict[str, float]] = None, + init_args: Optional[Tuple] = None, + init_kwargs: Optional[Dict] = None, + ): + from ray._private.usage.usage_lib import record_library_usage + + record_library_usage("util.ActorGroup") + + if num_actors <= 0: + raise ValueError( + "The provided `num_actors` must be greater " + f"than 0. Received num_actors={num_actors} " + f"instead." + ) + if num_cpus_per_actor < 0 or num_gpus_per_actor < 0: + raise ValueError( + "The number of CPUs and GPUs per actor must " + "not be negative. Received " + f"num_cpus_per_actor={num_cpus_per_actor} and " + f"num_gpus_per_actor={num_gpus_per_actor}." + ) + + self.actors = [] + + self.num_actors = num_actors + + self.actor_config = ActorConfig( + num_cpus=num_cpus_per_actor, + num_gpus=num_gpus_per_actor, + resources=resources_per_actor, + init_args=init_args or (), + init_kwargs=init_kwargs or {}, + ) + + self._remote_cls = ray.remote( + num_cpus=self.actor_config.num_cpus, + num_gpus=self.actor_config.num_gpus, + resources=self.actor_config.resources, + )(actor_cls) + + self.start() + + def __getattr__(self, item): + if len(self.actors) == 0: + raise RuntimeError( + "This ActorGroup has been shutdown. Please start it again." + ) + # Same implementation as actor.py + return ActorGroupMethod(self, item) + + def __len__(self): + return len(self.actors) + + def __getitem__(self, item): + return self.actors[item] + + def start(self): + """Starts all the actors in this actor group.""" + if self.actors and len(self.actors) > 0: + raise RuntimeError( + "The actors have already been started. " + "Please call `shutdown` first if you want to " + "restart them." + ) + + logger.debug(f"Starting {self.num_actors} actors.") + self.add_actors(self.num_actors) + logger.debug(f"{len(self.actors)} actors have successfully started.") + + def shutdown(self, patience_s: float = 5): + """Shutdown all the actors in this actor group. + + Args: + patience_s: Attempt a graceful shutdown + of the actors for this many seconds. Fallback to force kill + if graceful shutdown is not complete after this time. If + this is less than or equal to 0, immediately force kill all + actors. + """ + logger.debug(f"Shutting down {len(self.actors)} actors.") + if patience_s <= 0: + for actor in self.actors: + ray.kill(actor.actor) + else: + done_refs = [w.actor.__ray_terminate__.remote() for w in self.actors] + # Wait for actors to die gracefully. + done, not_done = ray.wait(done_refs, timeout=patience_s) + if not_done: + logger.debug("Graceful termination failed. Falling back to force kill.") + # If all actors are not able to die gracefully, then kill them. + for actor in self.actors: + ray.kill(actor.actor) + + logger.debug("Shutdown successful.") + self.actors = [] + + def remove_actors(self, actor_indexes: List[int]): + """Removes the actors with the specified indexes. + + Args: + actor_indexes (List[int]): The indexes of the actors to remove. + """ + new_actors = [] + for i in range(len(self.actors)): + if i not in actor_indexes: + new_actors.append(self.actors[i]) + self.actors = new_actors + + def add_actors(self, num_actors: int): + """Adds ``num_actors`` to this ActorGroup. + + Args: + num_actors: The number of actors to add. + """ + new_actors = [] + new_actor_metadata = [] + for _ in range(num_actors): + actor = self._remote_cls.remote( + *self.actor_config.init_args, **self.actor_config.init_kwargs + ) + new_actors.append(actor) + if hasattr(actor, "get_actor_metadata"): + new_actor_metadata.append(actor.get_actor_metadata.remote()) + + # Get metadata from all actors. + metadata = ray.get(new_actor_metadata) + + if len(metadata) == 0: + metadata = [None] * len(new_actors) + + for i in range(len(new_actors)): + self.actors.append(ActorWrapper(actor=new_actors[i], metadata=metadata[i])) + + @property + def actor_metadata(self): + return [a.metadata for a in self.actors] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/actor_pool.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/actor_pool.py new file mode 100644 index 0000000000000000000000000000000000000000..96eedfe29af1fc2a8289602ec2f37a722e967570 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/actor_pool.py @@ -0,0 +1,463 @@ +from typing import TYPE_CHECKING, Any, Callable, List, TypeVar + +import ray +from ray.util.annotations import DeveloperAPI + +if TYPE_CHECKING: + import ray.actor + +V = TypeVar("V") + + +@DeveloperAPI +class ActorPool: + """Utility class to operate on a fixed pool of actors. + + Arguments: + actors: List of Ray actor handles to use in this pool. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1, a2]) + print(list(pool.map(lambda a, v: a.double.remote(v), + [1, 2, 3, 4]))) + + .. testoutput:: + + [2, 4, 6, 8] + """ + + def __init__(self, actors: list): + from ray._private.usage.usage_lib import record_library_usage + + record_library_usage("util.ActorPool") + + # actors to be used + self._idle_actors = list(actors) + + # get actor from future + self._future_to_actor = {} + + # get future from index + self._index_to_future = {} + + # next task to do + self._next_task_index = 0 + + # next task to return + self._next_return_index = 0 + + # next work depending when actors free + self._pending_submits = [] + + def map(self, fn: Callable[["ray.actor.ActorHandle", V], Any], values: List[V]): + """Apply the given function in parallel over the actors and values. + + This returns an ordered iterator that will return results of the map + as they finish. Note that you must iterate over the iterator to force + the computation to finish. + + Arguments: + fn: Function that takes (actor, value) as argument and + returns an ObjectRef computing the result over the value. The + actor will be considered busy until the ObjectRef completes. + values: List of values that fn(actor, value) should be + applied to. + + Returns: + Iterator over results from applying fn to the actors and values. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1, a2]) + print(list(pool.map(lambda a, v: a.double.remote(v), + [1, 2, 3, 4]))) + + .. testoutput:: + + [2, 4, 6, 8] + """ + # Ignore/Cancel all the previous submissions + # by calling `has_next` and `gen_next` repeteadly. + while self.has_next(): + try: + self.get_next(timeout=0, ignore_if_timedout=True) + except TimeoutError: + pass + + for v in values: + self.submit(fn, v) + + def get_generator(): + while self.has_next(): + yield self.get_next() + + return get_generator() + + def map_unordered( + self, fn: Callable[["ray.actor.ActorHandle", V], Any], values: List[V] + ): + """Similar to map(), but returning an unordered iterator. + + This returns an unordered iterator that will return results of the map + as they finish. This can be more efficient that map() if some results + take longer to compute than others. + + Arguments: + fn: Function that takes (actor, value) as argument and + returns an ObjectRef computing the result over the value. The + actor will be considered busy until the ObjectRef completes. + values: List of values that fn(actor, value) should be + applied to. + + Returns: + Iterator over results from applying fn to the actors and values. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1, a2]) + print(list(pool.map_unordered(lambda a, v: a.double.remote(v), + [1, 2, 3, 4]))) + + .. testoutput:: + :options: +MOCK + + [6, 8, 4, 2] + """ + # Ignore/Cancel all the previous submissions + # by calling `has_next` and `gen_next_unordered` repeteadly. + while self.has_next(): + try: + self.get_next_unordered(timeout=0) + except TimeoutError: + pass + + for v in values: + self.submit(fn, v) + + def get_generator(): + while self.has_next(): + yield self.get_next_unordered() + + return get_generator() + + def submit(self, fn, value): + """Schedule a single task to run in the pool. + + This has the same argument semantics as map(), but takes on a single + value instead of a list of values. The result can be retrieved using + get_next() / get_next_unordered(). + + Arguments: + fn: Function that takes (actor, value) as argument and + returns an ObjectRef computing the result over the value. The + actor will be considered busy until the ObjectRef completes. + value: Value to compute a result for. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1, a2]) + pool.submit(lambda a, v: a.double.remote(v), 1) + pool.submit(lambda a, v: a.double.remote(v), 2) + print(pool.get_next(), pool.get_next()) + + .. testoutput:: + + 2 4 + """ + if self._idle_actors: + actor = self._idle_actors.pop() + future = fn(actor, value) + future_key = tuple(future) if isinstance(future, list) else future + self._future_to_actor[future_key] = (self._next_task_index, actor) + self._index_to_future[self._next_task_index] = future + self._next_task_index += 1 + else: + self._pending_submits.append((fn, value)) + + def has_next(self): + """Returns whether there are any pending results to return. + + Returns: + True if there are any pending results not yet returned. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1, a2]) + pool.submit(lambda a, v: a.double.remote(v), 1) + print(pool.has_next()) + print(pool.get_next()) + print(pool.has_next()) + + .. testoutput:: + + True + 2 + False + """ + return bool(self._future_to_actor) + + def get_next(self, timeout=None, ignore_if_timedout=False): + """Returns the next pending result in order. + + This returns the next result produced by submit(), blocking for up to + the specified timeout until it is available. + + Returns: + The next result. + + Raises: + TimeoutError: if the timeout is reached. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1, a2]) + pool.submit(lambda a, v: a.double.remote(v), 1) + print(pool.get_next()) + + .. testoutput:: + + 2 + """ + if not self.has_next(): + raise StopIteration("No more results to get") + if self._next_return_index >= self._next_task_index: + raise ValueError( + "It is not allowed to call get_next() after get_next_unordered()." + ) + future = self._index_to_future[self._next_return_index] + timeout_msg = "Timed out waiting for result" + raise_timeout_after_ignore = False + if timeout is not None: + res, _ = ray.wait([future], timeout=timeout) + if not res: + if not ignore_if_timedout: + raise TimeoutError(timeout_msg) + else: + raise_timeout_after_ignore = True + del self._index_to_future[self._next_return_index] + self._next_return_index += 1 + + future_key = tuple(future) if isinstance(future, list) else future + i, a = self._future_to_actor.pop(future_key) + + self._return_actor(a) + if raise_timeout_after_ignore: + raise TimeoutError( + timeout_msg + ". The task {} has been ignored.".format(future) + ) + return ray.get(future) + + def get_next_unordered(self, timeout=None, ignore_if_timedout=False): + """Returns any of the next pending results. + + This returns some result produced by submit(), blocking for up to + the specified timeout until it is available. Unlike get_next(), the + results are not always returned in same order as submitted, which can + improve performance. + + Returns: + The next result. + + Raises: + TimeoutError: if the timeout is reached. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1, a2]) + pool.submit(lambda a, v: a.double.remote(v), 1) + pool.submit(lambda a, v: a.double.remote(v), 2) + print(pool.get_next_unordered()) + print(pool.get_next_unordered()) + + .. testoutput:: + :options: +MOCK + + 4 + 2 + """ + if not self.has_next(): + raise StopIteration("No more results to get") + # TODO(ekl) bulk wait for performance + res, _ = ray.wait(list(self._future_to_actor), num_returns=1, timeout=timeout) + timeout_msg = "Timed out waiting for result" + raise_timeout_after_ignore = False + if res: + [future] = res + else: + if not ignore_if_timedout: + raise TimeoutError(timeout_msg) + else: + raise_timeout_after_ignore = True + i, a = self._future_to_actor.pop(future) + self._return_actor(a) + del self._index_to_future[i] + self._next_return_index = max(self._next_return_index, i + 1) + if raise_timeout_after_ignore: + raise TimeoutError( + timeout_msg + ". The task {} has been ignored.".format(future) + ) + return ray.get(future) + + def _return_actor(self, actor): + self._idle_actors.append(actor) + if self._pending_submits: + self.submit(*self._pending_submits.pop(0)) + + def has_free(self): + """Returns whether there are any idle actors available. + + Returns: + True if there are any idle actors and no pending submits. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1 = Actor.remote() + pool = ActorPool([a1]) + pool.submit(lambda a, v: a.double.remote(v), 1) + print(pool.has_free()) + print(pool.get_next()) + print(pool.has_free()) + + .. testoutput:: + + False + 2 + True + """ + return len(self._idle_actors) > 0 and len(self._pending_submits) == 0 + + def pop_idle(self): + """Removes an idle actor from the pool. + + Returns: + An idle actor if one is available. + None if no actor was free to be removed. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1 = Actor.remote() + pool = ActorPool([a1]) + pool.submit(lambda a, v: a.double.remote(v), 1) + assert pool.pop_idle() is None + assert pool.get_next() == 2 + assert pool.pop_idle() == a1 + + """ + if self.has_free(): + return self._idle_actors.pop() + return None + + def push(self, actor): + """Pushes a new actor into the current list of idle actors. + + Examples: + .. testcode:: + + import ray + from ray.util.actor_pool import ActorPool + + @ray.remote + class Actor: + def double(self, v): + return 2 * v + + a1, a2 = Actor.remote(), Actor.remote() + pool = ActorPool([a1]) + pool.push(a2) + """ + busy_actors = [] + if self._future_to_actor.values(): + _, busy_actors = zip(*self._future_to_actor.values()) + if actor in self._idle_actors or actor in busy_actors: + raise ValueError("Actor already belongs to current ActorPool") + else: + self._return_actor(actor) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/annotations.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/annotations.py new file mode 100644 index 0000000000000000000000000000000000000000..206c02b36d2627828734b9d26b5f5698d8f3b219 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/annotations.py @@ -0,0 +1,268 @@ +from enum import Enum +from typing import Optional +import inspect +import sys +import warnings +from functools import wraps + + +class AnnotationType(Enum): + PUBLIC_API = "PublicAPI" + DEVELOPER_API = "DeveloperAPI" + DEPRECATED = "Deprecated" + UNKNOWN = "Unknown" + + +def PublicAPI(*args, **kwargs): + """Annotation for documenting public APIs. + + Public APIs are classes and methods exposed to end users of Ray. + + If ``stability="alpha"``, the API can be used by advanced users who are + tolerant to and expect breaking changes. + + If ``stability="beta"``, the API is still public and can be used by early + users, but are subject to change. + + If ``stability="stable"``, the APIs will remain backwards compatible across + minor Ray releases (e.g., Ray 1.4 -> 1.8). + + For a full definition of the stability levels, please refer to the + :ref:`Ray API Stability definitions `. + + Args: + stability: One of {"stable", "beta", "alpha"}. + api_group: Optional. Used only for doc rendering purpose. APIs in the same group + will be grouped together in the API doc pages. + + Examples: + >>> from ray.util.annotations import PublicAPI + >>> @PublicAPI + ... def func(x): + ... return x + + >>> @PublicAPI(stability="beta") + ... def func(y): + ... return y + """ + if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): + return PublicAPI(stability="stable", api_group="Others")(args[0]) + + if "stability" in kwargs: + stability = kwargs["stability"] + assert stability in ["stable", "beta", "alpha"], stability + else: + stability = "stable" + api_group = kwargs.get("api_group", "Others") + + def wrap(obj): + if stability in ["alpha", "beta"]: + message = ( + f"**PublicAPI ({stability}):** This API is in {stability} " + "and may change before becoming stable." + ) + _append_doc(obj, message=message) + + _mark_annotated(obj, type=AnnotationType.PUBLIC_API, api_group=api_group) + return obj + + return wrap + + +def DeveloperAPI(*args, **kwargs): + """Annotation for documenting developer APIs. + + Developer APIs are lower-level methods explicitly exposed to advanced Ray + users and library developers. Their interfaces may change across minor + Ray releases. + + Examples: + >>> from ray.util.annotations import DeveloperAPI + >>> @DeveloperAPI + ... def func(x): + ... return x + """ + if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): + return DeveloperAPI()(args[0]) + + def wrap(obj): + _append_doc( + obj, + message="**DeveloperAPI:** This API may change across minor Ray releases.", + ) + _mark_annotated(obj, type=AnnotationType.DEVELOPER_API) + return obj + + return wrap + + +class RayDeprecationWarning(DeprecationWarning): + """Specialized Deprecation Warning for fine grained filtering control""" + + pass + + +# By default, print the first occurrence of matching warnings for +# each module where the warning is issued (regardless of line number) +if not sys.warnoptions: + warnings.filterwarnings("module", category=RayDeprecationWarning) + + +def Deprecated(*args, **kwargs): + """Annotation for documenting a deprecated API. + + Deprecated APIs may be removed in future releases of Ray. + + Args: + message: a message to help users understand the reason for the + deprecation, and provide a migration path. + + Examples: + >>> from ray.util.annotations import Deprecated + >>> @Deprecated + ... def func(x): + ... return x + + >>> @Deprecated(message="g() is deprecated because the API is error " + ... "prone. Please call h() instead.") + ... def g(y): + ... return y + """ + if len(args) == 1 and len(kwargs) == 0 and callable(args[0]): + return Deprecated()(args[0]) + + doc_message = ( + "**DEPRECATED**: This API is deprecated and may be removed " + "in future Ray releases." + ) + warning_message = ( + "This API is deprecated and may be removed in future Ray releases. " + "You could suppress this warning by setting env variable " + 'PYTHONWARNINGS="ignore::DeprecationWarning"' + ) + + warning = kwargs.pop("warning", False) + + if "message" in kwargs: + doc_message = doc_message + "\n" + kwargs["message"] + warning_message = warning_message + "\n" + kwargs["message"] + del kwargs["message"] + + if kwargs: + raise ValueError("Unknown kwargs: {}".format(kwargs.keys())) + + def inner(obj): + _append_doc(obj, message=doc_message, directive="warning") + _mark_annotated(obj, type=AnnotationType.DEPRECATED) + + if not warning: + return obj + + if inspect.isclass(obj): + obj_init = obj.__init__ + + def patched_init(*args, **kwargs): + warnings.warn(warning_message, RayDeprecationWarning, stacklevel=2) + return obj_init(*args, **kwargs) + + obj.__init__ = patched_init + return obj + else: + # class method or function. + @wraps(obj) + def wrapper(*args, **kwargs): + warnings.warn(warning_message, RayDeprecationWarning, stacklevel=2) + return obj(*args, **kwargs) + + return wrapper + + return inner + + +def _append_doc(obj, *, message: str, directive: Optional[str] = None) -> str: + if not obj.__doc__: + obj.__doc__ = "" + + obj.__doc__ = obj.__doc__.rstrip() + + indent = _get_indent(obj.__doc__) + obj.__doc__ += "\n\n" + + if directive is not None: + obj.__doc__ += f"{' ' * indent}.. {directive}::\n\n" + + message = message.replace("\n", "\n" + " " * (indent + 4)) + obj.__doc__ += f"{' ' * (indent + 4)}{message}" + else: + message = message.replace("\n", "\n" + " " * (indent + 4)) + obj.__doc__ += f"{' ' * indent}{message}" + obj.__doc__ += f"\n{' ' * indent}" + + +def _get_indent(docstring: str) -> int: + """ + + Example: + >>> def f(): + ... '''Docstring summary.''' + >>> f.__doc__ + 'Docstring summary.' + >>> _get_indent(f.__doc__) + 0 + + >>> def g(foo): + ... '''Docstring summary. + ... + ... Args: + ... foo: Does bar. + ... ''' + >>> g.__doc__ + 'Docstring summary.\\n\\n Args:\\n foo: Does bar.\\n ' + >>> _get_indent(g.__doc__) + 4 + + >>> class A: + ... def h(): + ... '''Docstring summary. + ... + ... Returns: + ... None. + ... ''' + >>> A.h.__doc__ + 'Docstring summary.\\n\\n Returns:\\n None.\\n ' + >>> _get_indent(A.h.__doc__) + 8 + """ + if not docstring: + return 0 + + non_empty_lines = list(filter(bool, docstring.splitlines())) + if len(non_empty_lines) == 1: + # Docstring contains summary only. + return 0 + + # The docstring summary isn't indented, so check the indentation of the second + # non-empty line. + return len(non_empty_lines[1]) - len(non_empty_lines[1].lstrip()) + + +def _mark_annotated( + obj, type: AnnotationType = AnnotationType.UNKNOWN, api_group="Others" +) -> None: + # Set magic token for check_api_annotations linter. + if hasattr(obj, "__name__"): + obj._annotated = obj.__name__ + obj._annotated_type = type + obj._annotated_api_group = api_group + + +def _is_annotated(obj) -> bool: + # Check the magic token exists and applies to this class (not a subclass). + return hasattr(obj, "_annotated") and obj._annotated == obj.__name__ + + +def _get_annotation_type(obj) -> Optional[str]: + if not _is_annotated(obj): + return None + + return obj._annotated_type.value diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/check_open_ports.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/check_open_ports.py new file mode 100644 index 0000000000000000000000000000000000000000..29c9e03e47405dd85b5cf281e479fad684baea1e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/check_open_ports.py @@ -0,0 +1,179 @@ +"""A CLI utility for check open ports in the Ray cluster. + +See https://www.anyscale.com/blog/update-on-ray-cve-2023-48022-new-verification-tooling-available # noqa: E501 +for more details. +""" +from typing import List, Tuple +import subprocess +import click +import psutil +import urllib +import json + +import ray +from ray.util.annotations import PublicAPI +from ray.autoscaler._private.cli_logger import add_click_logging_options, cli_logger +from ray.autoscaler._private.constants import RAY_PROCESSES +from ray.util.scheduling_strategies import NodeAffinitySchedulingStrategy + + +def _get_ray_ports() -> List[int]: + unique_ports = set() + + process_infos = [] + for proc in psutil.process_iter(["name", "cmdline"]): + try: + process_infos.append((proc, proc.name(), proc.cmdline())) + except psutil.Error: + pass + + for keyword, filter_by_cmd in RAY_PROCESSES: + for candidate in process_infos: + proc, proc_cmd, proc_args = candidate + corpus = proc_cmd if filter_by_cmd else subprocess.list2cmdline(proc_args) + if keyword in corpus: + try: + for connection in proc.connections(): + if connection.status == psutil.CONN_LISTEN: + unique_ports.add(connection.laddr.port) + except psutil.AccessDenied: + cli_logger.info( + "Access denied to process connections for process," + " worker process probably restarted", + proc, + ) + + return sorted(unique_ports) + + +def _check_for_open_ports_from_internet( + service_url: str, ports: List[int] +) -> Tuple[List[int], List[int]]: + request = urllib.request.Request( + method="POST", + url=service_url, + headers={ + "Content-Type": "application/json", + "X-Ray-Open-Port-Check": "1", + }, + data=json.dumps({"ports": ports}).encode("utf-8"), + ) + + response = urllib.request.urlopen(request) + if response.status != 200: + raise RuntimeError( + f"Failed to check with Ray Open Port Service: {response.status}" + ) + response_body = json.load(response) + + publicly_open_ports = response_body.get("open_ports", []) + checked_ports = response_body.get("checked_ports", []) + + return publicly_open_ports, checked_ports + + +def _check_if_exposed_to_internet( + service_url: str, +) -> Tuple[List[int], List[int]]: + return _check_for_open_ports_from_internet(service_url, _get_ray_ports()) + + +def _check_ray_cluster( + service_url: str, +) -> List[Tuple[str, Tuple[List[int], List[int]]]]: + ray.init(ignore_reinit_error=True) + + @ray.remote(num_cpus=0) + def check(node_id, service_url): + return node_id, _check_if_exposed_to_internet(service_url) + + ray_node_ids = [node["NodeID"] for node in ray.nodes() if node["Alive"]] + cli_logger.info( + f"Cluster has {len(ray_node_ids)} node(s)." + " Scheduling tasks on each to check for exposed ports", + ) + + per_node_tasks = { + node_id: ( + check.options( + scheduling_strategy=NodeAffinitySchedulingStrategy( + node_id=node_id, soft=False + ) + ).remote(node_id, service_url) + ) + for node_id in ray_node_ids + } + + results = [] + for node_id, per_node_task in per_node_tasks.items(): + try: + results.append(ray.get(per_node_task)) + except Exception as e: + cli_logger.info(f"Failed to check on node {node_id}: {e}") + + return results + + +@click.command() +@click.option( + "--yes", "-y", is_flag=True, default=False, help="Don't ask for confirmation." +) +@click.option( + "--service-url", + required=False, + type=str, + default="https://ray-open-port-checker.uc.r.appspot.com/open-port-check", + help="The url of service that checks whether submitted ports are open.", +) +@add_click_logging_options +@PublicAPI +def check_open_ports(yes, service_url): + """Check open ports in the local Ray cluster.""" + if not cli_logger.confirm( + yes=yes, + msg=( + "Do you want to check the local Ray cluster" + " for any nodes with ports accessible to the internet?" + ), + _default=True, + ): + cli_logger.info("Exiting without checking as instructed") + return + + cluster_open_ports = _check_ray_cluster(service_url) + + public_nodes = [] + for node_id, (open_ports, checked_ports) in cluster_open_ports: + if open_ports: + cli_logger.info( + f"[🛑] open ports detected open_ports={open_ports!r} node={node_id!r}" + ) + public_nodes.append((node_id, open_ports, checked_ports)) + else: + cli_logger.info( + f"[🟢] No open ports detected " + f"checked_ports={checked_ports!r} node={node_id!r}" + ) + + cli_logger.info("Check complete, results:") + + if public_nodes: + cli_logger.info( + """ +[🛑] An server on the internet was able to open a connection to one of this Ray +cluster's public IP on one of Ray's internal ports. If this is not a false +positive, this is an extremely unsafe configuration for Ray to be running in. +Ray is not meant to be exposed to untrusted clients and will allow them to run +arbitrary code on your machine. + +You should take immediate action to validate this result and if confirmed shut +down your Ray cluster immediately and take appropriate action to remediate its +exposure. Anything either running on this Ray cluster or that this cluster has +had access to could be at risk. + +For guidance on how to operate Ray safely, please review [Ray's security +documentation](https://docs.ray.io/en/latest/ray-security/index.html). +""".strip() + ) + else: + cli_logger.info("[🟢] No open ports detected from any Ray nodes") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/check_serialize.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/check_serialize.py new file mode 100644 index 0000000000000000000000000000000000000000..a9a8377b3a77242fbadabb9684cbf5cb90208875 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/check_serialize.py @@ -0,0 +1,265 @@ +"""A utility for debugging serialization issues.""" +import inspect +from contextlib import contextmanager +from typing import Any, Optional, Set, Tuple + +# Import ray first to use the bundled colorama +import ray # noqa: F401 +import colorama +import ray.cloudpickle as cp +from ray.util.annotations import DeveloperAPI + + +@contextmanager +def _indent(printer): + printer.level += 1 + yield + printer.level -= 1 + + +class _Printer: + def __init__(self, print_file): + self.level = 0 + self.print_file = print_file + + def indent(self): + return _indent(self) + + def print(self, msg): + indent = " " * self.level + print(indent + msg, file=self.print_file) + + +@DeveloperAPI +class FailureTuple: + """Represents the serialization 'frame'. + + Attributes: + obj: The object that fails serialization. + name: The variable name of the object. + parent: The object that references the `obj`. + """ + + def __init__(self, obj: Any, name: str, parent: Any): + self.obj = obj + self.name = name + self.parent = parent + + def __repr__(self): + return f"FailTuple({self.name} [obj={self.obj}, parent={self.parent}])" + + +def _inspect_func_serialization(base_obj, depth, parent, failure_set, printer): + """Adds the first-found non-serializable element to the failure_set.""" + assert inspect.isfunction(base_obj) + closure = inspect.getclosurevars(base_obj) + found = False + if closure.globals: + printer.print( + f"Detected {len(closure.globals)} global variables. " + "Checking serializability..." + ) + + with printer.indent(): + for name, obj in closure.globals.items(): + serializable, _ = _inspect_serializability( + obj, + name=name, + depth=depth - 1, + parent=parent, + failure_set=failure_set, + printer=printer, + ) + found = found or not serializable + if found: + break + + if closure.nonlocals: + printer.print( + f"Detected {len(closure.nonlocals)} nonlocal variables. " + "Checking serializability..." + ) + with printer.indent(): + for name, obj in closure.nonlocals.items(): + serializable, _ = _inspect_serializability( + obj, + name=name, + depth=depth - 1, + parent=parent, + failure_set=failure_set, + printer=printer, + ) + found = found or not serializable + if found: + break + if not found: + printer.print( + f"WARNING: Did not find non-serializable object in {base_obj}. " + "This may be an oversight." + ) + return found + + +def _inspect_generic_serialization(base_obj, depth, parent, failure_set, printer): + """Adds the first-found non-serializable element to the failure_set.""" + assert not inspect.isfunction(base_obj) + functions = inspect.getmembers(base_obj, predicate=inspect.isfunction) + found = False + with printer.indent(): + for name, obj in functions: + serializable, _ = _inspect_serializability( + obj, + name=name, + depth=depth - 1, + parent=parent, + failure_set=failure_set, + printer=printer, + ) + found = found or not serializable + if found: + break + + with printer.indent(): + members = inspect.getmembers(base_obj) + for name, obj in members: + if name.startswith("__") and name.endswith("__") or inspect.isbuiltin(obj): + continue + serializable, _ = _inspect_serializability( + obj, + name=name, + depth=depth - 1, + parent=parent, + failure_set=failure_set, + printer=printer, + ) + found = found or not serializable + if found: + break + if not found: + printer.print( + f"WARNING: Did not find non-serializable object in {base_obj}. " + "This may be an oversight." + ) + return found + + +@DeveloperAPI +def inspect_serializability( + base_obj: Any, + name: Optional[str] = None, + depth: int = 3, + print_file: Optional[Any] = None, +) -> Tuple[bool, Set[FailureTuple]]: + """Identifies what objects are preventing serialization. + + Args: + base_obj: Object to be serialized. + name: Optional name of string. + depth: Depth of the scope stack to walk through. Defaults to 3. + print_file: file argument that will be passed to print(). + + Returns: + bool: True if serializable. + set[FailureTuple]: Set of unserializable objects. + + .. versionadded:: 1.1.0 + + """ + printer = _Printer(print_file) + return _inspect_serializability(base_obj, name, depth, None, None, printer) + + +def _inspect_serializability( + base_obj, name, depth, parent, failure_set, printer +) -> Tuple[bool, Set[FailureTuple]]: + colorama.init() + top_level = False + declaration = "" + found = False + if failure_set is None: + top_level = True + failure_set = set() + declaration = f"Checking Serializability of {base_obj}" + printer.print("=" * min(len(declaration), 80)) + printer.print(declaration) + printer.print("=" * min(len(declaration), 80)) + + if name is None: + name = str(base_obj) + else: + printer.print(f"Serializing '{name}' {base_obj}...") + try: + cp.dumps(base_obj) + return True, failure_set + except Exception as e: + printer.print( + f"{colorama.Fore.RED}!!! FAIL{colorama.Fore.RESET} " f"serialization: {e}" + ) + found = True + try: + if depth == 0: + failure_set.add(FailureTuple(base_obj, name, parent)) + # Some objects may not be hashable, so we skip adding this to the set. + except Exception: + pass + + if depth <= 0: + return False, failure_set + + # TODO: we only differentiate between 'function' and 'object' + # but we should do a better job of diving into something + # more specific like a Type, Object, etc. + if inspect.isfunction(base_obj): + _inspect_func_serialization( + base_obj, + depth=depth, + parent=base_obj, + failure_set=failure_set, + printer=printer, + ) + else: + _inspect_generic_serialization( + base_obj, + depth=depth, + parent=base_obj, + failure_set=failure_set, + printer=printer, + ) + + if not failure_set: + failure_set.add(FailureTuple(base_obj, name, parent)) + + if top_level: + printer.print("=" * min(len(declaration), 80)) + if not failure_set: + printer.print( + "Nothing failed the inspect_serialization test, though " + "serialization did not succeed." + ) + else: + fail_vars = ( + f"\n\n\t{colorama.Style.BRIGHT}" + + "\n".join(str(k) for k in failure_set) + + f"{colorama.Style.RESET_ALL}\n\n" + ) + printer.print( + f"Variable: {fail_vars}was found to be non-serializable. " + "There may be multiple other undetected variables that were " + "non-serializable. " + ) + printer.print( + "Consider either removing the " + "instantiation/imports of these variables or moving the " + "instantiation into the scope of the function/class. " + ) + printer.print("=" * min(len(declaration), 80)) + printer.print( + "Check https://docs.ray.io/en/master/ray-core/objects/serialization.html#troubleshooting for more information." # noqa + ) + printer.print( + "If you have any suggestions on how to improve " + "this error message, please reach out to the " + "Ray developers on github.com/ray-project/ray/issues/" + ) + printer.print("=" * min(len(declaration), 80)) + return not found, failure_set diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/client_connect.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/client_connect.py new file mode 100644 index 0000000000000000000000000000000000000000..c88b86457b0ac0613a1a9c7313041e9a6dca0667 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/client_connect.py @@ -0,0 +1,76 @@ +from typing import Any, Dict, List, Optional, Tuple +import logging + +from ray._private.client_mode_hook import ( + _explicitly_enable_client_mode, + _set_client_hook_status, +) +from ray.job_config import JobConfig +from ray.util.annotations import Deprecated +from ray.util.client import ray +from ray._private.utils import get_ray_doc_version + +logger = logging.getLogger(__name__) + + +@Deprecated( + message="Use ray.init(ray://:) " + "instead. See detailed usage at {}.".format( + f"https://docs.ray.io/en/{get_ray_doc_version()}/ray-core/package-ref.html#ray-init" # noqa: E501 + ) +) +def connect( + conn_str: str, + secure: bool = False, + metadata: List[Tuple[str, str]] = None, + connection_retries: int = 3, + job_config: JobConfig = None, + namespace: str = None, + *, + ignore_version: bool = False, + _credentials: Optional["grpc.ChannelCredentials"] = None, # noqa: F821 + ray_init_kwargs: Optional[Dict[str, Any]] = None, +) -> Dict[str, Any]: + if ray.is_connected(): + ignore_reinit_error = ray_init_kwargs.get("ignore_reinit_error", False) + if ignore_reinit_error: + logger.info( + "Calling ray.init() again after it has already been called. " + "Reusing the existing Ray client connection." + ) + return ray.get_context().client_worker.connection_info() + raise RuntimeError( + "Ray Client is already connected. Maybe you called " + 'ray.init("ray://
    ") twice by accident?' + ) + + # Enable the same hooks that RAY_CLIENT_MODE does, as calling + # ray.init("ray://
    ") is specifically for using client mode. + _set_client_hook_status(True) + _explicitly_enable_client_mode() + + # TODO(barakmich): https://github.com/ray-project/ray/issues/13274 + # for supporting things like cert_path, ca_path, etc and creating + # the correct metadata + conn = ray.connect( + conn_str, + job_config=job_config, + secure=secure, + metadata=metadata, + connection_retries=connection_retries, + namespace=namespace, + ignore_version=ignore_version, + _credentials=_credentials, + ray_init_kwargs=ray_init_kwargs, + ) + return conn + + +@Deprecated( + message="Use ray.shutdown() instead. See detailed usage at {}.".format( + f"https://docs.ray.io/en/{get_ray_doc_version()}/ray-core/package-ref.html#ray-shutdown" # noqa: E501 + ) +) +def disconnect(): + """Disconnects from server; is idempotent.""" + return ray.disconnect() diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/common.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/common.py new file mode 100644 index 0000000000000000000000000000000000000000..081ee03ef25e9678d978e9192040ad19b54b2187 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/common.py @@ -0,0 +1 @@ +INT32_MAX = (2**31) - 1 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/debug.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/debug.py new file mode 100644 index 0000000000000000000000000000000000000000..e5482c7b6d8c73095fd09e0f3f5b4583549d2151 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/debug.py @@ -0,0 +1,274 @@ +from collections import defaultdict, namedtuple +import gc +import os +import re +import time +import tracemalloc +from typing import Callable, List, Optional +from ray.util.annotations import DeveloperAPI + +_logged = set() +_disabled = False +_periodic_log = False +_last_logged = 0.0 + + +@DeveloperAPI +def log_once(key): + """Returns True if this is the "first" call for a given key. + + Various logging settings can adjust the definition of "first". + + Example: + + .. testcode:: + + import logging + from ray.util.debug import log_once + + logger = logging.getLogger(__name__) + if log_once("some_key"): + logger.info("Some verbose logging statement") + """ + + global _last_logged + + if _disabled: + return False + elif key not in _logged: + _logged.add(key) + _last_logged = time.time() + return True + elif _periodic_log and time.time() - _last_logged > 60.0: + _logged.clear() + _last_logged = time.time() + return False + else: + return False + + +@DeveloperAPI +def disable_log_once_globally(): + """Make log_once() return False in this process.""" + + global _disabled + _disabled = True + + +@DeveloperAPI +def enable_periodic_logging(): + """Make log_once() periodically return True in this process.""" + + global _periodic_log + _periodic_log = True + + +@DeveloperAPI +def reset_log_once(key: Optional[str] = None): + """Resets log_once for the provided key. + + If you don't provide a key, resets log_once for all keys. + """ + if key is None: + _logged.clear() + else: + _logged.discard(key) + + +# A suspicious memory-allocating stack-trace that we should re-test +# to make sure it's not a false positive. +Suspect = DeveloperAPI( + namedtuple( + "Suspect", + [ + # The stack trace of the allocation, going back n frames, depending + # on the tracemalloc.start(n) call. + "traceback", + # The amount of memory taken by this particular stack trace + # over the course of the experiment. + "memory_increase", + # The slope of the scipy linear regression (x=iteration; y=memory size). + "slope", + # The rvalue of the scipy linear regression. + "rvalue", + # The memory size history (list of all memory sizes over all iterations). + "hist", + ], + ) +) + + +def _test_some_code_for_memory_leaks( + desc: str, + init: Optional[Callable[[], None]], + code: Callable[[], None], + repeats: int, + max_num_trials: int = 1, +) -> List[Suspect]: + """Runs given code (and init code) n times and checks for memory leaks. + + Args: + desc: A descriptor of the test. + init: Optional code to be executed initially. + code: The actual code to be checked for producing memory leaks. + repeats: How many times to repeatedly execute `code`. + max_num_trials: The maximum number of trials to run. A new trial is only + run, if the previous one produced a memory leak. For all non-1st trials, + `repeats` calculates as: actual_repeats = `repeats` * (trial + 1), where + the first trial is 0. + + Returns: + A list of Suspect objects, describing possible memory leaks. If list + is empty, no leaks have been found. + """ + + def _i_print(i): + if (i + 1) % 10 == 0: + print(".", end="" if (i + 1) % 100 else f" {i + 1}\n", flush=True) + + # Do n trials to make sure a found leak is really one. + suspicious = set() + suspicious_stats = [] + for trial in range(max_num_trials): + # Store up to n frames of each call stack. + tracemalloc.start(20) + + table = defaultdict(list) + + # Repeat running code for n times. + # Increase repeat value with each trial to make sure stats are more + # solid each time (avoiding false positives). + actual_repeats = repeats * (trial + 1) + + print(f"{desc} {actual_repeats} times.") + + # Initialize if necessary. + if init is not None: + init() + # Run `code` n times, each time taking a memory snapshot. + for i in range(actual_repeats): + _i_print(i) + # Manually trigger garbage collection before and after code runs in order to + # make tracemalloc snapshots as accurate as possible. + gc.collect() + code() + gc.collect() + _take_snapshot(table, suspicious) + print("\n") + + # Check, which traces have moved up in their memory consumption + # constantly over time. + suspicious.clear() + suspicious_stats.clear() + # Suspicious memory allocation found? + suspects = _find_memory_leaks_in_table(table) + for suspect in sorted(suspects, key=lambda s: s.memory_increase, reverse=True): + # Only print out the biggest offender: + if len(suspicious) == 0: + _pprint_suspect(suspect) + print("-> added to retry list") + suspicious.add(suspect.traceback) + suspicious_stats.append(suspect) + + tracemalloc.stop() + + # Some suspicious memory allocations found. + if len(suspicious) > 0: + print(f"{len(suspicious)} suspects found. Top-ten:") + for i, s in enumerate(suspicious_stats): + if i > 10: + break + print( + f"{i}) line={s.traceback[-1]} mem-increase={s.memory_increase}B " + f"slope={s.slope}B/detection rval={s.rvalue}" + ) + # Nothing suspicious found -> Exit trial loop and return. + else: + print("No remaining suspects found -> returning") + break + + # Print out final top offender. + if len(suspicious_stats) > 0: + _pprint_suspect(suspicious_stats[0]) + + return suspicious_stats + + +def _take_snapshot(table, suspicious=None): + # Take a memory snapshot. + snapshot = tracemalloc.take_snapshot() + # Group all memory allocations by their stacktrace (going n frames + # deep as defined above in tracemalloc.start(n)). + # Then sort groups by size, then count, then trace. + top_stats = snapshot.statistics("traceback") + + # For the first m largest increases, keep only, if a) first trial or b) those + # that are already in the `suspicious` set. + for stat in top_stats[:100]: + if not suspicious or stat.traceback in suspicious: + table[stat.traceback].append(stat.size) + + +def _find_memory_leaks_in_table(table): + import scipy.stats + import numpy as np + + suspects = [] + + for traceback, hist in table.items(): + # Do a quick mem increase check. + memory_increase = hist[-1] - hist[0] + + # Only if memory increased, do we check further. + if memory_increase <= 0.0: + continue + + # Ignore this very module here (we are collecting lots of data + # so an increase is expected). + top_stack = str(traceback[-1]) + drive_separator = "\\\\" if os.name == "nt" else "/" + if any( + s in top_stack + for s in [ + "tracemalloc", + "pycharm", + "thirdparty_files/psutil", + re.sub("\\.", drive_separator, __name__) + ".py", + ] + ): + continue + + # Do a linear regression to get the slope and R-value. + line = scipy.stats.linregress(x=np.arange(len(hist)), y=np.array(hist)) + + # - If weak positive slope and some confidence and + # increase > n bytes -> error. + # - If stronger positive slope -> error. + if memory_increase > 1000 and ( + (line.slope > 60.0 and line.rvalue > 0.875) + or (line.slope > 20.0 and line.rvalue > 0.9) + or (line.slope > 10.0 and line.rvalue > 0.95) + ): + suspects.append( + Suspect( + traceback=traceback, + memory_increase=memory_increase, + slope=line.slope, + rvalue=line.rvalue, + hist=hist, + ) + ) + + return suspects + + +def _pprint_suspect(suspect): + print( + "Most suspicious memory allocation in traceback " + "(only printing out this one, but all (less suspicious)" + " suspects will be investigated as well):" + ) + print("\n".join(suspect.traceback.format())) + print(f"Increase total={suspect.memory_increase}B") + print(f"Slope={suspect.slope} B/detection") + print(f"Rval={suspect.rvalue}") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/debugpy.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/debugpy.py new file mode 100644 index 0000000000000000000000000000000000000000..32b265d1d45161cccaaaf996e7dd80a791e4ce58 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/debugpy.py @@ -0,0 +1,136 @@ +import logging +import os +import sys +import threading +import importlib + +import ray +from ray.util.annotations import DeveloperAPI + +log = logging.getLogger(__name__) + +POST_MORTEM_ERROR_UUID = "post_mortem_error_uuid" + + +def _try_import_debugpy(): + try: + debugpy = importlib.import_module("debugpy") + if not hasattr(debugpy, "__version__") or debugpy.__version__ < "1.8.0": + raise ImportError() + return debugpy + except (ModuleNotFoundError, ImportError): + log.error( + "Module 'debugpy>=1.8.0' cannot be loaded. " + "Ray Debugpy Debugger will not work without 'debugpy>=1.8.0' installed. " + "Install this module using 'pip install debugpy==1.8.0' " + ) + return None + + +# A lock to ensure that only one thread can open the debugger port. +debugger_port_lock = threading.Lock() + + +def _override_breakpoint_hooks(): + """ + This method overrides the breakpoint() function to set_trace() + so that other threads can reuse the same setup logic. + This is based on: https://github.com/microsoft/debugpy/blob/ef9a67fe150179ee4df9997f9273723c26687fab/src/debugpy/_vendored/pydevd/pydev_sitecustomize/sitecustomize.py#L87 # noqa: E501 + """ + sys.__breakpointhook__ = set_trace + sys.breakpointhook = set_trace + import builtins as __builtin__ + + __builtin__.breakpoint = set_trace + + +def _ensure_debugger_port_open_thread_safe(): + """ + This is a thread safe method that ensure that the debugger port + is open, and if not, open it. + """ + + # The lock is acquired before checking the debugger port so only + # one thread can open the debugger port. + with debugger_port_lock: + debugpy = _try_import_debugpy() + if not debugpy: + return + + debugger_port = ray._private.worker.global_worker.debugger_port + if not debugger_port: + (host, port) = debugpy.listen( + (ray._private.worker.global_worker.node_ip_address, 0) + ) + ray._private.worker.global_worker.set_debugger_port(port) + log.info(f"Ray debugger is listening on {host}:{port}") + else: + log.info(f"Ray debugger is already open on {debugger_port}") + + +@DeveloperAPI +def set_trace(breakpoint_uuid=None): + """Interrupt the flow of the program and drop into the Ray debugger. + Can be used within a Ray task or actor. + """ + debugpy = _try_import_debugpy() + if not debugpy: + return + + _ensure_debugger_port_open_thread_safe() + + # debugpy overrides the breakpoint() function, so we need to set it back + # so other threads can reuse it. + _override_breakpoint_hooks() + + with ray._private.worker.global_worker.worker_paused_by_debugger(): + msg = ( + "Waiting for debugger to attach (see " + "https://docs.ray.io/en/latest/ray-observability/" + "ray-distributed-debugger.html)..." + ) + log.info(msg) + debugpy.wait_for_client() + + log.info("Debugger client is connected") + if breakpoint_uuid == POST_MORTEM_ERROR_UUID: + _debugpy_excepthook() + else: + _debugpy_breakpoint() + + +def _debugpy_breakpoint(): + """ + Drop the user into the debugger on a breakpoint. + """ + import pydevd + + pydevd.settrace(stop_at_frame=sys._getframe().f_back) + + +def _debugpy_excepthook(): + """ + Drop the user into the debugger on an unhandled exception. + """ + import threading + + import pydevd + + py_db = pydevd.get_global_debugger() + thread = threading.current_thread() + additional_info = py_db.set_additional_thread_info(thread) + additional_info.is_tracing += 1 + try: + error = sys.exc_info() + py_db.stop_on_unhandled_exception(py_db, thread, additional_info, error) + sys.excepthook(error[0], error[1], error[2]) + finally: + additional_info.is_tracing -= 1 + + +def _is_ray_debugger_post_mortem_enabled(): + return os.environ.get("RAY_DEBUG_POST_MORTEM", "0") == "1" + + +def _post_mortem(): + return set_trace(POST_MORTEM_ERROR_UUID) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/iter.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/iter.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3502f1d2ec8af5916a3c71e5e21c5dcdbaab33 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/iter.py @@ -0,0 +1,1286 @@ +import collections +import random +import threading +import time +from contextlib import contextmanager +from typing import Any, Callable, Generic, Iterable, List, TypeVar + +import ray +from ray.util.annotations import Deprecated +from ray.util.iter_metrics import MetricsContext, SharedMetrics + +# The type of an iterator element. +T = TypeVar("T") +U = TypeVar("U") + + +@Deprecated +def from_items( + items: List[T], num_shards: int = 2, repeat: bool = False +) -> "ParallelIterator[T]": + """Create a parallel iterator from an existing set of objects. + + The objects will be divided round-robin among the number of shards. + + Args: + items: The list of items to iterate over. + num_shards: The number of worker actors to create. + repeat: Whether to cycle over the items forever. + """ + shards = [[] for _ in range(num_shards)] + for i, item in enumerate(items): + shards[i % num_shards].append(item) + name = "from_items[{}, {}, shards={}{}]".format( + items and type(items[0]).__name__ or "None", + len(items), + num_shards, + ", repeat=True" if repeat else "", + ) + return from_iterators(shards, repeat=repeat, name=name) + + +@Deprecated +def from_range( + n: int, num_shards: int = 2, repeat: bool = False +) -> "ParallelIterator[int]": + """Create a parallel iterator over the range 0..n. + + The range will be partitioned sequentially among the number of shards. + + Args: + n: The max end of the range of numbers. + num_shards: The number of worker actors to create. + repeat: Whether to cycle over the range forever. + """ + generators = [] + shard_size = n // num_shards + for i in range(num_shards): + start = i * shard_size + if i == num_shards - 1: + end = n + else: + end = (i + 1) * shard_size + generators.append(range(start, end)) + name = ( + f"from_range[{n}, shards={num_shards}" f"{', repeat=True' if repeat else ''}]" + ) + return from_iterators( + generators, + repeat=repeat, + name=name, + ) + + +@Deprecated +def from_iterators( + generators: List[Iterable[T]], repeat: bool = False, name=None +) -> "ParallelIterator[T]": + """Create a parallel iterator from a list of iterables. + An iterable can be a conatiner (list, str, tuple, set, etc.), + a generator, or a custom class that implements __iter__ or __getitem__. + + An actor will be created for each iterable. + + Examples: + >>> # Create using a list of generators. + >>> from_iterators([range(100), range(100)]) + + >>> # Certain generators are not serializable. + >>> from_iterators([(x for x in range(100))]) + ... TypeError: can't pickle generator objects + + >>> # So use lambda functions instead. + >>> # Lambda functions are serializable. + >>> from_iterators([lambda: (x for x in range(100))]) + + Args: + generators: A list of Python iterables or lambda + functions that produce an iterable when called. We allow lambda + functions since certain generators might not be serializable, + but a lambda that returns it can be. + repeat: Whether to cycle over the iterators forever. + name: Optional name to give the iterator. + """ + worker_cls = ray.remote(ParallelIteratorWorker) + actors = [worker_cls.remote(g, repeat) for g in generators] + if not name: + name = "from_iterators[shards={}{}]".format( + len(generators), ", repeat=True" if repeat else "" + ) + return from_actors(actors, name=name) + + +@Deprecated +def from_actors( + actors: List["ray.actor.ActorHandle"], name=None +) -> "ParallelIterator[T]": + """Create a parallel iterator from an existing set of actors. + + Each actor must subclass the ParallelIteratorWorker interface. + + Args: + actors: List of actors that each implement + ParallelIteratorWorker. + name: Optional name to give the iterator. + """ + if not name: + name = f"from_actors[shards={len(actors)}]" + return ParallelIterator([_ActorSet(actors, [])], name, parent_iterators=[]) + + +@Deprecated +class ParallelIterator(Generic[T]): + """A parallel iterator over a set of remote actors. + + This can be used to iterate over a fixed set of task results + (like an actor pool), or a stream of data (e.g., a fixed range of numbers, + an infinite stream of RLlib rollout results). + + This class is **serializable** and can be passed to other remote + tasks and actors. However, each shard should be read from at most one + process at a time. + + Examples: + >>> # Applying a function over items in parallel. + >>> it = ray.util.iter.from_items([1, 2, 3], num_shards=2) + ... <__main__.ParallelIterator object> + >>> it = it.for_each(lambda x: x * 2).gather_sync() + ... <__main__.LocalIterator object> + >>> print(list(it)) + ... [2, 4, 6] + + >>> # Creating from generators. + >>> it = ray.util.iter.from_iterators([range(3), range(3)]) + ... <__main__.ParallelIterator object> + >>> print(list(it.gather_sync())) + ... [0, 0, 1, 1, 2, 2] + + >>> # Accessing the individual shards of an iterator. + >>> it = ray.util.iter.from_range(10, num_shards=2) + ... <__main__.ParallelIterator object> + >>> it0 = it.get_shard(0) + ... <__main__.LocalIterator object> + >>> print(list(it0)) + ... [0, 1, 2, 3, 4] + >>> it1 = it.get_shard(1) + ... <__main__.LocalIterator object> + >>> print(list(it1)) + ... [5, 6, 7, 8, 9] + + >>> # Gathering results from actors synchronously in parallel. + >>> it = ray.util.iter.from_actors(workers) + ... <__main__.ParallelIterator object> + >>> it = it.batch_across_shards() + ... <__main__.LocalIterator object> + >>> print(next(it)) + ... [worker_1_result_1, worker_2_result_1] + >>> print(next(it)) + ... [worker_1_result_2, worker_2_result_2] + """ + + def __init__( + self, + actor_sets: List["_ActorSet"], + name: str, + parent_iterators: List["ParallelIterator[Any]"], + ): + """Create a parallel iterator (this is an internal function).""" + + # We track multiple sets of actors to support parallel .union(). + self.actor_sets = actor_sets + self.name = name + + # keep explicit reference to parent iterator for repartition + self.parent_iterators = parent_iterators + + def __iter__(self): + raise TypeError( + "You must use it.gather_sync() or it.gather_async() to " + "iterate over the results of a ParallelIterator." + ) + + def __str__(self): + return repr(self) + + def __repr__(self): + return f"ParallelIterator[{self.name}]" + + def _with_transform(self, local_it_fn, name): + """Helper function to create new Parallel Iterator""" + return ParallelIterator( + [a.with_transform(local_it_fn) for a in self.actor_sets], + name=self.name + name, + parent_iterators=self.parent_iterators, + ) + + def transform( + self, fn: Callable[[Iterable[T]], Iterable[U]] + ) -> "ParallelIterator[U]": + """Remotely transform the iterator. + + This is advanced version of for_each that allows you to apply arbitrary + generator transformations over the iterator. Prefer to use .for_each() + when possible for simplicity. + + Args: + fn: function to use to transform the iterator. The function + should pass through instances of _NextValueNotReady that appear + in its input iterator. Note that this function is only called + **once** over the input iterator. + + Returns: + ParallelIterator[U]: a parallel iterator. + + Examples: + >>> def f(it): + ... for x in it: + ... if x % 2 == 0: + ... yield x + >>> from_range(10, 1).transform(f).gather_sync().take(5) + ... [0, 2, 4, 6, 8] + """ + return self._with_transform( + lambda local_it: local_it.transform(fn), ".transform()" + ) + + def for_each( + self, fn: Callable[[T], U], max_concurrency=1, resources=None + ) -> "ParallelIterator[U]": + """Remotely apply fn to each item in this iterator. + + If `max_concurrency` == 1 then `fn` will be executed serially by each + shards + + `max_concurrency` should be used to achieve a high degree of + parallelism without the overhead of increasing the number of shards + (which are actor based). If `max_concurrency` is not 1, this function + provides no semantic guarantees on the output order. + Results will be returned as soon as they are ready. + + A performance note: When executing concurrently, this function + maintains its own internal buffer. If `num_async` is `n` and + max_concur is `k` then the total number of buffered objects could be up + to `n + k - 1` + + Args: + fn: function to apply to each item. + max_concurrency: max number of concurrent calls to fn per + shard. If 0, then apply all operations concurrently. + resources: resources that the function requires to execute. + This has the same default as `ray.remote` and is only used + when `max_concurrency > 1`. + + Returns: + ParallelIterator[U]: a parallel iterator whose elements have `fn` + applied. + + Examples: + >>> next(from_range(4).for_each( + lambda x: x * 2, + max_concur=2, + resources={"num_cpus": 0.1}).gather_sync() + ) + ... [0, 2, 4, 8] + + """ + assert max_concurrency >= 0, "max_concurrency must be non-negative." + return self._with_transform( + lambda local_it: local_it.for_each(fn, max_concurrency, resources), + ".for_each()", + ) + + def filter(self, fn: Callable[[T], bool]) -> "ParallelIterator[T]": + """Remotely filter items from this iterator. + + Args: + fn: returns False for items to drop from the iterator. + + Examples: + >>> it = from_items([0, 1, 2]).filter(lambda x: x > 0) + >>> next(it.gather_sync()) + ... [1, 2] + """ + return self._with_transform(lambda local_it: local_it.filter(fn), ".filter()") + + def batch(self, n: int) -> "ParallelIterator[List[T]]": + """Remotely batch together items in this iterator. + + Args: + n: Number of items to batch together. + + Examples: + >>> next(from_range(10, 1).batch(4).gather_sync()) + ... [0, 1, 2, 3] + """ + return self._with_transform(lambda local_it: local_it.batch(n), f".batch({n})") + + def flatten(self) -> "ParallelIterator[T[0]]": + """Flatten batches of items into individual items. + + Examples: + >>> next(from_range(10, 1).batch(4).flatten()) + ... 0 + """ + return self._with_transform(lambda local_it: local_it.flatten(), ".flatten()") + + def combine(self, fn: Callable[[T], List[U]]) -> "ParallelIterator[U]": + """Transform and then combine items horizontally. + + This is the equivalent of for_each(fn).flatten() (flat map). + """ + it = self.for_each(fn).flatten() + it.name = self.name + ".combine()" + return it + + def local_shuffle( + self, shuffle_buffer_size: int, seed: int = None + ) -> "ParallelIterator[T]": + """Remotely shuffle items of each shard independently + + Args: + shuffle_buffer_size: The algorithm fills a buffer with + shuffle_buffer_size elements and randomly samples elements from + this buffer, replacing the selected elements with new elements. + For perfect shuffling, this argument should be greater than or + equal to the largest iterator size. + seed: Seed to use for + randomness. Default value is None. + + Returns: + A ParallelIterator with a local shuffle applied on the base + iterator + + Examples: + >>> it = from_range(10, 1).local_shuffle(shuffle_buffer_size=2) + >>> it = it.gather_sync() + >>> next(it) + 0 + >>> next(it) + 2 + >>> next(it) + 3 + >>> next(it) + 1 + """ + return self._with_transform( + lambda local_it: local_it.shuffle(shuffle_buffer_size, seed), + ".local_shuffle(shuffle_buffer_size={}, seed={})".format( + shuffle_buffer_size, str(seed) if seed is not None else "None" + ), + ) + + def repartition( + self, num_partitions: int, batch_ms: int = 0 + ) -> "ParallelIterator[T]": + """Returns a new ParallelIterator instance with num_partitions shards. + + The new iterator contains the same data in this instance except with + num_partitions shards. The data is split in round-robin fashion for + the new ParallelIterator. + + Args: + num_partitions: The number of shards to use for the new + ParallelIterator + batch_ms: Batches items for batch_ms milliseconds + on each shard before retrieving it. + Increasing batch_ms increases latency but improves throughput. + + Returns: + A ParallelIterator with num_partitions number of shards and the + data of this ParallelIterator split round-robin among the new + number of shards. + + Examples: + >>> it = from_range(8, 2) + >>> it = it.repartition(3) + >>> list(it.get_shard(0)) + [0, 4, 3, 7] + >>> list(it.get_shard(1)) + [1, 5] + >>> list(it.get_shard(2)) + [2, 6] + """ + + # initialize the local iterators for all the actors + all_actors = [] + for actor_set in self.actor_sets: + actor_set.init_actors() + all_actors.extend(actor_set.actors) + + def base_iterator(num_partitions, partition_index, timeout=None): + futures = {} + for a in all_actors: + futures[ + a.par_iter_slice_batch.remote( + step=num_partitions, start=partition_index, batch_ms=batch_ms + ) + ] = a + while futures: + pending = list(futures) + if timeout is None: + # First try to do a batch wait for efficiency. + ready, _ = ray.wait(pending, num_returns=len(pending), timeout=0) + # Fall back to a blocking wait. + if not ready: + ready, _ = ray.wait(pending, num_returns=1) + else: + ready, _ = ray.wait( + pending, num_returns=len(pending), timeout=timeout + ) + for obj_ref in ready: + actor = futures.pop(obj_ref) + try: + batch = ray.get(obj_ref) + futures[ + actor.par_iter_slice_batch.remote( + step=num_partitions, + start=partition_index, + batch_ms=batch_ms, + ) + ] = actor + for item in batch: + yield item + except StopIteration: + pass + # Always yield after each round of wait with timeout. + if timeout is not None: + yield _NextValueNotReady() + + def make_gen_i(i): + return lambda: base_iterator(num_partitions, i) + + name = self.name + f".repartition[num_partitions={num_partitions}]" + + generators = [make_gen_i(s) for s in range(num_partitions)] + worker_cls = ray.remote(ParallelIteratorWorker) + actors = [worker_cls.remote(g, repeat=False) for g in generators] + # need explicit reference to self so actors in this instance do not die + return ParallelIterator([_ActorSet(actors, [])], name, parent_iterators=[self]) + + def gather_sync(self) -> "LocalIterator[T]": + """Returns a local iterable for synchronous iteration. + + New items will be fetched from the shards on-demand as the iterator + is stepped through. + + This is the equivalent of batch_across_shards().flatten(). + + Examples: + >>> it = from_range(100, 1).gather_sync() + >>> next(it) + ... 0 + >>> next(it) + ... 1 + >>> next(it) + ... 2 + """ + it = self.batch_across_shards().flatten() + it.name = f"{self}.gather_sync()" + return it + + def batch_across_shards(self) -> "LocalIterator[List[T]]": + """Iterate over the results of multiple shards in parallel. + + Examples: + >>> it = from_iterators([range(3), range(3)]) + >>> next(it.batch_across_shards()) + ... [0, 0] + """ + + def base_iterator(timeout=None): + active = [] + for actor_set in self.actor_sets: + actor_set.init_actors() + active.extend(actor_set.actors) + futures = [a.par_iter_next.remote() for a in active] + while active: + try: + yield ray.get(futures, timeout=timeout) + futures = [a.par_iter_next.remote() for a in active] + # Always yield after each round of gets with timeout. + if timeout is not None: + yield _NextValueNotReady() + except TimeoutError: + yield _NextValueNotReady() + except StopIteration: + # Find and remove the actor that produced StopIteration. + results = [] + for a, f in zip(list(active), futures): + try: + results.append(ray.get(f)) + except StopIteration: + active.remove(a) + if results: + yield results + futures = [a.par_iter_next.remote() for a in active] + + name = f"{self}.batch_across_shards()" + return LocalIterator(base_iterator, SharedMetrics(), name=name) + + def gather_async(self, batch_ms=0, num_async=1) -> "LocalIterator[T]": + """Returns a local iterable for asynchronous iteration. + + New items will be fetched from the shards asynchronously as soon as + the previous one is computed. Items arrive in non-deterministic order. + + Arguments: + batch_ms: Batches items for batch_ms milliseconds + on each shard before retrieving it. + Increasing batch_ms increases latency but improves throughput. + If this value is 0, then items are returned immediately. + num_async: The max number of async requests in flight + per actor. Increasing this improves the amount of pipeline + parallelism in the iterator. + + Examples: + >>> it = from_range(100, 1).gather_async() + >>> next(it) + ... 3 + >>> next(it) + ... 0 + >>> next(it) + ... 1 + """ + + if num_async < 1: + raise ValueError("queue depth must be positive") + if batch_ms < 0: + raise ValueError("batch time must be positive") + + # Forward reference to the returned iterator. + local_iter = None + + def base_iterator(timeout=None): + all_actors = [] + for actor_set in self.actor_sets: + actor_set.init_actors() + all_actors.extend(actor_set.actors) + futures = {} + for _ in range(num_async): + for a in all_actors: + futures[a.par_iter_next_batch.remote(batch_ms)] = a + while futures: + pending = list(futures) + if timeout is None: + # First try to do a batch wait for efficiency. + ready, _ = ray.wait(pending, num_returns=len(pending), timeout=0) + # Fall back to a blocking wait. + if not ready: + ready, _ = ray.wait(pending, num_returns=1) + else: + ready, _ = ray.wait( + pending, num_returns=len(pending), timeout=timeout + ) + for obj_ref in ready: + actor = futures.pop(obj_ref) + try: + local_iter.shared_metrics.get().current_actor = actor + batch = ray.get(obj_ref) + futures[actor.par_iter_next_batch.remote(batch_ms)] = actor + for item in batch: + yield item + except StopIteration: + pass + # Always yield after each round of wait with timeout. + if timeout is not None: + yield _NextValueNotReady() + + name = f"{self}.gather_async()" + local_iter = LocalIterator(base_iterator, SharedMetrics(), name=name) + return local_iter + + def take(self, n: int) -> List[T]: + """Return up to the first n items from this iterator.""" + return self.gather_sync().take(n) + + def show(self, n: int = 20): + """Print up to the first n items from this iterator.""" + return self.gather_sync().show(n) + + def union(self, other: "ParallelIterator[T]") -> "ParallelIterator[T]": + """Return an iterator that is the union of this and the other.""" + if not isinstance(other, ParallelIterator): + raise TypeError( + f"other must be of type ParallelIterator, got {type(other)}" + ) + actor_sets = [] + actor_sets.extend(self.actor_sets) + actor_sets.extend(other.actor_sets) + # if one of these iterators is a result of a repartition, we need to + # keep an explicit reference to its parent iterator + return ParallelIterator( + actor_sets, + f"ParallelUnion[{self}, {other}]", + parent_iterators=self.parent_iterators + other.parent_iterators, + ) + + def select_shards(self, shards_to_keep: List[int]) -> "ParallelIterator[T]": + """Return a child iterator that only iterates over given shards. + + It is the user's responsibility to ensure child iterators are operating + over disjoint sub-sets of this iterator's shards. + """ + if len(self.actor_sets) > 1: + raise ValueError("select_shards() is not allowed after union()") + if len(shards_to_keep) == 0: + raise ValueError("at least one shard must be selected") + old_actor_set = self.actor_sets[0] + new_actors = [ + a for (i, a) in enumerate(old_actor_set.actors) if i in shards_to_keep + ] + assert len(new_actors) == len(shards_to_keep), "Invalid actor index" + new_actor_set = _ActorSet(new_actors, old_actor_set.transforms) + return ParallelIterator( + [new_actor_set], + f"{self}.select_shards({len(shards_to_keep)} total)", + parent_iterators=self.parent_iterators, + ) + + def num_shards(self) -> int: + """Return the number of worker actors backing this iterator.""" + return sum(len(a.actors) for a in self.actor_sets) + + def shards(self) -> List["LocalIterator[T]"]: + """Return the list of all shards.""" + return [self.get_shard(i) for i in range(self.num_shards())] + + def get_shard( + self, shard_index: int, batch_ms: int = 0, num_async: int = 1 + ) -> "LocalIterator[T]": + """Return a local iterator for the given shard. + + The iterator is guaranteed to be serializable and can be passed to + remote tasks or actors. + + Arguments: + shard_index: Index of the shard to gather. + batch_ms: Batches items for batch_ms milliseconds + before retrieving it. + Increasing batch_ms increases latency but improves throughput. + If this value is 0, then items are returned immediately. + num_async: The max number of requests in flight. + Increasing this improves the amount of pipeline + parallelism in the iterator. + """ + if num_async < 1: + raise ValueError("num async must be positive") + if batch_ms < 0: + raise ValueError("batch time must be positive") + a, t = None, None + i = shard_index + for actor_set in self.actor_sets: + if i < len(actor_set.actors): + a = actor_set.actors[i] + t = actor_set.transforms + break + else: + i -= len(actor_set.actors) + if a is None: + raise ValueError("Shard index out of range", shard_index, self.num_shards()) + + def base_iterator(timeout=None): + queue = collections.deque() + ray.get(a.par_iter_init.remote(t)) + for _ in range(num_async): + queue.append(a.par_iter_next_batch.remote(batch_ms)) + while True: + try: + batch = ray.get(queue.popleft(), timeout=timeout) + queue.append(a.par_iter_next_batch.remote(batch_ms)) + for item in batch: + yield item + # Always yield after each round of gets with timeout. + if timeout is not None: + yield _NextValueNotReady() + except TimeoutError: + yield _NextValueNotReady() + except StopIteration: + break + + name = self.name + f".shard[{shard_index}]" + return LocalIterator(base_iterator, SharedMetrics(), name=name) + + +@Deprecated +class LocalIterator(Generic[T]): + """An iterator over a single shard of data. + + It implements similar transformations as ParallelIterator[T], but the + transforms will be applied locally and not remotely in parallel. + + This class is **serializable** and can be passed to other remote + tasks and actors. However, it should be read from at most one process at + a time.""" + + # If a function passed to LocalIterator.for_each() has this method, + # we will call it at the beginning of each data fetch call. This can be + # used to measure the underlying wait latency for measurement purposes. + ON_FETCH_START_HOOK_NAME = "_on_fetch_start" + + thread_local = threading.local() + + def __init__( + self, + base_iterator: Callable[[], Iterable[T]], + shared_metrics: SharedMetrics, + local_transforms: List[Callable[[Iterable], Any]] = None, + timeout: int = None, + name=None, + ): + """Create a local iterator (this is an internal function). + + Args: + base_iterator: A function that produces the base iterator. + This is a function so that we can ensure LocalIterator is + serializable. + shared_metrics: Existing metrics context or a new + context. Should be the same for each chained iterator. + local_transforms: A list of transformation functions to be + applied on top of the base iterator. When iteration begins, we + create the base iterator and apply these functions. This lazy + creation ensures LocalIterator is serializable until you start + iterating over it. + timeout: Optional timeout in seconds for this iterator, after + which _NextValueNotReady will be returned. This avoids + blocking. + name: Optional name for this iterator. + """ + assert isinstance(shared_metrics, SharedMetrics) + self.base_iterator = base_iterator + self.built_iterator = None + self.local_transforms = local_transforms or [] + self.shared_metrics = shared_metrics + self.timeout = timeout + self.name = name or "unknown" + + @staticmethod + def get_metrics() -> MetricsContext: + """Return the current metrics context. + + This can only be called within an iterator function.""" + if ( + not hasattr(LocalIterator.thread_local, "metrics") + or LocalIterator.thread_local.metrics is None + ): + raise ValueError("Cannot access context outside an iterator.") + return LocalIterator.thread_local.metrics + + def _build_once(self): + if self.built_iterator is None: + it = iter(self.base_iterator(self.timeout)) + for fn in self.local_transforms: + it = fn(it) + self.built_iterator = it + + @contextmanager + def _metrics_context(self): + self.thread_local.metrics = self.shared_metrics.get() + yield + + def __iter__(self): + self._build_once() + return self.built_iterator + + def __next__(self): + self._build_once() + return next(self.built_iterator) + + def __str__(self): + return repr(self) + + def __repr__(self): + return f"LocalIterator[{self.name}]" + + def transform(self, fn: Callable[[Iterable[T]], Iterable[U]]) -> "LocalIterator[U]": + + # TODO(ekl) can we automatically handle NextValueNotReady here? + def apply_transform(it): + for item in fn(it): + yield item + + return LocalIterator( + self.base_iterator, + self.shared_metrics, + self.local_transforms + [apply_transform], + name=self.name + ".transform()", + ) + + def for_each( + self, fn: Callable[[T], U], max_concurrency=1, resources=None + ) -> "LocalIterator[U]": + if max_concurrency == 1: + + def apply_foreach(it): + for item in it: + if isinstance(item, _NextValueNotReady): + yield item + else: + # Keep retrying the function until it returns a valid + # value. This allows for non-blocking functions. + while True: + with self._metrics_context(): + result = fn(item) + yield result + if not isinstance(result, _NextValueNotReady): + break + + else: + if resources is None: + resources = {} + + def apply_foreach(it): + cur = [] + remote = ray.remote(fn).options(**resources) + remote_fn = remote.remote + for item in it: + if isinstance(item, _NextValueNotReady): + yield item + else: + if max_concurrency and len(cur) >= max_concurrency: + finished, cur = ray.wait(cur) + yield from ray.get(finished) + cur.append(remote_fn(item)) + while cur: + finished, cur = ray.wait(cur) + yield from ray.get(finished) + + if hasattr(fn, LocalIterator.ON_FETCH_START_HOOK_NAME): + unwrapped = apply_foreach + + def add_wait_hooks(it): + it = unwrapped(it) + new_item = True + while True: + # Avoids calling on_fetch_start repeatedly if we are + # yielding _NextValueNotReady. + if new_item: + with self._metrics_context(): + fn._on_fetch_start() + new_item = False + item = next(it) + if not isinstance(item, _NextValueNotReady): + new_item = True + yield item + + apply_foreach = add_wait_hooks + + return LocalIterator( + self.base_iterator, + self.shared_metrics, + self.local_transforms + [apply_foreach], + name=self.name + ".for_each()", + ) + + def filter(self, fn: Callable[[T], bool]) -> "LocalIterator[T]": + def apply_filter(it): + for item in it: + with self._metrics_context(): + if isinstance(item, _NextValueNotReady) or fn(item): + yield item + + return LocalIterator( + self.base_iterator, + self.shared_metrics, + self.local_transforms + [apply_filter], + name=self.name + ".filter()", + ) + + def batch(self, n: int) -> "LocalIterator[List[T]]": + def apply_batch(it): + batch = [] + for item in it: + if isinstance(item, _NextValueNotReady): + yield item + else: + batch.append(item) + if len(batch) >= n: + yield batch + batch = [] + if batch: + yield batch + + return LocalIterator( + self.base_iterator, + self.shared_metrics, + self.local_transforms + [apply_batch], + name=self.name + f".batch({n})", + ) + + def flatten(self) -> "LocalIterator[T[0]]": + def apply_flatten(it): + for item in it: + if isinstance(item, _NextValueNotReady): + yield item + else: + for subitem in item: + yield subitem + + return LocalIterator( + self.base_iterator, + self.shared_metrics, + self.local_transforms + [apply_flatten], + name=self.name + ".flatten()", + ) + + def shuffle(self, shuffle_buffer_size: int, seed: int = None) -> "LocalIterator[T]": + """Shuffle items of this iterator + + Args: + shuffle_buffer_size: The algorithm fills a buffer with + shuffle_buffer_size elements and randomly samples elements from + this buffer, replacing the selected elements with new elements. + For perfect shuffling, this argument should be greater than or + equal to the largest iterator size. + seed: Seed to use for + randomness. Default value is None. + + Returns: + A new LocalIterator with shuffling applied + """ + shuffle_random = random.Random(seed) + + def apply_shuffle(it): + buffer = [] + for item in it: + if isinstance(item, _NextValueNotReady): + yield item + else: + buffer.append(item) + if len(buffer) >= shuffle_buffer_size: + yield buffer.pop(shuffle_random.randint(0, len(buffer) - 1)) + while len(buffer) > 0: + yield buffer.pop(shuffle_random.randint(0, len(buffer) - 1)) + + return LocalIterator( + self.base_iterator, + self.shared_metrics, + self.local_transforms + [apply_shuffle], + name=self.name + + ".shuffle(shuffle_buffer_size={}, seed={})".format( + shuffle_buffer_size, str(seed) if seed is not None else "None" + ), + ) + + def combine(self, fn: Callable[[T], List[U]]) -> "LocalIterator[U]": + it = self.for_each(fn).flatten() + it.name = self.name + ".combine()" + return it + + def zip_with_source_actor(self): + def zip_with_source(item): + metrics = LocalIterator.get_metrics() + if metrics.current_actor is None: + raise ValueError("Could not identify source actor of item") + return metrics.current_actor, item + + it = self.for_each(zip_with_source) + it.name = self.name + ".zip_with_source_actor()" + return it + + def take(self, n: int) -> List[T]: + """Return up to the first n items from this iterator.""" + out = [] + for item in self: + out.append(item) + if len(out) >= n: + break + return out + + def show(self, n: int = 20): + """Print up to the first n items from this iterator.""" + i = 0 + for item in self: + print(item) + i += 1 + if i >= n: + break + + def duplicate(self, n) -> List["LocalIterator[T]"]: + """Copy this iterator `n` times, duplicating the data. + + The child iterators will be prioritized by how much of the parent + stream they have consumed. That is, we will not allow children to fall + behind, since that can cause infinite memory buildup in this operator. + + Returns: + List[LocalIterator[T]]: child iterators that each have a copy + of the data of this iterator. + """ + + if n < 2: + raise ValueError("Number of copies must be >= 2") + + queues = [] + for _ in range(n): + queues.append(collections.deque()) + + def fill_next(timeout): + self.timeout = timeout + item = next(self) + for q in queues: + q.append(item) + + def make_next(i): + def gen(timeout): + while True: + my_len = len(queues[i]) + max_len = max(len(q) for q in queues) + # Yield to let other iterators that have fallen behind + # process more items. + if my_len < max_len: + yield _NextValueNotReady() + else: + if len(queues[i]) == 0: + try: + fill_next(timeout) + except StopIteration: + return + yield queues[i].popleft() + + return gen + + iterators = [] + for i in range(n): + iterators.append( + LocalIterator( + make_next(i), + self.shared_metrics, + [], + name=self.name + f".duplicate[{i}]", + ) + ) + + return iterators + + def union( + self, + *others: "LocalIterator[T]", + deterministic: bool = False, + round_robin_weights: List[float] = None, + ) -> "LocalIterator[T]": + """Return an iterator that is the union of this and the others. + + Args: + deterministic: If deterministic=True, we alternate between + reading from one iterator and the others. Otherwise we return + items from iterators as they become ready. + round_robin_weights: List of weights to use for round robin + mode. For example, [2, 1] will cause the iterator to pull twice + as many items from the first iterator as the second. + [2, 1, "*"] will cause as many items to be pulled as possible + from the third iterator without blocking. This overrides the + deterministic flag. + """ + + for it in others: + if not isinstance(it, LocalIterator): + raise ValueError(f"other must be of type LocalIterator, got {type(it)}") + + active = [] + parent_iters = [self] + list(others) + shared_metrics = SharedMetrics(parents=[p.shared_metrics for p in parent_iters]) + + timeout = None if deterministic else 0 + if round_robin_weights: + if len(round_robin_weights) != len(parent_iters): + raise ValueError( + "Length of round robin weights must equal number of " + "iterators total." + ) + timeouts = [0 if w == "*" else None for w in round_robin_weights] + else: + timeouts = [timeout] * len(parent_iters) + round_robin_weights = [1] * len(parent_iters) + + for i, it in enumerate(parent_iters): + active.append( + LocalIterator( + it.base_iterator, + shared_metrics, + it.local_transforms, + timeout=timeouts[i], + ) + ) + active = list(zip(round_robin_weights, active)) + + def build_union(timeout=None): + while True: + for weight, it in list(active): + if weight == "*": + max_pull = 100 # TOOD(ekl) how to best bound this? + else: + max_pull = _randomized_int_cast(weight) + try: + for _ in range(max_pull): + item = next(it) + if isinstance(item, _NextValueNotReady): + if timeout is not None: + yield item + break + else: + yield item + except StopIteration: + active.remove((weight, it)) + if not active: + break + + return LocalIterator( + build_union, + shared_metrics, + [], + name=f"LocalUnion[{self}, {', '.join(map(str, others))}]", + ) + + +@Deprecated +class ParallelIteratorWorker(object): + """Worker actor for a ParallelIterator. + + Actors that are passed to iter.from_actors() must subclass this interface. + """ + + def __init__(self, item_generator: Any, repeat: bool): + """Create an iterator worker. + + Subclasses must call this init function. + + Args: + item_generator: A Python iterable or lambda function + that produces a generator when called. We allow lambda + functions since the generator itself might not be serializable, + but a lambda that returns it can be. + repeat: Whether to loop over the iterator forever. + """ + + def make_iterator(): + if callable(item_generator): + return item_generator() + else: + return item_generator + + if repeat: + + def cycle(): + while True: + it = iter(make_iterator()) + if it is item_generator: + raise ValueError( + "Cannot iterate over {0} multiple times." + + "Please pass in the base iterable or" + + "lambda: {0} instead.".format(item_generator) + ) + for item in it: + yield item + + self.item_generator = cycle() + else: + self.item_generator = make_iterator() + + self.transforms = [] + self.local_it = None + self.next_ith_buffer = None + + def par_iter_init(self, transforms): + """Implements ParallelIterator worker init.""" + it = LocalIterator(lambda timeout: self.item_generator, SharedMetrics()) + for fn in transforms: + it = fn(it) + assert it is not None, fn + self.local_it = iter(it) + + def par_iter_next(self): + """Implements ParallelIterator worker item fetch.""" + assert self.local_it is not None, "must call par_iter_init()" + return next(self.local_it) + + def par_iter_next_batch(self, batch_ms: int): + """Batches par_iter_next.""" + batch = [] + if batch_ms == 0: + batch.append(self.par_iter_next()) + return batch + t_end = time.time() + (0.001 * batch_ms) + while time.time() < t_end: + try: + batch.append(self.par_iter_next()) + except StopIteration: + if len(batch) == 0: + raise StopIteration + else: + pass + return batch + + def par_iter_slice(self, step: int, start: int): + """Iterates in increments of step starting from start.""" + assert self.local_it is not None, "must call par_iter_init()" + + if self.next_ith_buffer is None: + self.next_ith_buffer = collections.defaultdict(list) + + index_buffer = self.next_ith_buffer[start] + if len(index_buffer) > 0: + return index_buffer.pop(0) + else: + for j in range(step): + try: + val = next(self.local_it) + self.next_ith_buffer[j].append(val) + except StopIteration: + pass + + if not self.next_ith_buffer[start]: + raise StopIteration + + return self.next_ith_buffer[start].pop(0) + + def par_iter_slice_batch(self, step: int, start: int, batch_ms: int): + """Batches par_iter_slice.""" + batch = [] + if batch_ms == 0: + batch.append(self.par_iter_slice(step, start)) + return batch + t_end = time.time() + (0.001 * batch_ms) + while time.time() < t_end: + try: + batch.append(self.par_iter_slice(step, start)) + except StopIteration: + if len(batch) == 0: + raise StopIteration + else: + pass + return batch + + +def _randomized_int_cast(float_value): + base = int(float_value) + remainder = float_value - base + if random.random() < remainder: + base += 1 + return base + + +class _NextValueNotReady(Exception): + """Indicates that a local iterator has no value currently available. + + This is used internally to implement the union() of multiple blocking + local generators.""" + + pass + + +class _ActorSet(object): + """Helper class that represents a set of actors and transforms.""" + + def __init__( + self, + actors: List["ray.actor.ActorHandle"], + transforms: List[Callable[["LocalIterator"], "LocalIterator"]], + ): + self.actors = actors + self.transforms = transforms + + def init_actors(self): + ray.get([a.par_iter_init.remote(self.transforms) for a in self.actors]) + + def with_transform(self, fn): + return _ActorSet(self.actors, self.transforms + [fn]) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/iter_metrics.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/iter_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..eb06a97c3ace41d230e1d16b329126272d71a3ff --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/iter_metrics.py @@ -0,0 +1,69 @@ +import collections +from typing import List + +from ray.util.annotations import Deprecated +from ray.util.timer import _Timer + + +@Deprecated +class MetricsContext: + """Metrics context object for a local iterator. + + This object is accessible by all operators of a local iterator. It can be + used to store and retrieve global execution metrics for the iterator. + It can be accessed by calling LocalIterator.get_metrics(), which is only + allowable inside iterator functions. + + Attributes: + counters: dict storing increasing metrics. + timers: dict storing latency timers. + info: dict storing misc metric values. + current_actor: reference to the actor handle that + produced the current iterator output. This is automatically set + for gather_async(). + """ + + def __init__(self): + self.counters = collections.defaultdict(int) + self.timers = collections.defaultdict(_Timer) + self.info = {} + self.current_actor = None + + def save(self): + """Return a serializable copy of this context.""" + return { + "counters": dict(self.counters), + "info": dict(self.info), + "timers": None, # TODO(ekl) consider persisting timers too + } + + def restore(self, values): + """Restores state given the output of save().""" + self.counters.clear() + self.counters.update(values["counters"]) + self.timers.clear() + self.info = values["info"] + + +@Deprecated +class SharedMetrics: + """Holds an indirect reference to a (shared) metrics context. + + This is used by LocalIterator.union() to point the metrics contexts of + entirely separate iterator chains to the same underlying context.""" + + def __init__( + self, metrics: MetricsContext = None, parents: List["SharedMetrics"] = None + ): + self.metrics = metrics or MetricsContext() + self.parents = parents or [] + self.set(self.metrics) + + def set(self, metrics): + """Recursively set self and parents to point to the same metrics.""" + self.metrics = metrics + for parent in self.parents: + parent.set(metrics) + + def get(self): + return self.metrics diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/metrics.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..53bc84bec50880156f5cfd59b3424d7cb94ea9bb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/metrics.py @@ -0,0 +1,349 @@ +import logging +import re +import warnings + +from typing import Dict, Any, List, Optional, Tuple, Union + +from ray._raylet import ( + Sum as CythonCount, + Histogram as CythonHistogram, + Gauge as CythonGauge, +) # noqa: E402 + +# Sum is used for CythonCount because it allows incrementing by positive +# values that are different from one. +from ray.util.annotations import DeveloperAPI + +logger = logging.getLogger(__name__) + +# Copied from Prometheus Python Client. While the regex is not part of the public API +# for Prometheus, it's not expected to change. +# https://github.com/prometheus/client_python/blob/46eae7bae88f76951f7246d9f359f2dd5eeff110/prometheus_client/validation.py#L4 +_VALID_METRIC_NAME_RE = re.compile(r"^[a-zA-Z_:][a-zA-Z0-9_:]*$") + + +def _is_invalid_metric_name(name: str) -> bool: + if len(name) == 0: + raise ValueError("Empty name is not allowed. Please provide a metric name.") + if not _VALID_METRIC_NAME_RE.match(name): + warnings.warn( + f"Invalid metric name: {name}. Metric will be discarded " + "and data will not be collected or published. " + "Metric names can only contain letters, numbers, _, and :. " + "Metric names cannot start with numbers.", + UserWarning, + ) + return True + return False + + +@DeveloperAPI +class Metric: + """The parent class of custom metrics. + + Ray's custom metrics APIs are rooted from this class and share + the same public methods. + """ + + def __init__( + self, + name: str, + description: str = "", + tag_keys: Optional[Tuple[str, ...]] = None, + ): + # Metrics with invalid names will be discarded and will not be collected + # by Prometheus. + self._discard_metric = _is_invalid_metric_name(name) + self._name = name + self._description = description + # The default tags key-value pair. + self._default_tags = {} + # Keys of tags. + self._tag_keys = tag_keys or tuple() + # The Cython metric class. This should be set in the child class. + self._metric = None + + if not isinstance(self._tag_keys, tuple): + raise TypeError( + "tag_keys should be a tuple type, got: " f"{type(self._tag_keys)}" + ) + + for key in self._tag_keys: + if not isinstance(key, str): + raise TypeError(f"Tag keys must be str, got {type(key)}.") + + def set_default_tags(self, default_tags: Dict[str, str]): + """Set default tags of metrics. + + Example: + >>> from ray.util.metrics import Counter + >>> # Note that set_default_tags returns the instance itself. + >>> counter = Counter("name", tag_keys=("a",)) + >>> counter2 = counter.set_default_tags({"a": "b"}) + >>> assert counter is counter2 + >>> # this means you can instantiate it in this way. + >>> counter = Counter("name", tag_keys=("a",)).set_default_tags({"a": "b"}) + + Args: + default_tags: Default tags that are + used for every record method. + + Returns: + Metric: it returns the instance itself. + """ + for key, val in default_tags.items(): + if key not in self._tag_keys: + raise ValueError(f"Unrecognized tag key {key}.") + if not isinstance(val, str): + raise TypeError(f"Tag values must be str, got {type(val)}.") + + self._default_tags = default_tags + return self + + def _record( + self, + value: Union[int, float], + tags: Optional[Dict[str, str]] = None, + ) -> None: + """Record the metric point of the metric. + + Tags passed in will take precedence over the metric's default tags. + + Args: + value: The value to be recorded as a metric point. + """ + if self._discard_metric: + return + + assert self._metric is not None + + final_tags = self._get_final_tags(tags) + self._validate_tags(final_tags) + self._metric.record(value, tags=final_tags) + + def _get_final_tags(self, tags): + if not tags: + return self._default_tags + + for val in tags.values(): + if not isinstance(val, str): + raise TypeError(f"Tag values must be str, got {type(val)}.") + + return {**self._default_tags, **tags} + + def _validate_tags(self, final_tags): + missing_tags = [] + for tag_key in self._tag_keys: + # Prefer passed tags over default tags. + if tag_key not in final_tags: + missing_tags.append(tag_key) + + # Strict validation: if any required tag_keys are missing, raise error + if missing_tags: + raise ValueError(f"Missing value for tag key(s): {','.join(missing_tags)}.") + + @property + def info(self) -> Dict[str, Any]: + """Return the information of this metric. + + Example: + >>> from ray.util.metrics import Counter + >>> counter = Counter("name", description="desc") + >>> print(counter.info) + {'name': 'name', 'description': 'desc', 'tag_keys': (), 'default_tags': {}} + """ + return { + "name": self._name, + "description": self._description, + "tag_keys": self._tag_keys, + "default_tags": self._default_tags, + } + + +@DeveloperAPI +class Counter(Metric): + """A cumulative metric that is monotonically increasing. + + This corresponds to Prometheus' counter metric: + https://prometheus.io/docs/concepts/metric_types/#counter + + Before Ray 2.10, this exports a Prometheus gauge metric instead of + a counter metric, which is wrong. + Since 2.10, this exports both counter (with a suffix "_total") and + gauge metrics (for bug compatibility). + Use `RAY_EXPORT_COUNTER_AS_GAUGE=0` to disable exporting the gauge metric. + + Args: + name: Name of the metric. + description: Description of the metric. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, + name: str, + description: str = "", + tag_keys: Optional[Tuple[str, ...]] = None, + ): + super().__init__(name, description, tag_keys) + if self._discard_metric: + self._metric = None + else: + self._metric = CythonCount(self._name, self._description, self._tag_keys) + + def __reduce__(self): + deserializer = self.__class__ + serialized_data = (self._name, self._description, self._tag_keys) + return deserializer, serialized_data + + def inc(self, value: Union[int, float] = 1.0, tags: Dict[str, str] = None): + """Increment the counter by `value` (defaults to 1). + + Tags passed in will take precedence over the metric's default tags. + + Args: + value(int, float): Value to increment the counter by (default=1). + tags(Dict[str, str]): Tags to set or override for this counter. + """ + if not isinstance(value, (int, float)): + raise TypeError(f"value must be int or float, got {type(value)}.") + if value <= 0: + raise ValueError(f"value must be >0, got {value}") + + self._record(value, tags=tags) + + +@DeveloperAPI +class Histogram(Metric): + """Tracks the size and number of events in buckets. + + Histograms allow you to calculate aggregate quantiles + such as 25, 50, 95, 99 percentile latency for an RPC. + + This corresponds to Prometheus' histogram metric: + https://prometheus.io/docs/concepts/metric_types/#histogram + + Args: + name: Name of the metric. + description: Description of the metric. + boundaries: Boundaries of histogram buckets. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, + name: str, + description: str = "", + boundaries: List[float] = None, + tag_keys: Optional[Tuple[str, ...]] = None, + ): + super().__init__(name, description, tag_keys) + if boundaries is None or len(boundaries) == 0: + raise ValueError( + "boundaries argument should be provided when using " + "the Histogram class. e.g., " + 'Histogram("name", boundaries=[1.0, 2.0])' + ) + for i, boundary in enumerate(boundaries): + if boundary <= 0: + raise ValueError( + "Invalid `boundaries` argument at index " + f"{i}, {boundaries}. Use positive values for the arguments." + ) + + self.boundaries = boundaries + if self._discard_metric: + self._metric = None + else: + self._metric = CythonHistogram( + self._name, self._description, self.boundaries, self._tag_keys + ) + + def observe(self, value: Union[int, float], tags: Dict[str, str] = None): + """Observe a given `value` and add it to the appropriate bucket. + + Tags passed in will take precedence over the metric's default tags. + + Args: + value(int, float): Value to set the gauge to. + tags(Dict[str, str]): Tags to set or override for this gauge. + """ + if not isinstance(value, (int, float)): + raise TypeError(f"value must be int or float, got {type(value)}.") + + self._record(value, tags) + + def __reduce__(self): + deserializer = Histogram + serialized_data = ( + self._name, + self._description, + self.boundaries, + self._tag_keys, + ) + return deserializer, serialized_data + + @property + def info(self): + """Return information about histogram metric.""" + info = super().info + info.update({"boundaries": self.boundaries}) + return info + + +@DeveloperAPI +class Gauge(Metric): + """Gauges keep the last recorded value and drop everything before. + + Unlike counters, gauges can go up or down over time. + + This corresponds to Prometheus' gauge metric: + https://prometheus.io/docs/concepts/metric_types/#gauge + + Args: + name: Name of the metric. + description: Description of the metric. + tag_keys: Tag keys of the metric. + """ + + def __init__( + self, + name: str, + description: str = "", + tag_keys: Optional[Tuple[str, ...]] = None, + ): + super().__init__(name, description, tag_keys) + if self._discard_metric: + self._metric = None + else: + self._metric = CythonGauge(self._name, self._description, self._tag_keys) + + def set(self, value: Optional[Union[int, float]], tags: Dict[str, str] = None): + """Set the gauge to the given `value`. + + Tags passed in will take precedence over the metric's default tags. + + Args: + value(int, float): Value to set the gauge to. If `None`, this method is a + no-op. + tags(Dict[str, str]): Tags to set or override for this gauge. + """ + if value is None: + return + + if not isinstance(value, (int, float)): + raise TypeError(f"value must be int or float, got {type(value)}.") + + self._record(value, tags) + + def __reduce__(self): + deserializer = Gauge + serialized_data = (self._name, self._description, self._tag_keys) + return deserializer, serialized_data + + +__all__ = [ + "Counter", + "Histogram", + "Gauge", +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/placement_group.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/placement_group.py new file mode 100644 index 0000000000000000000000000000000000000000..02c45f3804845d484aca52033c707a489254c03a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/placement_group.py @@ -0,0 +1,611 @@ +import warnings +from typing import Dict, List, Optional, Union + +from ray._common.utils import hex_to_binary, PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME +import ray +from ray._private.auto_init_hook import auto_init_ray +from ray._private.client_mode_hook import client_mode_should_convert, client_mode_wrap +from ray._private.utils import get_ray_doc_version +from ray._raylet import PlacementGroupID +from ray.util.annotations import DeveloperAPI, PublicAPI +from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy +from ray._private.label_utils import validate_label_selector + +bundle_reservation_check = None + +VALID_PLACEMENT_GROUP_STRATEGIES = { + "PACK", + "SPREAD", + "STRICT_PACK", + "STRICT_SPREAD", +} + + +# We need to import this method to use for ready API. +# But ray.remote is only available in runtime, and +# if we define this method inside ready method, this function is +# exported whenever ready is called, which can impact performance, +# https://github.com/ray-project/ray/issues/6240. +def _export_bundle_reservation_check_method_if_needed(): + global bundle_reservation_check + if bundle_reservation_check: + return + + @ray.remote(num_cpus=0) + def bundle_reservation_check_func(placement_group): + return placement_group + + bundle_reservation_check = bundle_reservation_check_func + + +@PublicAPI +class PlacementGroup: + """A handle to a placement group.""" + + @staticmethod + def empty() -> "PlacementGroup": + return PlacementGroup(PlacementGroupID.nil()) + + def __init__( + self, + id: "ray._raylet.PlacementGroupID", + bundle_cache: Optional[List[Dict]] = None, + ): + self.id = id + self.bundle_cache = bundle_cache + + @property + def is_empty(self): + return self.id.is_nil() + + def ready(self) -> "ray._raylet.ObjectRef": + """Returns an ObjectRef to check ready status. + + This API runs a small dummy task to wait for placement group creation. + It is compatible to ray.get and ray.wait. + + Example: + .. testcode:: + + import ray + + pg = ray.util.placement_group([{"CPU": 1}]) + ray.get(pg.ready()) + + pg = ray.util.placement_group([{"CPU": 1}]) + ray.wait([pg.ready()]) + + """ + self._fill_bundle_cache_if_needed() + + _export_bundle_reservation_check_method_if_needed() + + assert len(self.bundle_cache) != 0, ( + "ready() cannot be called on placement group object with a " + "bundle length == 0, current bundle length: " + f"{len(self.bundle_cache)}" + ) + + return bundle_reservation_check.options( + scheduling_strategy=PlacementGroupSchedulingStrategy(placement_group=self), + ).remote(self) + + def wait(self, timeout_seconds: Union[float, int] = 30) -> bool: + """Wait for the placement group to be ready within the specified time. + Args: + timeout_seconds(float|int): Timeout in seconds. + Return: + True if the placement group is created. False otherwise. + """ + return _call_placement_group_ready(self.id, timeout_seconds) + + @property + def bundle_specs(self) -> List[Dict]: + """List[Dict]: Return bundles belonging to this placement group.""" + self._fill_bundle_cache_if_needed() + return self.bundle_cache + + @property + def bundle_count(self) -> int: + self._fill_bundle_cache_if_needed() + return len(self.bundle_cache) + + def _fill_bundle_cache_if_needed(self) -> None: + if not self.bundle_cache: + self.bundle_cache = _get_bundle_cache(self.id) + + def __eq__(self, other): + if not isinstance(other, PlacementGroup): + return False + return self.id == other.id + + def __hash__(self): + return hash(self.id) + + +@client_mode_wrap +def _call_placement_group_ready(pg_id: PlacementGroupID, timeout_seconds: int) -> bool: + worker = ray._private.worker.global_worker + worker.check_connected() + + return worker.core_worker.wait_placement_group_ready(pg_id, timeout_seconds) + + +@client_mode_wrap +def _get_bundle_cache(pg_id: PlacementGroupID) -> List[Dict]: + worker = ray._private.worker.global_worker + worker.check_connected() + + return list( + ray._private.state.state.placement_group_table(pg_id)["bundles"].values() + ) + + +@PublicAPI +@client_mode_wrap +def placement_group( + bundles: List[Dict[str, float]], + strategy: str = "PACK", + name: str = "", + lifetime: Optional[str] = None, + _max_cpu_fraction_per_node: float = 1.0, + _soft_target_node_id: Optional[str] = None, + bundle_label_selector: List[Dict[str, str]] = None, +) -> PlacementGroup: + """Asynchronously creates a PlacementGroup. + + Args: + bundles: A list of bundles which + represent the resources requirements. + strategy: The strategy to create the placement group. + + - "PACK": Packs Bundles into as few nodes as possible. + - "SPREAD": Places Bundles across distinct nodes as even as possible. + - "STRICT_PACK": Packs Bundles into one node. The group is + not allowed to span multiple nodes. + - "STRICT_SPREAD": Packs Bundles across distinct nodes. + + name: The name of the placement group. + lifetime: Either `None`, which defaults to the placement group + will fate share with its creator and will be deleted once its + creator is dead, or "detached", which means the placement group + will live as a global object independent of the creator. + _max_cpu_fraction_per_node: (Experimental) Disallow placing bundles on nodes + if it would cause the fraction of CPUs used by bundles from *any* placement + group on the node to exceed this fraction. This effectively sets aside + CPUs that placement groups cannot occupy on nodes. when + `max_cpu_fraction_per_node < 1.0`, at least 1 CPU will be excluded from + placement group scheduling. Note: This feature is experimental and is not + recommended for use with autoscaling clusters (scale-up will not trigger + properly). + _soft_target_node_id: (Private, Experimental) Soft hint where bundles of + this placement group should be placed. + The target node is specified by it's hex ID. + If the target node has no available resources or died, + bundles can be placed elsewhere. + This currently only works with STRICT_PACK pg. + bundle_label_selector: A list of label selectors to apply to a + placement group on a per-bundle level. + + Raises: + ValueError: if bundle type is not a list. + ValueError: if empty bundle or empty resource bundles are given. + ValueError: if the wrong lifetime arguments are given. + + Return: + PlacementGroup: Placement group object. + """ + worker = ray._private.worker.global_worker + worker.check_connected() + + validate_placement_group( + bundles=bundles, + strategy=strategy, + lifetime=lifetime, + _max_cpu_fraction_per_node=_max_cpu_fraction_per_node, + _soft_target_node_id=_soft_target_node_id, + bundle_label_selector=bundle_label_selector, + ) + + if bundle_label_selector is None: + bundle_label_selector = [] + + if lifetime == "detached": + detached = True + else: + detached = False + + placement_group_id = worker.core_worker.create_placement_group( + name, + bundles, + strategy, + detached, + _max_cpu_fraction_per_node, + _soft_target_node_id, + bundle_label_selector, + ) + + return PlacementGroup(placement_group_id) + + +@PublicAPI +@client_mode_wrap +def remove_placement_group(placement_group: PlacementGroup) -> None: + """Asynchronously remove placement group. + + Args: + placement_group: The placement group to delete. + """ + assert placement_group is not None + worker = ray._private.worker.global_worker + worker.check_connected() + + worker.core_worker.remove_placement_group(placement_group.id) + + +@PublicAPI +@client_mode_wrap +def get_placement_group(placement_group_name: str) -> PlacementGroup: + """Get a placement group object with a global name. + + Returns: + None if can't find a placement group with the given name. + The placement group object otherwise. + """ + if not placement_group_name: + raise ValueError("Please supply a non-empty value to get_placement_group") + worker = ray._private.worker.global_worker + worker.check_connected() + placement_group_info = ray._private.state.state.get_placement_group_by_name( + placement_group_name, worker.namespace + ) + if placement_group_info is None: + raise ValueError( + f"Failed to look up placement group with name: {placement_group_name}" + ) + else: + return PlacementGroup( + PlacementGroupID(hex_to_binary(placement_group_info["placement_group_id"])) + ) + + +@DeveloperAPI +@client_mode_wrap +def placement_group_table(placement_group: PlacementGroup = None) -> dict: + """Get the state of the placement group from GCS. + + Args: + placement_group: placement group to see + states. + """ + worker = ray._private.worker.global_worker + worker.check_connected() + placement_group_id = placement_group.id if (placement_group is not None) else None + return ray._private.state.state.placement_group_table(placement_group_id) + + +@PublicAPI +def get_current_placement_group() -> Optional[PlacementGroup]: + """Get the current placement group which a task or actor is using. + + It returns None if there's no current placement group for the worker. + For example, if you call this method in your driver, it returns None + (because drivers never belong to any placement group). + + Examples: + .. testcode:: + + import ray + from ray.util.placement_group import get_current_placement_group + from ray.util.scheduling_strategies import PlacementGroupSchedulingStrategy + + @ray.remote + def f(): + # This returns the placement group the task f belongs to. + # It means this pg is identical to the pg created below. + return get_current_placement_group() + + pg = ray.util.placement_group([{"CPU": 2}]) + assert ray.get(f.options( + scheduling_strategy=PlacementGroupSchedulingStrategy( + placement_group=pg)).remote()) == pg + + # Driver doesn't belong to any placement group, + # so it returns None. + assert get_current_placement_group() is None + + Return: + PlacementGroup: Placement group object. + None if the current task or actor wasn't + created with any placement group. + """ + auto_init_ray() + if client_mode_should_convert(): + # Client mode is only a driver. + return None + worker = ray._private.worker.global_worker + worker.check_connected() + pg_id = worker.placement_group_id + if pg_id.is_nil(): + return None + return PlacementGroup(pg_id) + + +def check_placement_group_index( + placement_group: PlacementGroup, bundle_index: int +) -> None: + assert placement_group is not None + if placement_group.id.is_nil(): + if bundle_index != -1: + raise ValueError( + "If placement group is not set, " + "the value of bundle index must be -1." + ) + elif bundle_index >= placement_group.bundle_count or bundle_index < -1: + raise ValueError( + f"placement group bundle index {bundle_index} " + f"is invalid. Valid placement group indexes: " + f"0-{placement_group.bundle_count}" + ) + + +def validate_placement_group( + bundles: List[Dict[str, float]], + strategy: str = "PACK", + lifetime: Optional[str] = None, + _max_cpu_fraction_per_node: float = 1.0, + _soft_target_node_id: Optional[str] = None, + bundle_label_selector: List[Dict[str, str]] = None, +) -> bool: + """Validates inputs for placement_group. + + Raises ValueError if inputs are invalid. + """ + + assert _max_cpu_fraction_per_node is not None + + if _max_cpu_fraction_per_node != 1.0: + warnings.warn( + "The experimental '_max_cpu_fraction_per_node' option for placement groups " + "is deprecated and will be removed in a future version of Ray." + ) + + if _max_cpu_fraction_per_node <= 0 or _max_cpu_fraction_per_node > 1: + raise ValueError( + "Invalid argument `_max_cpu_fraction_per_node`: " + f"{_max_cpu_fraction_per_node}. " + "_max_cpu_fraction_per_node must be a float between 0 and 1. " + ) + + if _soft_target_node_id and strategy != "STRICT_PACK": + raise ValueError( + "_soft_target_node_id currently only works " + f"with STRICT_PACK but got {strategy}" + ) + + if _soft_target_node_id and ray.NodeID.from_hex(_soft_target_node_id).is_nil(): + raise ValueError( + f"Invalid hex ID of _soft_target_node_id, got {_soft_target_node_id}" + ) + + _validate_bundles(bundles) + + if bundle_label_selector is not None: + if len(bundles) != len(bundle_label_selector): + raise ValueError( + f"Invalid bundle label selector {bundle_label_selector}. " + f"The length of `bundle_label_selector` should equal the length of `bundles`." + ) + _validate_bundle_label_selector(bundle_label_selector) + + if strategy not in VALID_PLACEMENT_GROUP_STRATEGIES: + raise ValueError( + f"Invalid placement group strategy {strategy}. " + f"Supported strategies are: {VALID_PLACEMENT_GROUP_STRATEGIES}." + ) + + if lifetime not in [None, "detached"]: + raise ValueError( + "Placement group `lifetime` argument must be either `None` or " + f"'detached'. Got {lifetime}." + ) + + +def _validate_bundles(bundles: List[Dict[str, float]]): + """Validates each bundle and raises a ValueError if any bundle is invalid.""" + + if not isinstance(bundles, list): + raise ValueError( + "Placement group bundles must be a list, " f"got {type(bundles)}." + ) + + if len(bundles) == 0: + raise ValueError( + "Bundles must be a non-empty list of resource " + 'dictionaries. For example: `[{"CPU": 1.0}, {"GPU": 1.0}]`. ' + "Got empty list instead." + ) + + for bundle in bundles: + if ( + not isinstance(bundle, dict) + or not all(isinstance(k, str) for k in bundle.keys()) + or not all(isinstance(v, (int, float)) for v in bundle.values()) + ): + raise ValueError( + "Bundles must be a non-empty list of " + "resource dictionaries. For example: " + '`[{"CPU": 1.0}, {"GPU": 1.0}]`.' + ) + + if len(bundle) == 0 or all( + resource_value == 0 for resource_value in bundle.values() + ): + raise ValueError( + "Bundles cannot be an empty dictionary or " + f"resources with only 0 values. Bundles: {bundles}" + ) + + if "object_store_memory" in bundle.keys(): + warnings.warn( + "Setting 'object_store_memory' for" + " bundles is deprecated since it doesn't actually" + " reserve the required object store memory." + f" Use object spilling that's enabled by default (https://docs.ray.io/en/{get_ray_doc_version()}/ray-core/objects/object-spilling.html) " # noqa: E501 + "instead to bypass the object store memory size limitation.", + DeprecationWarning, + stacklevel=1, + ) + + +def _validate_bundle_label_selector(bundle_label_selector: List[Dict[str, str]]): + """Validates each label selector and raises a ValueError if any label selector is invalid.""" + + if not isinstance(bundle_label_selector, list): + raise ValueError( + "Placement group bundle_label_selector must be a list, " + f"got {type(bundle_label_selector)}." + ) + + if len(bundle_label_selector) == 0: + # No label selectors provided, no-op. + return + + for label_selector in bundle_label_selector: + if ( + not isinstance(label_selector, dict) + or not all(isinstance(k, str) for k in label_selector.keys()) + or not all(isinstance(v, str) for v in label_selector.values()) + ): + raise ValueError( + "Bundle label selector must be a list of string dictionary" + " label selectors. For example: " + '`[{ray.io/market_type": "spot"}, {"ray.io/accelerator-type": "A100"}]`.' + ) + # Call helper function to validate label selector key-value syntax. + error_message = validate_label_selector(label_selector) + if error_message: + raise ValueError( + f"Invalid label selector provided in bundle_label_selector list." + f" Detailed error: '{error_message}'" + ) + + +def _valid_resource_shape(resources, bundle_specs): + """ + If the resource shape cannot fit into every + bundle spec, return False + """ + for bundle in bundle_specs: + fit_in_bundle = True + for resource, requested_val in resources.items(): + # Skip "bundle" resource as it is automatically added + # to all nodes with bundles by the placement group. + if resource == PLACEMENT_GROUP_BUNDLE_RESOURCE_NAME: + continue + if bundle.get(resource, 0) < requested_val: + fit_in_bundle = False + break + if fit_in_bundle: + # If resource request fits in any bundle, it is valid. + return True + return False + + +def _validate_resource_shape( + placement_group, resources, placement_resources, task_or_actor_repr +): + bundles = placement_group.bundle_specs + resources_valid = _valid_resource_shape(resources, bundles) + placement_resources_valid = _valid_resource_shape(placement_resources, bundles) + + if not resources_valid: + raise ValueError( + f"Cannot schedule {task_or_actor_repr} with " + "the placement group because the resource request " + f"{resources} cannot fit into any bundles for " + f"the placement group, {bundles}." + ) + if not placement_resources_valid: + # Happens for the default actor case. + # placement_resources is not an exposed concept to users, + # so we should write more specialized error messages. + raise ValueError( + f"Cannot schedule {task_or_actor_repr} with " + "the placement group because the actor requires " + f"{placement_resources.get('CPU', 0)} CPU for " + "creation, but it cannot " + f"fit into any bundles for the placement group, " + f"{bundles}. Consider " + "creating a placement group with CPU resources." + ) + + +def _configure_placement_group_based_on_context( + placement_group_capture_child_tasks: bool, + bundle_index: int, + resources: Dict, + placement_resources: Dict, + task_or_actor_repr: str, + placement_group: Union[PlacementGroup, str, None] = "default", +) -> PlacementGroup: + """Configure the placement group based on the given context. + + Based on the given context, this API returns the placement group instance + for task/actor scheduling. + + Params: + placement_group_capture_child_tasks: Whether or not the + placement group needs to be captured from the global + context. + bundle_index: The bundle index for tasks/actor scheduling. + resources: The scheduling resources. + placement_resources: The scheduling placement resources for + actors. + task_or_actor_repr: The repr of task or actor + function/class descriptor. + placement_group: The placement group instance. + - "default": Default placement group argument. Currently, + the default behavior is to capture the parent task' + placement group if placement_group_capture_child_tasks + is set. + - None: means placement group is explicitly not configured. + - Placement group instance: In this case, do nothing. + + Returns: + Placement group instance based on the given context. + + Raises: + ValueError: If the bundle index is invalid for the placement group + or the requested resources shape doesn't fit to any + bundles. + """ + # Validate inputs. + assert placement_group_capture_child_tasks is not None + assert resources is not None + + # Validate and get the PlacementGroup instance. + # Placement group could be None, default, or placement group. + # Default behavior is "do not capture child tasks". + if placement_group != "default": + if not placement_group: + placement_group = PlacementGroup.empty() + elif placement_group == "default": + if placement_group_capture_child_tasks: + placement_group = get_current_placement_group() + else: + placement_group = PlacementGroup.empty() + + if not placement_group: + placement_group = PlacementGroup.empty() + assert isinstance(placement_group, PlacementGroup) + + # Validate the index. + check_placement_group_index(placement_group, bundle_index) + + # Validate the shape. + if not placement_group.is_empty: + _validate_resource_shape( + placement_group, resources, placement_resources, task_or_actor_repr + ) + return placement_group diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/queue.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/queue.py new file mode 100644 index 0000000000000000000000000000000000000000..b714bfb7f7f5a0256a6c980602ba4c0e13f321a7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/queue.py @@ -0,0 +1,306 @@ +import asyncio +import queue +from typing import Optional, Any, List, Dict +from collections.abc import Iterable + +import ray +from ray.util.annotations import PublicAPI + + +@PublicAPI(stability="beta") +class Empty(queue.Empty): + pass + + +@PublicAPI(stability="beta") +class Full(queue.Full): + pass + + +@PublicAPI(stability="beta") +class Queue: + """A first-in, first-out queue implementation on Ray. + + The behavior and use cases are similar to those of the asyncio.Queue class. + + Features both sync and async put and get methods. Provides the option to + block until space is available when calling put on a full queue, + or to block until items are available when calling get on an empty queue. + + Optionally supports batched put and get operations to minimize + serialization overhead. + + Args: + maxsize (optional, int): maximum size of the queue. If zero, size is + unbounded. + actor_options (optional, Dict): Dictionary of options to pass into + the QueueActor during creation. These are directly passed into + QueueActor.options(...). This could be useful if you + need to pass in custom resource requirements, for example. + + Examples: + .. testcode:: + + from ray.util.queue import Queue + q = Queue() + items = list(range(10)) + for item in items: + q.put(item) + for item in items: + assert item == q.get() + # Create Queue with the underlying actor reserving 1 CPU. + q = Queue(actor_options={"num_cpus": 1}) + """ + + def __init__(self, maxsize: int = 0, actor_options: Optional[Dict] = None) -> None: + from ray._private.usage.usage_lib import record_library_usage + + record_library_usage("util.Queue") + + actor_options = actor_options or {} + self.maxsize = maxsize + self.actor = ( + ray.remote(_QueueActor).options(**actor_options).remote(self.maxsize) + ) + + def __len__(self) -> int: + return self.size() + + def size(self) -> int: + """The size of the queue.""" + return ray.get(self.actor.qsize.remote()) + + def qsize(self) -> int: + """The size of the queue.""" + return self.size() + + def empty(self) -> bool: + """Whether the queue is empty.""" + return ray.get(self.actor.empty.remote()) + + def full(self) -> bool: + """Whether the queue is full.""" + return ray.get(self.actor.full.remote()) + + def put( + self, item: Any, block: bool = True, timeout: Optional[float] = None + ) -> None: + """Adds an item to the queue. + + If block is True and the queue is full, blocks until the queue is no + longer full or until timeout. + + There is no guarantee of order if multiple producers put to the same + full queue. + + Raises: + Full: if the queue is full and blocking is False. + Full: if the queue is full, blocking is True, and it timed out. + ValueError: if timeout is negative. + """ + if not block: + try: + ray.get(self.actor.put_nowait.remote(item)) + except asyncio.QueueFull: + raise Full + else: + if timeout is not None and timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + else: + ray.get(self.actor.put.remote(item, timeout)) + + async def put_async( + self, item: Any, block: bool = True, timeout: Optional[float] = None + ) -> None: + """Adds an item to the queue. + + If block is True and the queue is full, + blocks until the queue is no longer full or until timeout. + + There is no guarantee of order if multiple producers put to the same + full queue. + + Raises: + Full: if the queue is full and blocking is False. + Full: if the queue is full, blocking is True, and it timed out. + ValueError: if timeout is negative. + """ + if not block: + try: + await self.actor.put_nowait.remote(item) + except asyncio.QueueFull: + raise Full + else: + if timeout is not None and timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + else: + await self.actor.put.remote(item, timeout) + + def get(self, block: bool = True, timeout: Optional[float] = None) -> Any: + """Gets an item from the queue. + + If block is True and the queue is empty, blocks until the queue is no + longer empty or until timeout. + + There is no guarantee of order if multiple consumers get from the + same empty queue. + + Returns: + The next item in the queue. + + Raises: + Empty: if the queue is empty and blocking is False. + Empty: if the queue is empty, blocking is True, and it timed out. + ValueError: if timeout is negative. + """ + if not block: + try: + return ray.get(self.actor.get_nowait.remote()) + except asyncio.QueueEmpty: + raise Empty + else: + if timeout is not None and timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + else: + return ray.get(self.actor.get.remote(timeout)) + + async def get_async( + self, block: bool = True, timeout: Optional[float] = None + ) -> Any: + """Gets an item from the queue. + + There is no guarantee of order if multiple consumers get from the + same empty queue. + + Returns: + The next item in the queue. + Raises: + Empty: if the queue is empty and blocking is False. + Empty: if the queue is empty, blocking is True, and it timed out. + ValueError: if timeout is negative. + """ + if not block: + try: + return await self.actor.get_nowait.remote() + except asyncio.QueueEmpty: + raise Empty + else: + if timeout is not None and timeout < 0: + raise ValueError("'timeout' must be a non-negative number") + else: + return await self.actor.get.remote(timeout) + + def put_nowait(self, item: Any) -> None: + """Equivalent to put(item, block=False). + + Raises: + Full: if the queue is full. + """ + return self.put(item, block=False) + + def put_nowait_batch(self, items: Iterable) -> None: + """Takes in a list of items and puts them into the queue in order. + + Raises: + Full: if the items will not fit in the queue + """ + if not isinstance(items, Iterable): + raise TypeError("Argument 'items' must be an Iterable") + + ray.get(self.actor.put_nowait_batch.remote(items)) + + def get_nowait(self) -> Any: + """Equivalent to get(block=False). + + Raises: + Empty: if the queue is empty. + """ + return self.get(block=False) + + def get_nowait_batch(self, num_items: int) -> List[Any]: + """Gets items from the queue and returns them in a + list in order. + + Raises: + Empty: if the queue does not contain the desired number of items + """ + if not isinstance(num_items, int): + raise TypeError("Argument 'num_items' must be an int") + if num_items < 0: + raise ValueError("'num_items' must be nonnegative") + + return ray.get(self.actor.get_nowait_batch.remote(num_items)) + + def shutdown(self, force: bool = False, grace_period_s: int = 5) -> None: + """Terminates the underlying QueueActor. + + All of the resources reserved by the queue will be released. + + Args: + force: If True, forcefully kill the actor, causing an + immediate failure. If False, graceful + actor termination will be attempted first, before falling back + to a forceful kill. + grace_period_s: If force is False, how long in seconds to + wait for graceful termination before falling back to + forceful kill. + """ + if self.actor: + if force: + ray.kill(self.actor, no_restart=True) + else: + done_ref = self.actor.__ray_terminate__.remote() + done, not_done = ray.wait([done_ref], timeout=grace_period_s) + if not_done: + ray.kill(self.actor, no_restart=True) + self.actor = None + + +class _QueueActor: + def __init__(self, maxsize): + self.maxsize = maxsize + self.queue = asyncio.Queue(self.maxsize) + + def qsize(self): + return self.queue.qsize() + + def empty(self): + return self.queue.empty() + + def full(self): + return self.queue.full() + + async def put(self, item, timeout=None): + try: + await asyncio.wait_for(self.queue.put(item), timeout) + except asyncio.TimeoutError: + raise Full + + async def get(self, timeout=None): + try: + return await asyncio.wait_for(self.queue.get(), timeout) + except asyncio.TimeoutError: + raise Empty + + def put_nowait(self, item): + self.queue.put_nowait(item) + + def put_nowait_batch(self, items): + # If maxsize is 0, queue is unbounded, so no need to check size. + if self.maxsize > 0 and len(items) + self.qsize() > self.maxsize: + raise Full( + f"Cannot add {len(items)} items to queue of size " + f"{self.qsize()} and maxsize {self.maxsize}." + ) + for item in items: + self.queue.put_nowait(item) + + def get_nowait(self): + return self.queue.get_nowait() + + def get_nowait_batch(self, num_items): + if num_items > self.qsize(): + raise Empty( + f"Cannot get {num_items} items from queue of size " f"{self.qsize()}." + ) + return [self.queue.get_nowait() for _ in range(num_items)] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/rpdb.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/rpdb.py new file mode 100644 index 0000000000000000000000000000000000000000..20ac1680856cf4a61600afb5a1542b568194975e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/rpdb.py @@ -0,0 +1,378 @@ +# Some code in this file is from +# https://github.com/ionelmc/python-remote-pdb/blob/07d563331c4ab9eb45731bb272b158816d98236e/src/remote_pdb.py +# (BSD 2-Clause "Simplified" License) + +import errno +import inspect +import json +import logging +import os +import re +import select +import socket +import sys +import time +import traceback +import uuid +from pdb import Pdb +from typing import Callable + +import ray +from ray._private import ray_constants +from ray.experimental.internal_kv import _internal_kv_del, _internal_kv_put +from ray.util.annotations import DeveloperAPI + +log = logging.getLogger(__name__) + + +def _cry(message, stderr=sys.__stderr__): + print(message, file=stderr) + stderr.flush() + + +class _LF2CRLF_FileWrapper(object): + def __init__(self, connection): + self.connection = connection + self.stream = fh = connection.makefile("rw") + self.read = fh.read + self.readline = fh.readline + self.readlines = fh.readlines + self.close = fh.close + self.flush = fh.flush + self.fileno = fh.fileno + if hasattr(fh, "encoding"): + self._send = lambda data: connection.sendall( + data.encode(fh.encoding, errors="replace") + ) + else: + self._send = connection.sendall + + @property + def encoding(self): + return self.stream.encoding + + def __iter__(self): + return self.stream.__iter__() + + def write(self, data, nl_rex=re.compile("\r?\n")): + data = nl_rex.sub("\r\n", data) + self._send(data) + + def writelines(self, lines, nl_rex=re.compile("\r?\n")): + for line in lines: + self.write(line, nl_rex) + + +class _PdbWrap(Pdb): + """Wrap PDB to run a custom exit hook on continue.""" + + def __init__(self, exit_hook: Callable[[], None]): + self._exit_hook = exit_hook + Pdb.__init__(self) + + def do_continue(self, arg): + self._exit_hook() + return Pdb.do_continue(self, arg) + + do_c = do_cont = do_continue + + +class _RemotePdb(Pdb): + """ + This will run pdb as a ephemeral telnet service. Once you connect no one + else can connect. On construction this object will block execution till a + client has connected. + Based on https://github.com/tamentis/rpdb I think ... + To use this:: + RemotePdb(host="0.0.0.0", port=4444).set_trace() + Then run: telnet 127.0.0.1 4444 + """ + + active_instance = None + + def __init__( + self, + breakpoint_uuid, + host, + port, + ip_address, + patch_stdstreams=False, + quiet=False, + ): + self._breakpoint_uuid = breakpoint_uuid + self._quiet = quiet + self._patch_stdstreams = patch_stdstreams + self._listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self._listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) + self._listen_socket.bind((host, port)) + self._ip_address = ip_address + + def listen(self): + if not self._quiet: + _cry( + "RemotePdb session open at %s:%s, " + "use 'ray debug' to connect..." + % (self._ip_address, self._listen_socket.getsockname()[1]) + ) + self._listen_socket.listen(1) + connection, address = self._listen_socket.accept() + if not self._quiet: + _cry(f"RemotePdb accepted connection from {address}") + self.handle = _LF2CRLF_FileWrapper(connection) + Pdb.__init__( + self, + completekey="tab", + stdin=self.handle, + stdout=self.handle, + skip=["ray.*"], + ) + self.backup = [] + if self._patch_stdstreams: + for name in ( + "stderr", + "stdout", + "__stderr__", + "__stdout__", + "stdin", + "__stdin__", + ): + self.backup.append((name, getattr(sys, name))) + setattr(sys, name, self.handle) + _RemotePdb.active_instance = self + + def __restore(self): + if self.backup and not self._quiet: + _cry("Restoring streams: %s ..." % self.backup) + for name, fh in self.backup: + setattr(sys, name, fh) + self.handle.close() + _RemotePdb.active_instance = None + + def do_quit(self, arg): + self.__restore() + return Pdb.do_quit(self, arg) + + do_q = do_exit = do_quit + + def do_continue(self, arg): + self.__restore() + self.handle.connection.close() + return Pdb.do_continue(self, arg) + + do_c = do_cont = do_continue + + def set_trace(self, frame=None): + if frame is None: + frame = sys._getframe().f_back + try: + Pdb.set_trace(self, frame) + except IOError as exc: + if exc.errno != errno.ECONNRESET: + raise + + def post_mortem(self, traceback=None): + # See https://github.com/python/cpython/blob/ + # 022bc7572f061e1d1132a4db9d085b29707701e7/Lib/pdb.py#L1617 + try: + t = sys.exc_info()[2] + self.reset() + Pdb.interaction(self, None, t) + except IOError as exc: + if exc.errno != errno.ECONNRESET: + raise + + def do_remote(self, arg): + """remote + Skip into the next remote call. + """ + # Tell the next task to drop into the debugger. + ray._private.worker.global_worker.debugger_breakpoint = self._breakpoint_uuid + # Tell the debug loop to connect to the next task. + data = json.dumps( + { + "job_id": ray.get_runtime_context().get_job_id(), + } + ) + _internal_kv_put( + "RAY_PDB_CONTINUE_{}".format(self._breakpoint_uuid), + data, + namespace=ray_constants.KV_NAMESPACE_PDB, + ) + self.__restore() + self.handle.connection.close() + return Pdb.do_continue(self, arg) + + def do_get(self, arg): + """get + Skip to where the current task returns to. + """ + ray._private.worker.global_worker.debugger_get_breakpoint = ( + self._breakpoint_uuid + ) + self.__restore() + self.handle.connection.close() + return Pdb.do_continue(self, arg) + + +def _connect_ray_pdb( + host=None, + port=None, + patch_stdstreams=False, + quiet=None, + breakpoint_uuid=None, + debugger_external=False, +): + """ + Opens a remote PDB on first available port. + """ + if debugger_external: + assert not host, "Cannot specify both host and debugger_external" + host = "0.0.0.0" + elif host is None: + host = os.environ.get("REMOTE_PDB_HOST", "127.0.0.1") + if port is None: + port = int(os.environ.get("REMOTE_PDB_PORT", "0")) + if quiet is None: + quiet = bool(os.environ.get("REMOTE_PDB_QUIET", "")) + if not breakpoint_uuid: + breakpoint_uuid = uuid.uuid4().hex + if debugger_external: + ip_address = ray._private.worker.global_worker.node_ip_address + else: + ip_address = "localhost" + rdb = _RemotePdb( + breakpoint_uuid=breakpoint_uuid, + host=host, + port=port, + ip_address=ip_address, + patch_stdstreams=patch_stdstreams, + quiet=quiet, + ) + sockname = rdb._listen_socket.getsockname() + pdb_address = "{}:{}".format(ip_address, sockname[1]) + parentframeinfo = inspect.getouterframes(inspect.currentframe())[2] + data = { + "proctitle": ray._raylet.getproctitle(), + "pdb_address": pdb_address, + "filename": parentframeinfo.filename, + "lineno": parentframeinfo.lineno, + "traceback": "\n".join(traceback.format_exception(*sys.exc_info())), + "timestamp": time.time(), + "job_id": ray.get_runtime_context().get_job_id(), + "node_id": ray.get_runtime_context().get_node_id(), + "worker_id": ray.get_runtime_context().get_worker_id(), + "actor_id": ray.get_runtime_context().get_actor_id(), + "task_id": ray.get_runtime_context().get_task_id(), + } + _internal_kv_put( + "RAY_PDB_{}".format(breakpoint_uuid), + json.dumps(data), + overwrite=True, + namespace=ray_constants.KV_NAMESPACE_PDB, + ) + rdb.listen() + _internal_kv_del( + "RAY_PDB_{}".format(breakpoint_uuid), namespace=ray_constants.KV_NAMESPACE_PDB + ) + + return rdb + + +@DeveloperAPI +def set_trace(breakpoint_uuid=None): + """Interrupt the flow of the program and drop into the Ray debugger. + + Can be used within a Ray task or actor. + """ + if os.environ.get("RAY_DEBUG", "1") == "1": + return ray.util.ray_debugpy.set_trace(breakpoint_uuid) + if os.environ.get("RAY_DEBUG", "1") == "legacy": + # If there is an active debugger already, we do not want to + # start another one, so "set_trace" is just a no-op in that case. + if ray._private.worker.global_worker.debugger_breakpoint == b"": + frame = sys._getframe().f_back + rdb = _connect_ray_pdb( + host=None, + port=None, + patch_stdstreams=False, + quiet=None, + breakpoint_uuid=breakpoint_uuid.decode() if breakpoint_uuid else None, + debugger_external=ray._private.worker.global_worker.ray_debugger_external, # noqa: E501 + ) + rdb.set_trace(frame=frame) + + +def _driver_set_trace(): + """The breakpoint hook to use for the driver. + + This disables Ray driver logs temporarily so that the PDB console is not + spammed: https://github.com/ray-project/ray/issues/18172 + """ + if os.environ.get("RAY_DEBUG", "1") == "1": + return ray.util.ray_debugpy.set_trace() + if os.environ.get("RAY_DEBUG", "1") == "legacy": + print("*** Temporarily disabling Ray worker logs ***") + ray._private.worker._worker_logs_enabled = False + + def enable_logging(): + print("*** Re-enabling Ray worker logs ***") + ray._private.worker._worker_logs_enabled = True + + pdb = _PdbWrap(enable_logging) + frame = sys._getframe().f_back + pdb.set_trace(frame) + + +def _is_ray_debugger_post_mortem_enabled(): + return os.environ.get("RAY_DEBUG_POST_MORTEM", "0") == "1" + + +def _post_mortem(): + if os.environ.get("RAY_DEBUG", "1") == "1": + return ray.util.ray_debugpy._post_mortem() + + rdb = _connect_ray_pdb( + host=None, + port=None, + patch_stdstreams=False, + quiet=None, + debugger_external=ray._private.worker.global_worker.ray_debugger_external, + ) + rdb.post_mortem() + + +def _connect_pdb_client(host, port): + if sys.platform == "win32": + import msvcrt + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((host, port)) + + while True: + # Get the list of sockets which are readable. + if sys.platform == "win32": + ready_to_read = select.select([s], [], [], 1)[0] + if msvcrt.kbhit(): + ready_to_read.append(sys.stdin) + if not ready_to_read and not sys.stdin.isatty(): + # in tests, when using pexpect, the pipe makes + # the msvcrt.kbhit() trick fail. Assume we are waiting + # for stdin, since this will block waiting for input + ready_to_read.append(sys.stdin) + else: + ready_to_read, write_sockets, error_sockets = select.select( + [sys.stdin, s], [], [] + ) + + for sock in ready_to_read: + if sock == s: + # Incoming message from remote debugger. + data = sock.recv(4096) + if not data: + return + else: + sys.stdout.write(data.decode()) + sys.stdout.flush() + else: + # User entered a message. + msg = sys.stdin.readline() + s.send(msg.encode()) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/scheduling_strategies.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/scheduling_strategies.py new file mode 100644 index 0000000000000000000000000000000000000000..b283aed5046541749487294df751da978faecc3f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/scheduling_strategies.py @@ -0,0 +1,197 @@ +from typing import Dict, Union, Optional, TYPE_CHECKING +from ray.util.annotations import PublicAPI + +if TYPE_CHECKING: + from ray.util.placement_group import PlacementGroup + +# "DEFAULT": The default hybrid scheduling strategy +# based on config scheduler_spread_threshold. +# This disables any potential placement group capture. + +# "SPREAD": Spread scheduling on a best effort basis. + + +@PublicAPI +class PlacementGroupSchedulingStrategy: + """Placement group based scheduling strategy. + + Attributes: + placement_group: the placement group this actor belongs to, + or None if it doesn't belong to any group. + placement_group_bundle_index: the index of the bundle + if the actor belongs to a placement group, which may be -1 to + specify any available bundle. + placement_group_capture_child_tasks: Whether or not children tasks + of this actor should implicitly use the same placement group + as its parent. It is False by default. + """ + + def __init__( + self, + placement_group: "PlacementGroup", + placement_group_bundle_index: int = -1, + placement_group_capture_child_tasks: Optional[bool] = None, + ): + self.placement_group = placement_group + self.placement_group_bundle_index = placement_group_bundle_index + self.placement_group_capture_child_tasks = placement_group_capture_child_tasks + + +@PublicAPI +class NodeAffinitySchedulingStrategy: + """Static scheduling strategy used to run a task or actor on a particular node. + + Attributes: + node_id: the hex id of the node where the task or actor should run. + soft: whether the scheduler should run the task or actor somewhere else + if the target node doesn't exist (e.g. the node dies) or is infeasible + during scheduling. + If the node exists and is feasible, the task or actor + will only be scheduled there. + This means if the node doesn't have the available resources, + the task or actor will wait indefinitely until resources become available. + If the node doesn't exist or is infeasible, the task or actor + will fail if soft is False + or be scheduled somewhere else if soft is True. + """ + + def __init__( + self, + node_id: str, + soft: bool, + _spill_on_unavailable: bool = False, + _fail_on_unavailable: bool = False, + ): + # This will be removed once we standardize on node id being hex string. + if not isinstance(node_id, str): + node_id = node_id.hex() + + self.node_id = node_id + self.soft = soft + self._spill_on_unavailable = _spill_on_unavailable + self._fail_on_unavailable = _fail_on_unavailable + + +def _validate_label_match_operator_values(values, operator): + if not values: + raise ValueError( + f"The variadic parameter of the {operator} operator" + f' must be a non-empty tuple: e.g. {operator}("value1", "value2").' + ) + + index = 0 + for value in values: + if not isinstance(value, str): + raise ValueError( + f"Type of value in position {index} for the {operator} operator " + f'must be str (e.g. {operator}("value1", "value2")) ' + f"but got {str(value)} of type {type(value)}." + ) + index = index + 1 + + +@PublicAPI(stability="alpha") +class In: + def __init__(self, *values): + _validate_label_match_operator_values(values, "In") + self.values = list(values) + + +@PublicAPI(stability="alpha") +class NotIn: + def __init__(self, *values): + _validate_label_match_operator_values(values, "NotIn") + self.values = list(values) + + +@PublicAPI(stability="alpha") +class Exists: + def __init__(self): + pass + + +@PublicAPI(stability="alpha") +class DoesNotExist: + def __init__(self): + pass + + +class _LabelMatchExpression: + """An expression used to select node by node's labels + Attributes: + key: the key of label + operator: In、NotIn、Exists、DoesNotExist + """ + + def __init__(self, key: str, operator: Union[In, NotIn, Exists, DoesNotExist]): + self.key = key + self.operator = operator + + +LabelMatchExpressionsT = Dict[str, Union[In, NotIn, Exists, DoesNotExist]] + + +@PublicAPI(stability="alpha") +class NodeLabelSchedulingStrategy: + """ + Label based node affinity scheduling strategy + + scheduling_strategy=NodeLabelSchedulingStrategy({ + "region": In("us"), + "gpu_type": Exists(), + }) + """ + + def __init__( + self, hard: LabelMatchExpressionsT, *, soft: LabelMatchExpressionsT = None + ): + self.hard = _convert_map_to_expressions(hard, "hard") + self.soft = _convert_map_to_expressions(soft, "soft") + self._check_usage() + + def _check_usage(self): + if not (self.hard or self.soft): + raise ValueError( + "The `hard` and `soft` parameter " + "of NodeLabelSchedulingStrategy cannot both be empty." + ) + + +def _convert_map_to_expressions(map_expressions: LabelMatchExpressionsT, param: str): + expressions = [] + if map_expressions is None: + return expressions + + if not isinstance(map_expressions, Dict): + raise ValueError( + f'The {param} parameter must be a map (e.g. {{"key1": In("value1")}}) ' + f"but got type {type(map_expressions)}." + ) + + for key, value in map_expressions.items(): + if not isinstance(key, str): + raise ValueError( + f"The map key of the {param} parameter must " + f'be of type str (e.g. {{"key1": In("value1")}}) ' + f"but got {str(key)} of type {type(key)}." + ) + + if not isinstance(value, (In, NotIn, Exists, DoesNotExist)): + raise ValueError( + f"The map value for key {key} of the {param} parameter " + f"must be one of the `In`, `NotIn`, `Exists` or `DoesNotExist` " + f'operator (e.g. {{"key1": In("value1")}}) ' + f"but got {str(value)} of type {type(value)}." + ) + + expressions.append(_LabelMatchExpression(key, value)) + return expressions + + +SchedulingStrategyT = Union[ + None, + str, # Literal["DEFAULT", "SPREAD"] + PlacementGroupSchedulingStrategy, + NodeAffinitySchedulingStrategy, + NodeLabelSchedulingStrategy, +] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/serialization.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..106e06c8681bc959db3f9ae7e0c64e5c0187bb38 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/serialization.py @@ -0,0 +1,55 @@ +import ray +import ray.cloudpickle as pickle +from ray.util.annotations import DeveloperAPI, PublicAPI + + +@PublicAPI +def register_serializer(cls: type, *, serializer: callable, deserializer: callable): + """Use the given serializer to serialize instances of type ``cls``, + and use the deserializer to deserialize the serialized object. + + Args: + cls: A Python class/type. + serializer: A function that converts an instances of + type ``cls`` into a serializable object (e.g. python dict + of basic objects). + deserializer: A function that constructs the + instance of type ``cls`` from the serialized object. + This function itself must be serializable. + """ + context = ray._private.worker.global_worker.get_serialization_context() + context._register_cloudpickle_serializer(cls, serializer, deserializer) + + +@PublicAPI +def deregister_serializer(cls: type): + """Deregister the serializer associated with the type ``cls``. + There is no effect if the serializer is unavailable. + + Args: + cls: A Python class/type. + """ + context = ray._private.worker.global_worker.get_serialization_context() + context._unregister_cloudpickle_reducer(cls) + + +@DeveloperAPI +class StandaloneSerializationContext: + # NOTE(simon): Used for registering custom serializers. We cannot directly + # use the SerializationContext because it requires Ray workers. Please + # make sure to keep the API consistent. + + def _register_cloudpickle_reducer(self, cls, reducer): + pickle.CloudPickler.dispatch[cls] = reducer + + def _unregister_cloudpickle_reducer(self, cls): + pickle.CloudPickler.dispatch.pop(cls, None) + + def _register_cloudpickle_serializer( + self, cls, custom_serializer, custom_deserializer + ): + def _CloudPicklerReducer(obj): + return custom_deserializer, (custom_serializer(obj),) + + # construct a reducer + pickle.CloudPickler.dispatch[cls] = _CloudPicklerReducer diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/serialization_addons.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/serialization_addons.py new file mode 100644 index 0000000000000000000000000000000000000000..497a4269b0df731d78cde51d07910f1c0b48af69 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/serialization_addons.py @@ -0,0 +1,39 @@ +""" +This module is intended for implementing internal serializers for some +site packages. +""" + +import sys + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +def register_starlette_serializer(serialization_context): + try: + import starlette.datastructures + except ImportError: + return + + # Starlette's app.state object is not serializable + # because it overrides __getattr__ + serialization_context._register_cloudpickle_serializer( + starlette.datastructures.State, + custom_serializer=lambda s: s._state, + custom_deserializer=lambda s: starlette.datastructures.State(s), + ) + + +@DeveloperAPI +def apply(serialization_context): + from ray._common.pydantic_compat import register_pydantic_serializers + + register_pydantic_serializers(serialization_context) + register_starlette_serializer(serialization_context) + + if sys.platform != "win32": + from ray._private.arrow_serialization import ( + _register_custom_datasets_serializers, + ) + + _register_custom_datasets_serializers(serialization_context) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/timer.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/timer.py new file mode 100644 index 0000000000000000000000000000000000000000..2f36aef155ea4dfaf4c693642b4bcf4e1054d046 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/util/timer.py @@ -0,0 +1,65 @@ +import time + + +class _Timer: + """A running stat for conveniently logging the duration of a code block. + + Example: + wait_timer = TimerStat() + with wait_timer: + ray.wait(...) + + Note that this class is *not* thread-safe. + """ + + def __init__(self, window_size=10): + self._window_size = window_size + self._samples = [] + self._units_processed = [] + self._start_time = None + self._total_time = 0.0 + self.count = 0 + + def __enter__(self): + assert self._start_time is None, "concurrent updates not supported" + self._start_time = time.time() + + def __exit__(self, exc_type, exc_value, tb): + assert self._start_time is not None + time_delta = time.time() - self._start_time + self.push(time_delta) + self._start_time = None + + def push(self, time_delta): + self._samples.append(time_delta) + if len(self._samples) > self._window_size: + self._samples.pop(0) + self.count += 1 + self._total_time += time_delta + + def push_units_processed(self, n): + self._units_processed.append(n) + if len(self._units_processed) > self._window_size: + self._units_processed.pop(0) + + def has_units_processed(self): + return len(self._units_processed) > 0 + + @property + def mean(self): + if len(self._samples) == 0: + return 0.0 + return float(sum(self._samples)) / len(self._samples) + + @property + def mean_units_processed(self): + if len(self._units_processed) == 0: + return 0.0 + return float(sum(self._units_processed)) / len(self._units_processed) + + @property + def mean_throughput(self): + time_total = float(sum(self._samples)) + if not time_total: + return 0.0 + return float(sum(self._units_processed)) / time_total diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2479501640ba3f2b0be30c3548ee465a13a481a9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/__init__.py @@ -0,0 +1,4 @@ +from ray.widgets.render import Template +from ray.widgets.util import make_table_html_repr + +__all__ = ["Template", "make_table_html_repr"] diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/render.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/render.py new file mode 100644 index 0000000000000000000000000000000000000000..f9e861d39925680c403ff996e9279d4d349bafe5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/render.py @@ -0,0 +1,39 @@ +import pathlib +from typing import List + +from ray.util.annotations import DeveloperAPI + + +@DeveloperAPI +class Template: + """Class which provides basic HTML templating.""" + + def __init__(self, file: str): + with open(pathlib.Path(__file__).parent / "templates" / file, "r") as f: + self.template = f.read() + + def render(self, **kwargs) -> str: + """Render an HTML template with the given data. + + This is done by replacing instances of `{{ key }}` with `value` + from the keyword arguments. + + Returns: + HTML template with the keys of the kwargs replaced with corresponding + values. + """ + rendered = self.template + for key, value in kwargs.items(): + if isinstance(value, List): + value = "".join(value) + rendered = rendered.replace("{{ " + key + " }}", value if value else "") + return rendered + + @staticmethod + def list_templates() -> List[pathlib.Path]: + """List the available HTML templates. + + Returns: + A list of files with .html.j2 extensions inside ../templates/ + """ + return (pathlib.Path(__file__).parent / "templates").glob("*.html.j2") diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/util.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/util.py new file mode 100644 index 0000000000000000000000000000000000000000..2f171c6519cde57fd69033e040a9305ebbbdf53b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/widgets/util.py @@ -0,0 +1,207 @@ +import importlib +import logging +import sys +import textwrap +from functools import wraps +from typing import Any, Callable, Iterable, Optional, TypeVar, Union + +from packaging.version import Version + +from ray._private.thirdparty.tabulate.tabulate import tabulate +from ray.util.annotations import DeveloperAPI +from ray.widgets import Template + +logger = logging.getLogger(__name__) + +F = TypeVar("F", bound=Callable[..., Any]) + + +@DeveloperAPI +def make_table_html_repr( + obj: Any, title: Optional[str] = None, max_height: str = "none" +) -> str: + """Generate a generic html repr using a table. + + Args: + obj: Object for which a repr is to be generated + title: If present, a title for the section is included + max_height: Maximum height of the table; valid values + are given by the max-height CSS property + + Returns: + HTML representation of the object + """ + data = {} + for k, v in vars(obj).items(): + if isinstance(v, (str, bool, int, float)): + data[k] = str(v) + + elif isinstance(v, dict) or hasattr(v, "__dict__"): + data[k] = Template("scrollableTable.html.j2").render( + table=tabulate( + v.items() if isinstance(v, dict) else vars(v).items(), + tablefmt="html", + showindex=False, + headers=["Setting", "Value"], + ), + max_height="none", + ) + + table = Template("scrollableTable.html.j2").render( + table=tabulate( + data.items(), + tablefmt="unsafehtml", + showindex=False, + headers=["Setting", "Value"], + ), + max_height=max_height, + ) + + if title: + content = Template("title_data.html.j2").render(title=title, data=table) + else: + content = table + + return content + + +def _has_missing( + *deps: Iterable[Union[str, Optional[str]]], message: Optional[str] = None +): + """Return a list of missing dependencies. + + Args: + deps: Dependencies to check for + message: Message to be emitted if a dependency isn't found + + Returns: + A list of dependencies which can't be found, if any + """ + missing = [] + for (lib, _) in deps: + if importlib.util.find_spec(lib) is None: + missing.append(lib) + + if missing: + if not message: + message = f"Run `pip install {' '.join(missing)}` for rich notebook output." + + # stacklevel=3: First level is this function, then ensure_notebook_deps, + # then the actual function affected. + logger.info(f"Missing packages: {missing}. {message}", stacklevel=3) + + return missing + + +def _has_outdated( + *deps: Iterable[Union[str, Optional[str]]], message: Optional[str] = None +): + outdated = [] + for (lib, version) in deps: + try: + + module = importlib.import_module(lib) + if version and Version(module.__version__) < Version(version): + outdated.append([lib, version, module.__version__]) + except ImportError: + pass + + if outdated: + outdated_strs = [] + install_args = [] + for lib, version, installed in outdated: + outdated_strs.append(f"{lib}=={installed} found, needs {lib}>={version}") + install_args.append(f"{lib}>={version}") + + outdated_str = textwrap.indent("\n".join(outdated_strs), " ") + install_str = " ".join(install_args) + + if not message: + message = f"Run `pip install -U {install_str}` for rich notebook output." + + # stacklevel=3: First level is this function, then ensure_notebook_deps, + # then the actual function affected. + logger.info(f"Outdated packages:\n{outdated_str}\n{message}", stacklevel=3) + + return outdated + + +@DeveloperAPI +def repr_with_fallback( + *notebook_deps: Iterable[Union[str, Optional[str]]] +) -> Callable[[F], F]: + """Decorator which strips rich notebook output from mimebundles in certain cases. + + Fallback to plaintext and don't use rich output in the following cases: + 1. In a notebook environment and the appropriate dependencies are not installed. + 2. In a ipython shell environment. + 3. In Google Colab environment. + See https://github.com/googlecolab/colabtools/ issues/60 for more information + about the status of this issue. + + Args: + notebook_deps: The required dependencies and version for notebook environment. + + Returns: + A function that returns the usual _repr_mimebundle_, unless any of the 3 + conditions above hold, in which case it returns a mimebundle that only contains + a single text/plain mimetype. + """ + message = ( + "Run `pip install -U ipywidgets`, then restart " + "the notebook server for rich notebook output." + ) + if _can_display_ipywidgets(*notebook_deps, message=message): + + def wrapper(func: F) -> F: + @wraps(func) + def wrapped(self, *args, **kwargs): + return func(self, *args, **kwargs) + + return wrapped + + else: + + def wrapper(func: F) -> F: + @wraps(func) + def wrapped(self, *args, **kwargs): + return {"text/plain": repr(self)} + + return wrapped + + return wrapper + + +def _get_ipython_shell_name() -> str: + if "IPython" in sys.modules: + from IPython import get_ipython + + return get_ipython().__class__.__name__ + return "" + + +def _can_display_ipywidgets(*deps, message) -> bool: + # Default to safe behavior: only display widgets if running in a notebook + # that has valid dependencies + if in_notebook() and not ( + _has_missing(*deps, message=message) or _has_outdated(*deps, message=message) + ): + return True + + return False + + +@DeveloperAPI +def in_notebook(shell_name: Optional[str] = None) -> bool: + """Return whether we are in a Jupyter notebook or qtconsole.""" + if not shell_name: + shell_name = _get_ipython_shell_name() + return shell_name == "ZMQInteractiveShell" + + +@DeveloperAPI +def in_ipython_shell(shell_name: Optional[str] = None) -> bool: + """Return whether we are in a terminal running IPython""" + if not shell_name: + shell_name = _get_ipython_shell_name() + return shell_name == "TerminalInteractiveShell" diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/workflow/__init__.py b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/workflow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa16d0a14d1fc4ce52e97460db842873a986d81d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/ray/workflow/__init__.py @@ -0,0 +1,4 @@ +raise RuntimeError( + "The experimental Ray Workflows library was deprecated in Ray 2.44 and has been " + "removed. The last Ray release containing ray.workflows is `ray==2.47`." +) diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/__pycache__/cluster.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/__pycache__/cluster.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a6970bf2d0a3effb4da3c72ed5351fd5b152f6a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/__pycache__/cluster.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:780c3ff843a534e980a9139e76d4bcfa7a992b2013f2cbeda2572afee9fd529d +size 126801 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/asyncio/__pycache__/cluster.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/asyncio/__pycache__/cluster.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aea47fc82ff918147718594a9c4ddf90c141a71d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/asyncio/__pycache__/cluster.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:74d9dea340e1b6dd25561d2f097e9a124d0e3cba4018779ef358253c4603578b +size 103441 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/commands/__pycache__/core.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/commands/__pycache__/core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f5c0da252cf6191976ce80d7af0a2c1303abf0a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/redis/commands/__pycache__/core.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07cef2b21ab346c2c29ab309cb26990484dc77a5249d6212e206aa5e22053017 +size 275339 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..071b9cd08dbfec1af4c094fc45141f861e461f6b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/_regex_core.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3825f274db7d6368c25645c97efba87b3dd17af2cff1f180fe763fef3318bbfa +size 199822 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/test_regex.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/test_regex.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c790a2d27d3e926b27d967b310f5c45ef6ec01a0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/regex/__pycache__/test_regex.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa41da575fbe83a0c4cfba1be4bcd110e4da07e22c574e5e3e512a115584e988 +size 334646 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/_emoji_codes.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/_emoji_codes.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1ed4d61333090027da8aea105dbc345198f9d9a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/_emoji_codes.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:830cb2ff788bf203d2b83cf95998a18cbdc5ea6155b624b97070b1473fcdf628 +size 205946 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/console.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/console.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e1734c4c7097c9d9fa82e88e5b2ed5719db37a54 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/rich/__pycache__/console.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3aa6b33c10f95d54c82b7f4eb91af8a8899d7a038f666ae5490a2bb54cc293f7 +size 115210 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e59dc688cd427fd92ec501d229a226c861b8fcf2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/_lib/_uarray/_uarray.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:db3ec45a5b6b13203ce8abdb9dc7530e1bc9fbfff394e651228b4a43a40c8e6c +size 178040 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccb576cd78e002fd8dc104d69cb999b1fb54b018 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/__pycache__/hierarchy.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b0961dafb01317caf93a779032fb3de38a2ce8db5a240a372b88aeab1946ea3f +size 161956 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..76bdcdf0c660d5965d27e3ed408447171bb52926 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_hierarchy.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06d7a371d04ebd6ebffb169e63c62b47c3647e97548f012b942d1cbcb32c1903 +size 300088 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fc4683c356f9f714e33e17dff0cf1515120be86e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_optimal_leaf_ordering.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a07f9f1b9bce7a39f0150194dc8bcacae4f8f53c47af21f9f672d38ed05c67c4 +size 195304 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..102914a1898d547cc1b00ccf5031ffb4a985d282 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/cluster/_vq.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54a856896fc3b62956b45b0ec7c29b5fc5e338beb5dc078952e1950aaec24d43 +size 129872 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e34038d6bdae414394a4da4f3f4e7e867751f471 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/constants/__pycache__/_codata.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:40596a67f981f2e76729b076de39c8c9f9cb50e9afbfd899c792f69cee54fb4d +size 203267 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..afc6a26bb020b0aa7dbff8ff5dd3e92140fae551 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fft/_pocketfft/pypocketfft.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e891b59c20699ee106a7a3c608515585499f78ea52c9655535295f2159b622ff +size 1223392 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bb567271d7ed412d8f28244d165c139639054495 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/convolve.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4080933209e3ec1fc2f3c77e2f4d14edada022bbff0e9e002a00281ce4c6139 +size 128784 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_double_ref.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_double_ref.npz new file mode 100644 index 0000000000000000000000000000000000000000..e1e3d620400746177b560b9193efce03c2841e99 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_double_ref.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a60c649415b645223924d8342ccc5c097801c86901287a369e53fc9259f5ec4e +size 162120 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_longdouble_ref.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_longdouble_ref.npz new file mode 100644 index 0000000000000000000000000000000000000000..b1a646889c9889541e8d368c8c2d96520d183dc4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_longdouble_ref.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a406cbd4dad04d0c59dd38f54416fb49424c82229c1a074b6a44ec0cde2000e3 +size 296072 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_single_ref.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_single_ref.npz new file mode 100644 index 0000000000000000000000000000000000000000..a42748dba14b7ff0d2f53ce4cd5a86a4f08e5d93 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/fftw_single_ref.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:276a9141318e6fc36e4ab6ff54a61b64054ef8849b660f17359e5f541b43c526 +size 95144 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/test.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/test.npz new file mode 100644 index 0000000000000000000000000000000000000000..1e5a4e06615c6bcc58f0feff20f73e83439a937d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/fftpack/tests/test.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36de804a22d8fdea054590ce49ddf3c859838b7d89193c56b3bcb660cbf43797 +size 11968 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa5f092f76fd68d902a12ecf015b9d3699050fc1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3b77baeb9d311580055ad5e4a1c77c8e9ffa742398714d31cea41fde6180a239 +size 180695 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a4ae999cc97cc5d4e52d8ea00b85b8cf6cf68b1c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_dop.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32eaad3e41964ee69acfbf75c53ba1d7fa187b7f32f66db846d9130d677d29a9 +size 121089 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b96e1f37e9a266d09b96aaffe18f35981efd5da8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_lsoda.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4ed8ce8abebcad0c463c00b8384ad1540864a8d63ab2136877ee6c108dafa01 +size 516881 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..788129cb32c16a73cd72947c2855768d7bcf199a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_odepack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:157269fe88cd78f001896f4af6206bbaca0661d77f0b2877be367bad12e2fdb4 +size 479121 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ee510f8a81cfa3649e8efd853d69985ed77588b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_quadpack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb1728d15ddb15a03610d77ebd2796ef68654cdaf87702d7eb3d5b6415fe9da7 +size 112024 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3e03d8081647faec735b6d65bc1ebe5a30fbe2a7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_test_odeint_banded.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8262fc06a56cee7b5417f660131f435a35262c7ab6cd19947490346f7e7a2bc9 +size 520681 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c48f401d17d76b984d3d08dcb79c90d9b1f2dcd6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/integrate/_vode.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dad907422f261f219b5498288130906176a10ee0bc56b916cee4d9d867bd53e4 +size 570081 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a65943dd1f6a3bd4f37075eeac6d9574a881534 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/__pycache__/_fitpack2.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c3326e9c17339ebfd730a5f8f88903e93cb319bb933efc84761d984f2c6f7575 +size 101539 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dfitpack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dfitpack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b7f382a9eda77b0a9e0271227df23956a129402e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dfitpack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c9c75ab91c2182846fd9f49c7da8d43e566d6391b2dd91c1c7521ce73af620c4 +size 350473 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..34db837973fcf0a16b9d65c93ac7da2280f28647 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_dierckx.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afb228721c909e45785aa9cd9b03a2d147e20fe00dac124aa6c285fa55b0ff3f +size 154209 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..eb1628621506d06515305ca26ae817d1b2eed0a7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_interpnd.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45d587b82b20814de29f466aa47c99d68de302d84ff0f585d27c81bf12670873 +size 302592 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ebf159e9f2f1981d699d88033465d7c9f078aa68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_ppoly.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:37c2fa30ff929bf4a48368006f6d84db51afd5dec4e7849d5cc53316096f0c8c +size 313352 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..79fb8e62463b4d43acfb597c8b3416a75b9d16e7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rbfinterp_pythran.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85f8a95a0d3c4120c808ef8f609702b0b86740054bfaa10d82238d58387fad06 +size 256632 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f95c8d256b22538fbcd09a300a0266de3523041f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/_rgi_cython.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccd32f7db10298ab21c8b077c63f69467a480674a29e9f416eb67f38c3e7af26 +size 153624 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_bsplines.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_bsplines.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e15b52bd37cac2254fb2067331185aac4bc6c1d1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_bsplines.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b39056e36df2ba7f91d7f14cac7c0e416b0fc0e3a2ab5b75ed764c4b60a6e6de +size 225636 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_interpolate.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_interpolate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6a9b92ad6db3ad1450474987aa7a497e4163469 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/__pycache__/test_interpolate.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29f7c1129ff1f1be1c522cb9a58a622ab3f3354e1775cd591af6cceeec47e308 +size 156830 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/bug-1310.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/bug-1310.npz new file mode 100644 index 0000000000000000000000000000000000000000..8bddf805c36b29dc449556c27a2b489691f841af --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/bug-1310.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d6803c0b398f2704c236f1d1b9e8e5ede06bd165a0abb0f228281abbd455ae9 +size 2648 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/estimate_gradients_hang.npy b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/estimate_gradients_hang.npy new file mode 100644 index 0000000000000000000000000000000000000000..c5ef8f63f263a476823ddeacf2571551c2fe4690 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/estimate_gradients_hang.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:406c10857417ff5ea98d8cd28945c9d0e4f5c24f92a48ad0e8fab955bf2477f1 +size 35680 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/gcvspl.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/gcvspl.npz new file mode 100644 index 0000000000000000000000000000000000000000..50e9348dcca79eae861e67092add93cdb8ff1ca3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/interpolate/tests/data/gcvspl.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:03ce8155a6cba0c1bf0a2441a10c228191f916dec36cb820723429811296bba8 +size 3138 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..840815ca2af8696cf1d38733e95993e3259d3c09 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/_fast_matrix_market/_fmm_core.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:94c0a9cba353645a0e10a460e08f3667f154643e64299fc6d1af653951a66659 +size 3909200 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..54a5a43f94af84c2f30f6183bd5773e54738f243 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_mio5_utils.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8ec116b2dd7295a8e3b896f13f1ecca74a3562fa1f681e4091761eb0a70b3af +size 247024 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..58af2f1510d013f7b296333cc0d4051ff3a5ee02 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/matlab/_streams.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a70f2c0c1e54df69e2def0d35943d67adc040c12e37fcfa7f81f48b818a0ba3 +size 140232 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav new file mode 100644 index 0000000000000000000000000000000000000000..4dc4ebed4e134fccfbf88c0ab93ac33705e93cb5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-1234Hz-le-1ch-10S-20bit-extra.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:87c097b16e7f4a1291d7deedfddf935139600ea399fbbc0afc47151ae711f9a6 +size 74 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav new file mode 100644 index 0000000000000000000000000000000000000000..20b9264eeb61d4575b9c0484cc0b7cd59f2efe0a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-be.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:823bfffe783dc47fec9b7e21cb109b0a03b800ffbe3d901f0ce02b1f9a269233 +size 3586 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav new file mode 100644 index 0000000000000000000000000000000000000000..aa79a3ae4097ba68e9a0071f273abd466d0dcc48 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-2ch-32bit-float-le.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f42cbcafda573682ecd81a7c780d65d4eaf079ec9ad15fe1bd0dde2a1a1d213 +size 3586 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav new file mode 100644 index 0000000000000000000000000000000000000000..6fa1d82cc466464f0378654a0a1dfb6772e1384c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-be-1ch-4bytes.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28acfd497bff477817fc055e103dafca16278f806f0f5bb20e22a9093dee959d +size 17720 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav new file mode 100644 index 0000000000000000000000000000000000000000..8c227b753036941bf9b2488c1064a89c7608c66c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof-no-data.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:617d60f2a7423801b5eaf5fd1baab84ac7c28f6655935f7d8f30d0f12d335982 +size 72 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav new file mode 100644 index 0000000000000000000000000000000000000000..87af8be1ae45f2d89b0557045f5ce1ac37463fe5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-early-eof.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c5aec46ac344179ac683b630fa4c53fc859e631183326829adfa46bf0ba18d9 +size 1024 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav new file mode 100644 index 0000000000000000000000000000000000000000..f8d332e94208f448b8377fed7a539181e13bb65c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-incomplete-chunk.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ccc9e1bd9beb3f893239629529f6c19decafd37c6fce0a976211cdc6c0310c9e +size 13 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav new file mode 100644 index 0000000000000000000000000000000000000000..37811d0253cbc106a571ac1a1ab118162ad9e240 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes-rf64.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1922690ae7b396f1db84fdc2af88cd5a6cf8cc6e3a5d9ea3722d9f5ad88c3749 +size 17756 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav new file mode 100644 index 0000000000000000000000000000000000000000..6971300129120ca8a3a2a92a733eddb0984abdad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-44100Hz-le-1ch-4bytes.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6a4c2be981dcf7ada79c54dd558a08073e742305fe3bc665e877d8820ec1229 +size 17720 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav new file mode 100644 index 0000000000000000000000000000000000000000..e8ae491462f17664f15c6daa7023f522078b6e82 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-48000Hz-2ch-64bit-float-le-wavex.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12a6019c4813c532af69302d740e47225e3b0821488def77cb885ac11e8fcaed +size 7792 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..71934ac873c7e4278420597e763a596f4dfbbc72 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-be-3ch-5S-24bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84661c8714058ebb6f642068d142e2fb1759f24aea5dc29d4e5dcd4947ea7bc9 +size 90 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav new file mode 100644 index 0000000000000000000000000000000000000000..b3c27ca654cd8fb73621c6ac226eb340fe808ed1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-1ch-1byte-ulaw.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0685020dcb771a263f24957f1e88211779b301e6d3d7c8f4d9cf8c3a7d7d2b15 +size 70 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav new file mode 100644 index 0000000000000000000000000000000000000000..f733f90d4dea6f6429d88219928d52037365e9e0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-2ch-1byteu.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:47a109b21bd0a79615478181f6ee0a867e4733554c7c9523d3cda2f2d901209f +size 1644 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav new file mode 100644 index 0000000000000000000000000000000000000000..fdd1849f98e5883c46e6c2889e7a32f484b1e847 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-inconsistent.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b76320ae2de1e892d00de92bc0884304e686e3a394cc7ca7533d2929bbcea4d5 +size 90 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav new file mode 100644 index 0000000000000000000000000000000000000000..085b5afd663fec6e9c6d3fbf8c099c96a566cbde --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit-rf64.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8921b2aa8b97e7735a101df7b732976b5d4d44863dec61b8d3fa6a585fe4e4b4 +size 126 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..23be5c7b67cc6c3209b9d66d2897e1daf2fb54e7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-24bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c82bf4ba1faec7fb2426cc5e3a3ce88346019376503bf930e4724732ab55c88d +size 90 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..3152c566f155a76b36c33f7de56b0942c26548ed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-36bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a22315b1057dfaa181cff670b1f024800f416573635db1f8cf1086bef753d116 +size 120 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..2e9dc76040faaea314a81b66b024a01b63d1ff73 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-45bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7bded7a0facf1890c887c9ceea68a2fff562639c95966b783a73d0a03375763b +size 134 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..99ec1413418a387563eba670c547de03b91ec783 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-53bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1ba272a5cefcd0fdb418c81b23f86c278a164e867d2ec5f2a12ff9c434218d7 +size 150 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..09ea515215b4f92f881bf97900ac2b56ee0c89ca --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-3ch-5S-64bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52ee503d071bb671659f139de33146c698930b8c20769e893a8609d95319214d +size 164 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..d6f534ab9619a6cb3a121e36e61d5f8c00ecea29 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-4ch-9S-12bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d45ebb87cb6bdb1cf40b92b6d53f72f60b29706034aa748ecec976be302b00cb +size 116 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav new file mode 100644 index 0000000000000000000000000000000000000000..d2fa9b3a9e9ba86eefbd1cee5378ba56a083cf3c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/io/tests/data/test-8000Hz-le-5ch-9S-5bit.wav @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4c9bc653b1a9817742addae3ccc943b6989e0cc9c32be95630caa55a34f6dc16 +size 89 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e2e448c23725b7aba98094743ee15bb6637ac3ec --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_cythonized_array_utils.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ae3e85fe51543cd1973719e0bb9f927c5b266b8978f4473ac0be474050746e21 +size 459824 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a69d29ec3bb76158d6c1a31cd9eea8c8cdcea412 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_interpolative.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:26cf08b5c8aaa5a82d6c38bff2f3649267ad70795c5fe53a0a05fc3531fb6c26 +size 790864 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_lu_cython.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_lu_cython.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ee9b4f0549bbd6c192d83765258e99f85c8c0e6b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_lu_cython.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42cb11899b40856e7a8c8965773e247c0999b77a6bd15bcdaa2800e10d30ba36 +size 127112 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..826daa27065b655977dde91d6478b40da5cc90fe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_decomp_update.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af5650a4ff5516b24e6448c8178b92adc62b8e9d33c952d1b5e83bd43a8ac97b +size 353024 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..343fea096f53a3b82989345dd6a89248dd203848 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_fblas.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b1039926d0370c044dc3fbfdada5f72187704fca5b64b299e6eb2082ca931cd +size 1040737 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e3ebcf6d07772a9adfe3ad1c1ca1a1895187ecef --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_flapack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e6dd22b6dae88d9e1a3efbe1ec3ba04e5c2c016ab6ddd616432958cefb8f10a +size 2585137 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ce6497b347cdb872b25983d352afc92b9f7c136a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_linalg_pythran.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5d6d4530f327b76980d3bbbc879982f3dcd33d71eeb31257ec40e00a805173c6 +size 140520 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_expm.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_expm.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d9559145205c2e97c16ebf0ba39fba759073d269 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_expm.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61789be782f769302758d3d294d7e26c7d5a0354eae07c2e1bbf8a67cf48ea70 +size 511433 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_schur_sqrtm.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_schur_sqrtm.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c6c8c4d77ce7e00b9007e522340241216a4ac535 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_schur_sqrtm.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0792c554077652a687c2d068a7e2f47dd7ba5467a92a6b49fe840ad6585fea10 +size 495073 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..906ce50a78deb1bf64a249cbea4ef6d5a20a35ba --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_matfuncs_sqrtm_triu.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d16270129200ce5c38f299ca7743af0e6413fdc1cd1f36065022e055c64b170a +size 139264 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..84ad9405a12be4b34a9c5be58c745ced7a09b41c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abf4d114493e536222809094fb4488d632dd3289ace1a2b0e4e8f54ccb2093ee +size 148312 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8a99f75a132da3ab06dc4178e48bc1a26d2629b8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29cf1bd575625718d7c38afaaf533eb02c35280bfb813d0591a4a8e46143ed5e +size 205457 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bbb9f1a27b13256c0455ef3d9b49342527942ab4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dee8381cf23e90a9c52fb8338ee606abb49891deef6d22633ac76bcee8d20e69 +size 879617 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad6c2019784173b6404a4f4416eed250473254b4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_basic.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c2929be9a909ff2d299e998c17ba74bd27bb134171dd7896106a86bd07fbad55 +size 117397 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63474bbf6c30651d3b781b98930892362d04922c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1527f9398320a1eb48add4eae554fffce15fc25e56dca6df032449d14569d648 +size 188418 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dedd9e222598d921b902934627a9e59e99ff9dd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_decomp_update.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35636bbb6a27ce47c175ecfb9036e605dab6bca76c99ca6bd8a60429617b8368 +size 113198 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..008d9016f695931d5f32a0bb62203b7e8c1a70c5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/__pycache__/test_lapack.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c62d7873c428fc487beecf64595f6bd3e6735fa78cda390dadfd44e5be00738c +size 179642 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_15_data.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_15_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..660bbb41b7fad43ed945dc701693451ceb60166c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_15_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:13f3e1491a876bbf59d7ea10ad29c1f9b5996a2ab99216f31d5bfcd659012c1e +size 34462 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_18_data.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_18_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..0b3d569a1a65e9b5ff153ae4121a6a5a69409f7c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_18_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59f839467f2752b7df6fb6d4094396edd32a5929b764f7ffa1e6666431e6cac6 +size 161487 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_19_data.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_19_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..90168ad4e888fba29a772ee13798ec126016140e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_19_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38e8fc7b041df0b23d7e5ca15ead1a065e6467611ef9a848cc7db93f80adfd87 +size 34050 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_20_data.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_20_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..87266deb46238307347362b63a4878f2565baf56 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_20_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14e222d34a7118c7284a1675c6feceee77b84df951a5c6ba2a5ee9ff3054fa1d +size 31231 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..35d1681786c95602c4f0d5260fc5ad0ff4236189 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/carex_6_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1b2a0736b541ebf5c4b9b4c00d6dab281e73c9fb9913c6e2581a781b37b602f9 +size 15878 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..ff967f2ca0d0868aacf7d7e67402599e64bab817 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/linalg/tests/data/gendare_20170120_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3dfab451d9d5c20243e0ed85cd8b6c9657669fb9a0f83b5be165585783d55b5 +size 2164 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2748b86831b5dff171e970fc80122abda769506 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/__pycache__/_morphology.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3bc17f1e6502b035e21b7df63cf0161ba30bc27aa626a415b8f7894630c9c394 +size 103431 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b8346ea3f5801530e51e9dbf15ef7b9f9b8d493c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:760a1b1401eaaf43959fb37639eb66f31e20cc018b16d55e2cb7c8f3d2b4241d +size 147184 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0d5d3d6a039eb23a75058655201897439d3e29f7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c28b7047f79a526d5e4553f4610b1ab7defda6ee11c2322bd1bfc763ca7f07e2 +size 294872 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83c2987bb5acea143e3ca87e3d2e9d35c26b938b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_filters.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b07aa89715892bdc9b799d1cf8e40feebba78457efe6b731dd9c5b4ef24e022b +size 172256 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dea8e1e6a3fe606a478b491d21cdca2944887d40 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/__pycache__/test_morphology.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3e2e4d38f3ec402d6677bc6622438fb9708ea9b4693d8dac34bde8996e2ac670 +size 127697 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png new file mode 100644 index 0000000000000000000000000000000000000000..2cb593b8e1cf68e429cc8402838c31f70be59afc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b20b56fadc7471c0694d3e8148d9e28a83d7967bac16bf8852094afea3950414 +size 2114 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..60af7887a7d082b0a490a5b2063bab8403445db0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82cffa7a057277bbb91117fc6bc615000e9e583d9938a861e68ba4c5e4d29eb6 +size 622553 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/__pycache__/_optimize.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/__pycache__/_optimize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..658f57824added2c4842fdcce980abe28f74fdbc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/__pycache__/_optimize.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:827e9ae7caf0d77347b69edbfbdf449898c10e89ebd692b7fbfe121021dd3b1f +size 150025 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2ced621e254f24c2ba5488e1b8d6dabb7bf8308a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef3d89b3f861643f677d68c6e8447f7272c75f87ea7870a9a555238e58c23ab9 +size 218288 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fbececc0d8cb7a7a0c5cf2f68546c4e07bddd996 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a421bdcfa7643d7e365d0d32dcf6a9f67fdbe08f59b618665110ed60fe6901b +size 5952152 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ac5925344a2c859c2453b7faa927a1f44c92887e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb091b46eff1a985bd39c8e8092cb53129e0aff75ce923c589cd83a01b350588 +size 437040 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9c9fcea18a4d0b32aeec1a5c38b69f9e689f51d9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29daad6d94bdd4191bbb23d0ea336e76d08e157b60a9204baf8a3bf35b3a3d3f +size 462225 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6630318393f292e15c710c854a813a6b2b4d3326 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b1ab1aef414a45c1bba47d227e820370d5c6ff64b59567847400bac4549a5cb +size 150960 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..887ecfd1ba530e100106c6c1f3f9abd2a913bfe3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:963540640f50f85cdb2030024382667a044719b0067c05d430ca8a8bb824bf15 +size 244672 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f7a72de951d8cd785dd119c14449f5ef895dcaa9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77aefa61c394844c21f5f3d15d7126a4802136138eacc1699af1e6739d08d956 +size 458305 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..06dd869518096abe1a0bd036cebb5c1f3e6a2cd9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b05ab7d384cb2107a92cb7403a23398e258d08079705a8a3a1ae31be79b974cb +size 232881 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..02f90737a4d493b814f115ee6b460fd7656062a4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a8da0d5dcfe2fb4e3f660f01919ca46f834c414f9fdad393112cd553906aaa1b +size 103904 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..20e44860962d3df5452fb08cf82851f2975b8c2d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_linprog.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f1f1d660faea9e70e29edd469827c333913c4341901390e417aa848892a9374 +size 136937 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..853222af16e6fbb2701b5b52eaf271d5cfede167 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/optimize/tests/__pycache__/test_optimize.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b13782ac4b345dd3fba531cc46496223d2253980f936abc99b67b8a332efdd8e +size 181226 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_filter_design.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_filter_design.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..72a9423c7cdee5185a3f0b549302cef61075aa00 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_filter_design.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:29e8e342f74b6c2f7e73ba4850604da708e178f851304e287f5c10a299ab6f2f +size 223769 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_ltisys.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_ltisys.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..19f50c5226b7e2e1ed5c12d669c441e9a8373491 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_ltisys.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4ea55d421d4d48a92b94b776c01888ca5112c0f52c0552b63dffbe861d8aa79 +size 134157 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_short_time_fft.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_short_time_fft.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0973ee5cca037422184b00dfabcbe9fba8616a75 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_short_time_fft.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:241f490054acbd90c597b9545cc4943559bfc2700be4366d948c044da77b7df9 +size 111819 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_signaltools.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_signaltools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f6ba1bebd9a0fcb880e9e083facf7a009006f7f5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/__pycache__/_signaltools.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4d267c5d0b67513668beed192af4cb33e0ac812e303bfa8d1e23be9e753b9f9d +size 210640 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e17ccbf1afef6aa7a2bbe47d2af2b862122d494a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:45dcaf0dc1c869192cf44608735b42e210a39f83aa78f1c27b7181e95b58a6b9 +size 159632 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..623fe21970dda47eeee0b6d75707b28e739c47ba --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f250d3c4ace2e5b431888857c9326f32235b024298cec2b8dd90b7a340d6a48f +size 113088 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..86874155d9a5bf6d29dffd11e3ddd7e136e51a89 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e28d86bcd44b427611fb85f9cf7fb42345600e34c5abf1d5ac09d0e211d93180 +size 165608 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f6c173bdb399a6560366222e14efff5e85192b2e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6aed7ca41ed1f16a28b02f40e8b76ee8e4a58e65017d937ca153c1020aa46d44 +size 250064 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_filter_design.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_filter_design.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5b2b5fad9e0eb64b3ae5310d05385b9668d3d547 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_filter_design.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a29f1965fc70d3f5f281c1229a2af5bf39632ed9f093fca0c578b22983afa020 +size 227896 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_signaltools.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_signaltools.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e148354fe48ea562d23b5db0bc13401a3d4dba68 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_signaltools.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ed9582508f32c92e153f2d94cbb50fbef0c2cff4f68c1a56b392c57c3bec231 +size 279002 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_spectral.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_spectral.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a90830927211885e8cfaca9f7cbcb8fcbfa9bb0e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/signal/tests/__pycache__/test_spectral.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8722364e85053a1e6bb61242bbcb8e1f7455e1388e7f0b1b73964b33924f519a +size 111294 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bb5c4f5f810bd7e82c0cccc890a7fd8679d9a936 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4df7e368097ba3342a2142626d5e7f82f2ba9d9eaac2689e090f49f975fbee1d +size 560136 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b7c5c3e461f14db31cd740cf75b226e8c7210219 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54d239dc364f96e6b82ff983fe9f2f71598af74b4f931b0f5198a8411b0375d3 +size 4314496 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d9d6939999a53c9e03b96ab4fef1fc92411a5d09 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:043c02f4813e98bc7730fbfb41d31352252c16a1f4afa8dc9c58cc9748ecd7e7 +size 199408 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0ca2d7cb748c8459026d1f6f63d3a55855e4f35b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4261ee539999d67c2223919136870b5af6cc3a018f0d3507f4947ac0429a481a +size 204688 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..cb9d4a732c8990af93b0093bdc077698f4e91d59 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:663e0364b703644001aea31a9dfb15c0048acfb2c784ea2674554b4704844b4b +size 119472 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5d80c605b0da2e05f7d68964fdc5843c73ffb370 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9e6c10c5b1ff0d8b5205f0b76626afcc7ae40337954cfb4e2bededea45e92ace +size 188672 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..dbc19e0cf34fcdd3ce80b0eb31bdcb394911ae5a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c04ec00715c9f05bf50d6e4a8d8311ac84310171dd7bfa4617b1e8d38a4467df +size 448064 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4034c61c2622e4a3d5cb45c98416a7588f623a03 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dc6726b09f7291f2238da567ceaae22fb95d3d820267ef635e1aecb375e7b142 +size 203040 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0334a7dc95fbcf67eec8256e862b8a151559840d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e197995778fb68f91aa7a20f0772a3187e29ee3cf87615384ea588882478f45f +size 463888 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1357493907322df288aeefb9adff1dfdec4f4af7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f28d7c2597401a7112294291951ee6c3cbb4142a4f87e4b886979c5c88e81e4 +size 811113 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e8e9c0ff911b3700b192411b351b9b707c454fa3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:07a84215e10b8eff5b4d49409bdbd586f65ab81a1f3f624a8d5fb1db8fdaf5a3 +size 881273 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9469b62c62767526798d0184dd6f397e263b7b7f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_cpropack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:647301567e404325793134920ad1d99a91bb979a0d869b95380b8059c72467af +size 570145 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_dpropack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_dpropack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..05f316a5b264ea7ac4d019a8d7324dee522c0b1b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_dpropack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3c401d288f579d0f8f868eee5ef9e45f44279fabea34a8ed37ffcc8376fd20e6 +size 533201 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_spropack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_spropack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..05fb70cb95710cd3c41be638929bab7965361ccc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_spropack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82e24d0dffc1e891745be0e20309dd419fbbd37d2d301ccaee98ad8e7255c3c1 +size 533201 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_zpropack.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_zpropack.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fc3696e90506710f5c150b9aeb61f7bc059cb117 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/_propack/_zpropack.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:30aaabdf5c915b1a8c6b071619cc85ba5d21d22ff898e028182847813032a92b +size 557857 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/tests/propack_test_data.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/tests/propack_test_data.npz new file mode 100644 index 0000000000000000000000000000000000000000..0bf01015610346655c749ead87a47d5575e2b67b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/linalg/tests/propack_test_data.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bfe34d9a92353e08f400f3837136e553a8e91d441186913d39b59bf8a627bba3 +size 600350 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a09a98e7226bbd1fbfe9d1f0108f1531447a096e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/__pycache__/test_base.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5102e46a4ed9e92ec4fdf7f6af995842e3ecafb84608f7aef7f3d930d1f46e36 +size 349511 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/data/csc_py2.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/data/csc_py2.npz new file mode 100644 index 0000000000000000000000000000000000000000..d4459ff2786fabe4bcf4653d880cbf0afd4bfdcf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/data/csc_py2.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bac27f1a3eb1fdd102dae39b7dd61ce83e82f096388e344e14285071984d01fa +size 846 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/data/csc_py3.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/data/csc_py3.npz new file mode 100644 index 0000000000000000000000000000000000000000..e40a38584bc4647621601075d946ce46a8e065dc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/sparse/tests/data/csc_py3.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6b1b84315c7077417e720512d086a5a6217c2875b818d27704ae9b7237c69dfe +size 851 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/__pycache__/distance.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/__pycache__/distance.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92fe4ba689bb6db4432d7c2de84ddf5c44aac564 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/__pycache__/distance.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e0462b8d1397cc48cd5433b0e8a484cb74e945dd5fc101fc7846049506aef311 +size 106761 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..875f4fffc7ce5dce54c75a950f5302c6dbed0181 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:488f96e22cfb0b63e2313917d35824fe20f25710377d2e87e0ff5a8998570fa9 +size 854408 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..56a28fb6cc680cd249a1db9707bf3b2b1f109108 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4c7200223102b64475ebb1c29cddf66e8fbba6e82968d18a8fe0a2af3467dfd +size 669400 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b6ef8b283cff5c5f27292f38815d096d82014d1a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca6afc7aa9898116a5f48866702b21d408ac8b63a9ecd4372a565df9133062f6 +size 113256 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_hausdorff.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_hausdorff.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..042bb01f045050ce767f716d4deec556c1efb51b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_hausdorff.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:460132d78f8af06ae11b81b4b7cd997ef476d2c5da3578116bd1ae82400ccdaf +size 101624 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b851a77196072e6f8a2058c8e36f65a4ef90d364 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f01ade6bdb743e6d464684ac78e78b7c7419ed4d2caa15e620649e5f755db23e +size 975952 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/tests/__pycache__/test_distance.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/tests/__pycache__/test_distance.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0b749db3bfbfd3a547d7c227d1911cea3ea4043 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/tests/__pycache__/test_distance.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22e95794148313060b30cb117eb729a4598cd92325d132fdbdfeeabc5fcc4965 +size 136911 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/tests/data/degenerate_pointset.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/tests/data/degenerate_pointset.npz new file mode 100644 index 0000000000000000000000000000000000000000..4f22bd3a3c941a683747944a0f12c7914f4b3f07 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/tests/data/degenerate_pointset.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:048abc1ddd924bf2d4d1f216015552ed9431f9e99546fbf382768eda58788175 +size 22548 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rigid_transform.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rigid_transform.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2276bf093b14b873be27cc6c1543bcee7ad255c6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rigid_transform.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce4ef3e23b36e87d1d5828be0c7764b430aacf826646f11652e637f0ce5258e4 +size 407248 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rotation.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rotation.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0c45cf4d2228771109af3eb0a26277ec361d8249 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/_rotation.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a386a41eaa251bce59d74951dcd3ae680d3b274569cdd651335e5893e52c59b +size 835592 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e05ed671847283bb76706a68622bcbcd030d88a8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/spatial/transform/tests/__pycache__/test_rotation.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd49e0ddc1dea3bce9e7680fbb574a402c812df7fd8dee564a7fab877f6eba54 +size 151200 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a70aa170249ebfca29bee06dbc2fb58b0c35744f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_add_newdocs.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d78c60b8935188aa9b10c42edb2e6ab7ca2ba214743964b200d1b910a332d53 +size 274438 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_basic.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_basic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b55bb4458199620ec0e06303ab66853e20370d5d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/__pycache__/_basic.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14d440bd2ab20e3b8b6eb0e7c9b574c0ddba869a113be03e64dbb744e55ffa51 +size 123322 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ellip_harm_2.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ellip_harm_2.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f162316f6de2926fa6ec29dfb701f7a8d92ec948 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ellip_harm_2.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:15c74bb6c726f708b2e2a8ea0c95d31ab9f75e4f74f84a50e194fb51ddda3593 +size 146513 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_gufuncs.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_gufuncs.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d21e5959decce7109b7f291a7477b5b05676f829 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_gufuncs.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:805bd153d3b7d4d0c832de49eadaa3352b42b60d0c6b5984e04680f9a02aba12 +size 753744 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_specfun.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_specfun.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ec34d173c91b45076110a6bbd0ba9b55795c6152 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_specfun.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b71987cc39debc2ed43fd8429a0afd8ff4ccc7168615eb073c4c853cabea9472 +size 236256 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_special_ufuncs.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_special_ufuncs.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b413bbba070d41b590ecab2c166442c093343d61 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_special_ufuncs.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e266c4c99a44cc554decca684e715dc769a9f1184e1980919fa07e381ebe644e +size 1569144 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_test_internal.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_test_internal.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f14ee99ceb73aace1f96b76fdd2fd953313be2ea --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_test_internal.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4937782da924c69e76dc30c802833a78c9b4107998c9c2a797d1eaf5def99fe5 +size 112168 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..95075501b061c3ad997f84ebc3696880916eea79 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9cbce3dbdc5594934e1986fe8dfe9dc1f3da862d9e3ec161c26fa70e6631f787 +size 1634505 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs_cxx.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs_cxx.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..592c90386bcd223253d35944ef355d783e1f37c5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/_ufuncs_cxx.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:361720cd7d86b740011e5f0679de6d1d152baac40fb56c6e1229e5e159b53fae +size 1811024 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/cython_special.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/cython_special.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b39e61d90feffa7a2635fc4762af1a195d1e90b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/cython_special.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d46a0adcf4829a23f5f5d6fd17e79cb8b5200145d004e79073fefe48b5f1c97d +size 3279952 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..996ff61d5298815c1f216b0834fb9557b67d1709 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_basic.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d201feb70ffa26500c014a03d145604f27b2758cc34ae027d60f9ee24e66fc1b +size 316915 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4f764ba2e486efd3de3d3c817ff33c1cac9a56b5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_legendre.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:405b5481221596a799493a7abd164514929fc21ae259048af74a187011187ee2 +size 101893 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c2913e742ffd7530f9c5f5a772d9cb83374aff48 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/__pycache__/test_mpmath.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eff788f37f77eb568923db2411fd6308d8d226424eeca9d02f489724cd8a8961 +size 137598 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/boost.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/boost.npz new file mode 100644 index 0000000000000000000000000000000000000000..6ada4fe916077ff0349c07c92407a647f5ab81d8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/boost.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:57b5c2b67ee01c741536aae6ad9f8f128106b7fdff152afcf3d8f774b0645844 +size 1270643 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/gsl.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/gsl.npz new file mode 100644 index 0000000000000000000000000000000000000000..a4e2a204e7cfdc7b251d0dea3b810dba42c20fe3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/gsl.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cbf1afdd27999806a710279910a2eb2f9f7f559033c7ecb796deaa10c44feb31 +size 51433 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/local.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/local.npz new file mode 100644 index 0000000000000000000000000000000000000000..7d8bcb0730326acedc98a112af6c2fc752602fe1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/special/tests/data/local.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c29e58ce827084f84db9f1bba96045a61ce69f1d3ea3d7c828a79c133cf88f2 +size 203438 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_continuous_distns.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_continuous_distns.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1eeaf56ad6ddb7d2a969496aafbf3af2774fca30 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_continuous_distns.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0dfb2dee032f86c13df5dcb15977583a8125dae725add6c8b25c1121d4e7dd28 +size 583973 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distn_infrastructure.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distn_infrastructure.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..809dd27af274449c1439da163ba44026bfb1e73e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distn_infrastructure.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:581a609ddc5b893b14f5093deacfba28e527f4197b407a69d784b1df8bb16d7f +size 177842 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distribution_infrastructure.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distribution_infrastructure.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e606b752a8c0981d2b4888ffa5f4a05e2f58098d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_distribution_infrastructure.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1d10c7a9423be53f6c546bf2289296a836574a1bd2160502917b974175a53c0 +size 269614 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_morestats.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_morestats.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d60ddfaff9653192873f7435ee180df5d7e4fd60 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_morestats.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2ba1f9d98b1a9216c0be7ac42bef651870fd354fb329cc9f6d2a853392800756 +size 190875 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_mstats_basic.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_mstats_basic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9276561649c955e4fad2ea26e5158af91b962e1c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_mstats_basic.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d144f083f9b92a32b329732f1ecee0c53aa9db7cc50597b9b0b75c442906f9d1 +size 150831 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_multivariate.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_multivariate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0105f4c5386279fe605f253c4266f6ca23236b2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_multivariate.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:264c293498dcd9303ab28ebe60b6f1cd233ed100e878111b7d24981e98e16ab5 +size 298424 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_qmc.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_qmc.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59c601857607ea7e8aff8cf82abc7b260a46ecad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_qmc.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd169e9ee44e7c03c1a166ab8bbf401b4a4d7683869788fbfd1cbf32edbbfe92 +size 120594 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_resampling.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_resampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a13afd15f34681c37afa067890156a2108a4c4ba --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_resampling.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6e1377929b83d36cf0e4e94123afbad67e3e0befde8864176cc92f55e336981 +size 105117 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_stats_py.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_stats_py.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ccbea233e9426ed930cf293253cae5f6bfa78df --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/__pycache__/_stats_py.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:deb9309438c5836f6987c278438b74cf57bdc664905548fc220adf9b9d856f20 +size 445092 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..381cd3f783e69418b23caf95a467a8c5e620470a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dec7640f266ce8a8a970e54dd3961c08df9ff1baff2fb012b19475344918671d +size 125968 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_biasedurn.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_biasedurn.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7259bf3e7b51ebf3584096b2512677cc236ee875 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_biasedurn.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c35a7ebc7de9f62f5c0fcb1b9e1bc7786dfcb8b6f7fa8b945a4ef549fb68671e +size 318376 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmc_cy.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmc_cy.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1c96e08ab5c688c97c39520aede2823b5cf06321 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmc_cy.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5fb1253a50994985eb60f137f11f27cefef2d18d1665d4ad2938184120e66df0 +size 151184 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmvnt_cy.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmvnt_cy.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0913f8a943e90d1c07f1303093a532093f35718e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_qmvnt_cy.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:06987010d3e13b3fff15402cc32008d2da2d4dcfff4028e8216bb68881168a4d +size 143128 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_rcont/rcont.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_rcont/rcont.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..bd753ba3bd8adc02699adc6b1236c1ddfaa6b085 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_rcont/rcont.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97bf8de1bd77a20aecaea64b59397ea7dceffe128473e3b7fe0a108a034ec9e4 +size 114728 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_sobol.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_sobol.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..b043a6882aca2043a0895fcc9e588af0c32dd283 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_sobol.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5abbf57525c2535330833700a0e8eb4ead46246839ba09340975d7e83c3ad516 +size 245032 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_sobol_direction_numbers.npz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_sobol_direction_numbers.npz new file mode 100644 index 0000000000000000000000000000000000000000..44f1f1e9ebd1eb188289ca9adb8027855c1a23b6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_sobol_direction_numbers.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4859931147d42ce465b8605cb277f957d98b839d03194fdf06579357906d193b +size 589334 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..baa5a703244025f1adfed97be2fba1b161cd5470 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c9b4bfdafe69653e0a9b2b0920b8aa30f07cc3f7d02227674dfd11220a4cc08 +size 572192 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats_pythran.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats_pythran.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d01fad369e94f48734076abc36b859caf377ab0c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_stats_pythran.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9438c2ffea24dc0589959a6ec3332f4600ea0aaaa5aa69c063421d986d53974f +size 182392 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5df13a192211c94558ae01e47e33bcd12d6a4ed0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/_unuran/unuran_wrapper.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:082085896b6fc1806555c84185964bccaf98e896ee0d4d286b7dcd57b3a97a40 +size 1373736 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_continuous.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_continuous.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fdf3d92e6f95c865e3a82bdb35a40c42795faf6a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_continuous.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8521fbd8f7a2a6268332befbbe6a4a20a966e4e4ccc3349215531c07fbb90c5c +size 141969 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..374e2af8df926ebcf62ac5ebfa959b0b87f850a7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_distributions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f157947c662d3a0d78e99a7b5ec28c1094b042169948c987cfa588749d998612 +size 554789 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_hypotests.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_hypotests.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c998805c3ef50fd39eb3ccd0c22d0c2d5479dc93 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_hypotests.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77a79776644195a548032667dd4c573f06234c7d7cc86d33f6480d13f986ffe9 +size 101932 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_morestats.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_morestats.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8d23bef459672280822b9660f5d186fad674c76 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_morestats.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:110bf1bd7681c62cb3ae234deca120e9aa3a4eb15b8d202c49814c2ed6232be3 +size 194763 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_mstats_basic.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_mstats_basic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aabcd66a14c79f3a6262071814fa95527b5ad3ed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_mstats_basic.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a4727a736f4cc58b76172d53f1d8903ad6c34ed89b75e1f43c584d650363eace +size 135409 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7f104c6c6e8ff2ad15a0fede2bf3b4b03e6969c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_multivariate.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c00f7c4e80c2b99f4132c740beb768c4da2d0bc3f8334db9429286e9f6ec32d9 +size 254563 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_resampling.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_resampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f26f28e125b7f6d894068ea8417cc71daef0820 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_resampling.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:89ca3b2e056a537e1fe0229bac22e7027b03803882d3f57c5f24d88fa147faeb +size 116914 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..622440261fe47c0b0fcc2eab7082401ef1b15deb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/__pycache__/test_stats.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfb9d7447d93fc2d3e1c22536b7b36dcb99274aa2c37c762382c162df2d6430f +size 584313 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/jf_skew_t_gamlss_pdf_data.npy b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/jf_skew_t_gamlss_pdf_data.npy new file mode 100644 index 0000000000000000000000000000000000000000..721749bcd853fa5c5efe5a1f5ba6e105658395dc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/jf_skew_t_gamlss_pdf_data.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:254d2dee4a4d547b9331c60243c6fcfcaffd26c8b104d08d4f6045a7645b3bba +size 4064 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy new file mode 100644 index 0000000000000000000000000000000000000000..adda664a7b5442fc0977ddbaa572c864ddd31f08 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-cdf-sample-data.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cf18c1f2d65a232bf2c7121282df31bf2a8be827afafc4ed810ed37457ee898a +size 183728 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-pdf-sample-data.npy b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-pdf-sample-data.npy new file mode 100644 index 0000000000000000000000000000000000000000..6c41166721b891a801cdc6828804c6da7233d625 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-Z1-pdf-sample-data.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fee99512bab4ccc6569b47b924e4b034e1cdbab5624fafc7e120648bd5f7a128 +size 183688 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-loc-scale-sample-data.npy b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-loc-scale-sample-data.npy new file mode 100644 index 0000000000000000000000000000000000000000..0a1460e407521836a9b73a081609af4ccdb6deae --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/levy_stable/stable-loc-scale-sample-data.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f3c719edd5431fb9e7b9ecb6d19e3ca7a9095298bd19f226685b0fca40f0c073 +size 9328 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/rel_breitwigner_pdf_sample_data_ROOT.npy b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/rel_breitwigner_pdf_sample_data_ROOT.npy new file mode 100644 index 0000000000000000000000000000000000000000..80dde74dcda9a23dcdbf9a2f677eb9c98337b0a7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/scipy/stats/tests/data/rel_breitwigner_pdf_sample_data_ROOT.npy @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eef4dc702dd8c6e31c18c74e1f81284c3e9ca2ab50282de39c9ad30b7bb8e76d +size 38624 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentence_transformers/__pycache__/SentenceTransformer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentence_transformers/__pycache__/SentenceTransformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03e4baff908d9435a614ff30f210109367fd8440 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentence_transformers/__pycache__/SentenceTransformer.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7fbaab782f491d82d38a1c070ec1f3b8714643e42365fc10d9ecf9f1e52349b3 +size 115989 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nfkc.bin b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nfkc.bin new file mode 100644 index 0000000000000000000000000000000000000000..c25a930d9afc4b932b39486729c1fe98778f5129 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nfkc.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52f11028ff8a7df3e009d94a8b6a54d4a8a17132efb4ccc1c9a0a41e432bd91e +size 240008 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nfkc_cf.bin b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nfkc_cf.bin new file mode 100644 index 0000000000000000000000000000000000000000..3f658f2d7b17177c66f73918d1530e6001119928 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nfkc_cf.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60833ec11201446659c3549c183b18f024c4007628cc6b3a4e91ae007697b826 +size 247028 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nmt_nfkc.bin b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nmt_nfkc.bin new file mode 100644 index 0000000000000000000000000000000000000000..f4b262a67109d56f77875a21ad496da75d48fe39 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nmt_nfkc.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79372c41389c2b9b29bc171017ab5400e352debd686b02670a42bec709015074 +size 240007 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nmt_nfkc_cf.bin b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nmt_nfkc_cf.bin new file mode 100644 index 0000000000000000000000000000000000000000..f46a7f6a2663cc41c5b17fb03c97654faf2ef376 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sentencepiece/package_data/nmt_nfkc_cf.bin @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:22c292c76f503795f30c85d79d30a7f572fff4f49e00392d2d60f4f93e941a1e +size 247027 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e3585fb7138dfa8a8822bbfbfdc76e8525ab9e1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/__pycache__/typing_extensions.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2a37ec67920a702c61d47cb28e675491babecb31111a93d43a2403031a4b8e30 +size 139485 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13195aebf1c264345f8ade08562c45caba65cbc5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/backports/tarfile/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:48a61ace9819f1a33e64715bcbf9d93d1a1c9a1eddb3490845c836120cb289bd +size 121248 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7d111a68e52c9667441802feeaf4489986682a2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/inflect/__pycache__/__init__.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b76d40e5bb2abaa53eb52f01a882712aaad4f58425680d38c0be15a37cb07ebe +size 113063 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f7f69111e57f21da00d0e925b4fcc535c604f3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/_vendor/more_itertools/__pycache__/more.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f2e73a40778bef12d34bb88ab55a2950651137bb3ae9604a5326f293d59c53dd +size 174188 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..faec70da53465d505f931f9bf3e6959c341d0cb5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/command/__pycache__/easy_install.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d5734c81fe631ff503bfdc527ace099a68174df2ba7a9bc5e3cabf75b0d9510 +size 110531 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6cc4fb23fad5f1121c8600c2110caed63a35b63 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/setuptools/config/_validate_pyproject/__pycache__/fastjsonschema_validations.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e79bf1378a1caddc66841810737577f90758b51e3ab8dcdcceb47d0d9c41faf1 +size 233656 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/_loss/_loss.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/_loss/_loss.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..71f57ad6cf4e00543cb472e7ba06dc5d7be42fa1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/_loss/_loss.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:85edf5fc644d3a311a22e57af3815944665dca3c56d8bc2a23dc8ffecaf79608 +size 2952761 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_linkage.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_linkage.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9dbddfea782241048a2a4aad64712f9c41a68a03 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_linkage.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa45a4969809ce90c73b82e4606bec1815fceffb05f9e2d476da910d8a2f3c9b +size 141232 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_reachability.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_reachability.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4a42994ae3815d7018b2748c3de2094f83211ee1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_reachability.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04c8125f4fc7c8f2b1788aef831e833f8ecad134d4335d0a0835ebd0c05bb6dd +size 248744 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_tree.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_tree.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..662ca04d8dc21fa8df9ce485c7c697b1dd0f00ab --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hdbscan/_tree.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d26d0bc2a376db47cee907c5693d745bc795f280d3564edeb2daa35c1c1a489c +size 266096 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hierarchical_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hierarchical_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4dd16063a822ef55bb17646bb1e130d72b0a1db3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_hierarchical_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b5eea294111063e7479461f147c1d43d0b66bda78730d606dee547f8166441d +size 209008 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_common.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_common.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4262f2987c2efd09235c0fbcb3b171a49b11c16f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_common.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0df5cd36c4a89e25de92f12e99c8b785facccb42f034eb6ff1598facdbb3a958 +size 413297 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_elkan.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_elkan.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ccdc6c9482115cad4c3e33523d22934fb5ff5726 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_elkan.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:081d7ba7e2455b8f6ae5b196189fb304901da1f6eafad136e8ca8d99fd7d3397 +size 388937 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_lloyd.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_lloyd.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4a7355b7a536fb6a9477d3cddbf5b08756f7065c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_lloyd.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:581e4c2aed983a94bdd1c18ca477f3d4831bcaf36bb03541dc3dd9db7270426d +size 269953 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_minibatch.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_minibatch.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9c6b08f1c536a0b9a2d01ff8c369dbc16635f8fa --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/cluster/_k_means_minibatch.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cac80075e9f8c67a17b3224ebc3c7aa54b60ebb4c297255e98271d60e312603b +size 203945 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/compose/tests/__pycache__/test_column_transformer.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/compose/tests/__pycache__/test_column_transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e902ecaa4a45bf7472972d038674d54f95e8ae58 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/compose/tests/__pycache__/test_column_transformer.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e826b04ce0a6f259172ff9e820f1bb58fe18361b96e39c4d1ce0707ece082bdd +size 122172 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/_svmlight_format_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/_svmlight_format_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..de4106b38bf57f43d3bd3c5250bcf1986ae6d092 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/_svmlight_format_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ab87936ca7098192880114df67ed25cb8d8b14b15fddfe25dbbe69730c871c28 +size 455480 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/diabetes_data_raw.csv.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/diabetes_data_raw.csv.gz new file mode 100644 index 0000000000000000000000000000000000000000..fc968bc750f5e995ed4092180e7434b2f780b9cf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/diabetes_data_raw.csv.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a3e94cc7cea00f8a84fa5f6345203913a68efa42df18f87ddf9bead721bfd503 +size 7105 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/diabetes_target.csv.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/diabetes_target.csv.gz new file mode 100644 index 0000000000000000000000000000000000000000..b11a1924f6085214fbedb70b19e689b05750cd11 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/diabetes_target.csv.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8e53f65eb811df43c206f3534bb3af0e5fed213bc37ed6ba36310157d6023803 +size 1050 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/digits.csv.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/digits.csv.gz new file mode 100644 index 0000000000000000000000000000000000000000..b655e3ffa0818ef8048d461352aaa58599baa4e0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/data/digits.csv.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09f66e6debdee2cd2b5ae59e0d6abbb73fc2b0e0185d2e1957e9ebb51e23aa22 +size 57523 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/images/china.jpg b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/images/china.jpg new file mode 100644 index 0000000000000000000000000000000000000000..9e885acfcf3f5a562290d081e204046372238233 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/images/china.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8378025ad2519d649d02e32bd98990db4ab572357d9f09841c2fbfbb4fefad29 +size 196653 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/images/flower.jpg b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/images/flower.jpg new file mode 100644 index 0000000000000000000000000000000000000000..56350635174c5d062428d0128910faa0476b66ee --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/images/flower.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a77f6ec41e353afdf8bdff2ea981b2955535d8d83294f8cfa49cf4e423dd5638 +size 142987 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..951ceb7f7f17c2f89280aac5d5c2da81afd69d43 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jd-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:862e08520a2433a495a3bd3ae9fd9e6c7c540a9c632db29bb8252784cbdad779 +size 1786 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jdf-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jdf-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..2f757032db273b37ef22dc6d4468e675e7bd0915 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jdf-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a966dad58cf5fbc914a374ad5556c0414f5ed962237ed55a379fe96e308d00de +size 889 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jdq-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jdq-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..c9c6d8fb40f9db23fb31349fa8a087c288f5dae9 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/api-v1-jdq-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84a8726d2c3f8bbca79d54d8b191158744b1993146f8f083b111a8ea78536057 +size 145 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..ee6e378589d722771363d186944ed1f0f78c9836 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1/data-v1-dl-1.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfe8945b949770b0da42daf58ce67d1c5fee25cf7b4fd145161837c2abc09429 +size 1841 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jd-1119.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jd-1119.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..8e23c4a4051b50c2a5dbe0b93f4619bbed92b9f3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jd-1119.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c41e5fbb3e59cd4de881ed7c8f88f9b03a750d537ba63581cafde6aafd77adc1 +size 711 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdf-1119.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdf-1119.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..cfe21c720a6a6f97d6857de1d0cf268ab20dda53 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdf-1119.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82f899edc59cb41fdd671b256a228e5e06dfc5e24c92712e75005b251b000865 +size 1108 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..c18f2eec9107a3e1455512f8d92e0289bb6d714d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-dv-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4a5dc36ca9758313978b2a9d79cce763c6f84d5d95f15ac557b3d7482f22ee21 +size 364 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..7b7718d29ecb2075088f54c5f2c5fc0d01d9404b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ec0955788914fa81f698e97a4d1aff773d7a125ed6e769c6271a0b48fc4011d +size 363 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..3265a7d933efe836193228b86e84c6c7a8b45afd --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ef7cbcb58c2edcfea45c058b751faf7783e710462a924e9aacad8d47a7e9f94b +size 1549 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..8f610044b5cc550df4d4ef18cd2131306dba05be --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6931af256195fcdd2e47dd8b0f9edf16fbf03b198e77b70e3dfd9877cdf09515 +size 1190 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jd-1590.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jd-1590.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..93289f3064f0d69614a88c2d71922a7a31a92b4a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jd-1590.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b105adfedc6b6b82f4695ca9bfe232393034cdf79803523f397a6dc5bf824d1 +size 1544 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdf-1590.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdf-1590.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..a273bcdfbb3409d37146d32081c82fbc3e7c6e52 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdf-1590.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:046f5e60564693f0f3b8e382725c8012c3e058647139c24685cec984e40fcd00 +size 1032 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdq-1590.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdq-1590.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..d738f893891ff3d747ee71e709301a481d09430e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdq-1590.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:44b9b0d290a1e339695a431438f84080071c5635161c3977dd17f4c27b00a34a +size 1507 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/data-v1-dl-1595261.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/data-v1-dl-1595261.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..6619336b53b5d71c6bd5c7f2de8e11b88c33ed31 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_1590/data-v1-dl-1595261.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee1dcdf58f2f1072f7dd1b43388969c51bc6cfe776e3e9465ae6a756e5ddb10a +size 1152 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..24caf1bf71f829c85f13b7d2b8d0a94e4d27f1b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a672d435b97a6033dfd1d2a5c823d237ad1865101bd5e403cd99b5be0ba4e03b +size 1363 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..be96cc72487b20a47142fb8c999ce032d73fba2e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c1b8387a7d08014a1c09807ae458ca7666ab8a3c579cbfb189e09c6d7de892a6 +size 866 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..e1f109fd6086eb97a3be2e7533dc658dac0970d5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e900b190795224ff48e46a1c02b10020d4c986ba142880c02c86f0b472ded3c9 +size 309 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..d5feb2e1a57bf4ba4d811dbff391977f38122fed --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ff6225cb98260ca4ebec015a1a2754f2a7b0dbfb4d0f17dcf6727542154e2a10 +size 346 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..08e36a9fb7d7eb1d95b74eebf7c1b870d4a052c1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c46f6c5f221d877de604b906403b20cbdf674f1225bcdbb3e15bd1882a69a471 +size 1501 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..b8a4504ee23ee6713dcfa418b7fe0926fde946e3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d57b2b04cae526306670e3516989dca32c88c155781325ddac42e43dc2322c30 +size 1855 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..83ac698458c7adac8bcda219b26f50cb0b2a2100 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1e6a38d79d8f9e53a2ce11b68b4153062d4e96ec0b368d02b2e64f1b33c51693 +size 551 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..8015288dcd2399e2c86a4050ce81ec49902d6baf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c26dcbe30cfb39161f305b2b3d43a9b50adc8b368d0749568c47106cbdb20897 +size 553 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..b3c915315eff5a266c715e3f99584b16ec06ea8f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:255c16f33ed2967fe100cd8011a7e69f789603724b1ec2ecf91dfeb72067c190 +size 306 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..b3c915315eff5a266c715e3f99584b16ec06ea8f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:255c16f33ed2967fe100cd8011a7e69f789603724b1ec2ecf91dfeb72067c190 +size 306 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..9c2f6f263750517c2b3ca25942cc4a426bc72de0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ef6025425fdfc5f736555ea385252af5bcbf62383615db82489366d4f96a0a7 +size 327 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..9cd17f124ef74920b925490ecc8e415dcd59d225 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9da09e9a6031d060ec416f639a6bf34989e6c88ce641d10621eb906ba1d8c293 +size 99 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..29b93d4214dac84a592173457e4eac04c15bb926 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:35890d08165c804526b48aad462d7ccc09e808bd7975ba604bd612b9608797ac +size 319 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..7bdb62f1628f096b9f91eb2e94ffc413bab4696c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b7ee24adabd4aaed6419b43fe9d3f86d55fcf4bee0f1698ae21d86c2701314e3 +size 2532 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..65982d59860e015a25a42d8bb57f72bf327c9e0b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:066a216679b197cc51946e17ee9a2e28215425991b0ceb7f10988c14f7f3f869 +size 2473 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..faf70da9cea25d998883721d679ca9f0030d9575 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ec4f2d6bc4df3882b08bba01571e0792a56f79e0a922d984897773acd284b426 +size 535 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..24537ca9b1e5187b37136b19898ab370dec315d7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09ef19cfad25c5de487ddbaef3c4d068ca3063777730a288dfd6f5096a0c6f46 +size 1407 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..32bdf94f0f4eac4f936d82476fc75917e92317fe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c63fdf8861761f1ca70509f7d2d169a7cc053988c7b7c09c09a6db6124e208be +size 19485 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..c3454ff8e5a399b14e2033d6122315c4e4b2dbfc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59d1aa6b02d2358c16fa9e4fbeff523a3bd10ebd38c7c371911fa8335e7bdcbf +size 598 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..d9ac42c2bbe778d928f3da1e09e3099962e412ad --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:826bab057a3929f41189bc51afa0a1752695e63ccf20e128ca6129e9e3321fc2 +size 856 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..ed4efacefc3e856c3ad56407f2d195c65c61e4bb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19e6b2a2a8fec5403c146642a4dc2e077d66a3a1ac87e8239bd1dd31c928ab9c +size 315 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..f8f940438f61ac6fbeaa00c46741c80579af46eb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4da63a60163340b6e18922abfe7f1f2a7a7da23da63c269324985d61ffaa6075 +size 318 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..49d394f0c458c02f7d9781445ef870cf8f747e0e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d0f7973193eb35d19e99d1d8bca3c7f3a8b8d0410508af34ad571aee8ec5ab05 +size 913 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..3c0efffc333c6ef0622ed3d3e3c95d3e319fc05f --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2c4226550827ceff3509c67179c473e14385cee206536362e57c5e0dfc7751bf +size 4344 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..b376ef7c9d32dd344e0fff0be5a30ae1e6dda779 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a787772d60fbfcc21a0e96fd81906f03542e0b942d19dcc95dae47498953a4fd +size 323 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..d74f6d6f085d991634610476015839faf034ff2d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d48d9679789d6baf7d0d3c346e3576d7589b663c3640942f9c1dba76e355faaa +size 307 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..336782317369c6fdf4d987c6fd3fdee3309a50e1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:21ed1ecc5d874956e951a9361f251afb2165adda92798c89ca5e2f97ae80dd8f +size 317 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..577840cd46f47e22c75975d855fe21c9b997ee22 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ad0a4a5477605380f8819ce840dbb928a3d084267c512f6cb50d5be2f7c76bc2 +size 85 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..de6ccfccc5f28d446f34b7ffd7fcf83688cb00cf --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:141ba630e039ea44bbaef92a288e2d964fc3aa2ef805a9723b4aac738a26a627 +size 88 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..ed6cf27efa78d576427119132581c3a3fb3b76b3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:88fcdc3a6fed5697f36dc262f69bfffb814767ce336ff28a21def3aac937b08c +size 886 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..d1d26798a46116abdc22f357615f381a19bccf99 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:543d0887312f43d9f65a7e1d08be78a2436369f632d7382b4134cebb525a48a3 +size 3000 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..06446ec67eeede9b6d48f044d8ae402fe11bb90e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02882c6b02c4e068ef2b16f37f33ae3d5e9dd17ca29d01662c6924e16427eb5d +size 437 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..24e0e87d484661242d46a4cf18e2e6695736fa26 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95f0938dfdf1b87d0ffc4d526f2c91e097ef7689480b693970126d908f291030 +size 320 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..adb1b0a58ae958ab00a906b0287f416a4ab48ace --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9c7e5a46554ab6a8121832dc0cd9f7a60f5034cef1a5a7d61346bbd912516b54 +size 1042 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..5d8d5ae4fd5692b26e281928f6a1baad008f2008 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:516e961f519876e5f89b339a0364a08dd64160ac3a4d76d5ec62955bfd6d6ce5 +size 32243 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jd-40966.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jd-40966.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..2b93281d0ded598bd03b1160a1b8a86df61b485c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jd-40966.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:36c63c3ac8c9db59910acbf4c772cd53040ccd0eac0b0452611dd7ad8da50474 +size 1660 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdf-40966.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdf-40966.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..138ffc718b067282922ebeb107b22b8c3af08477 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdf-40966.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8adac8e2f8cbcbfa9677acdd4927a961430465d2c99401832160be455cfaced8 +size 3690 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..7e6491106a294f38733d8dfd6475c1afe42b8848 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-dv-4.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f0c203b4627175cebbf527d81917a499911af915f6f2f46ee7248428a948d603 +size 325 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..ecd8d1b12a547833c2d00ed29be640a12167d082 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdl-dn-miceprotein-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:301396b4a42c814b1a15038ddfcbcf5c8590501231747d0dc2a500b84b2fd0df +size 328 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdq-40966.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdq-40966.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..1d119ce6ec907e4689015911b16bcbfe8552b4e8 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/api-v1-jdq-40966.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3dee83987fffa8ec20e23b3cabc00d42beb7a469af6bd803909998c1687fa634 +size 934 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/data-v1-dl-17928620.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/data-v1-dl-17928620.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..c82d051bccb1b232214b31c73114f4f78749d810 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_40966/data-v1-dl-17928620.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c5fd93ffec7deb63a940fd698534dd7ebb7db349fc183930041cbf17e60e2cc +size 6471 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jd-42074.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jd-42074.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..a0f72505ffd12e41fdd34455ca1dfb6b224160f6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jd-42074.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4fcb215595bb8223321943f0df50f5a5013445bf1819d53d3cb5bfa90d9e79c0 +size 595 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jdf-42074.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jdf-42074.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..89818ff01633a27976f11fd38a70cb1a652dce77 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jdf-42074.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38b74e7f02a61ff55bcfac4d87103d5bffc43febb0c019d9aaa162f8f7693068 +size 272 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jdq-42074.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jdq-42074.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..c152f7e5d9f72441b2fc6aa9f96af8f9ef9fc690 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/api-v1-jdq-42074.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8742a74bd5bc120acd9186c8a8737cb420ed9b009fade00b24e7ce5217797f2c +size 722 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/data-v1-dl-21552912.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/data-v1-dl-21552912.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..010258ddd3f64ab3d63665f106946a34b241d68e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42074/data-v1-dl-21552912.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f623e777c0a36ae6c82fae10a7c2088cb383298ea244595bf8dc95449c9be4c4 +size 2326 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jd-42585.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jd-42585.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..2d2b568ee4692ad61c20ab051723efceb318b816 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jd-42585.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ccbf138e0663895f9cf511136bc6395c153f6238af2eacb6a367e86e15d1a71 +size 1492 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdf-42585.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdf-42585.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..9564b2e437ee328b195f6289af99be51032c64d0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdf-42585.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0985045a454c8186b4e690ebefb6cea1ef7c13292c98d50abda470a0ff3ad425 +size 312 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..a54754b666113a517f58ff509416f461e92636e4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/api-v1-jdq-42585.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3736e7feb7ad30c68675c2c4e48a9fb262e80308c9083b100ddd0339da1fc282 +size 348 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/data-v1-dl-21854866.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/data-v1-dl-21854866.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..2ad2b8b4fd397ee8d61b44fb77b26076f643335d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_42585/data-v1-dl-21854866.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c8d00c6690576a9ec39e1cb77054e13296be0fdebab0fb35a64a0e8627b6e6f3 +size 4519 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jd-561.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jd-561.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..92ba4281fe86b5273792d24afaabb04eef03199d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jd-561.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1d38fdd601b67bb9c6d16152f53ddf166a0cfcfef4fa86438e899bfe449226c +size 1798 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdf-561.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdf-561.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..b2fce3413fd38f4c4f80ef7d6b198b4ac740a90a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdf-561.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:407424fb79cc30b8e9ff90900b3bf29244ac7f3797f278b5be602843f959b4ee +size 425 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..52ae92392967d187709107d1c1bc9709c085b519 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-dv-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0703b0ae20b9ff75087dc601640ee58f1c2ad6768858ea21a245151da9ba8e4c +size 301 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..6bde2de0c6047726f26476a514d27a0d03c7d4b5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdl-dn-cpu-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70d4596ad879547863109da8675c2b789d07df66b526d7ebcbce9616c4c9b94c +size 347 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdq-561.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdq-561.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..911f6823bb1bf0d9de5120e23e902e9a0a39a2bc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/api-v1-jdq-561.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8743b2d93d2c62a82fb47e1fbc002b97e25adcfb5bf1fcb26b58ad0bed15bd48 +size 1074 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/data-v1-dl-52739.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/data-v1-dl-52739.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..225208c948bd5270b3911828bead9d2fd3af3fbb --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_561/data-v1-dl-52739.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e96142b5e00dfec2617b0c22d7192b340ae2c28ec3ffc3a894c5be746b970a59 +size 3303 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..a7ff82cef2a309d55bcae99900bdd51b6bbc675e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jd-61.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a5c7e79aa41ef580838fb9fc1906280f076c47be1741fddd5004ddb500eb57fe +size 898 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..466d7fab3f54e053ae4abc1044c671ac525accc0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdf-61.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:33cbd6ae945ba04969370ab35604e9363c87256393493382b5118a89d59386d6 +size 268 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..76bb2da49d2e31a888153004b5177dc2a0c2f46c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-dv-1.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0bce20aae7fd903796d96d5b3a3677b7058fbc5f3fe0996ee9d491e4ee23d132 +size 293 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..c628aa1d9076067123d34c4c392a3a215dae524b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdl-dn-iris-l-2-s-act-.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a9f4b9317997df63ed8d2bb073a3906344c0e0be017fd384eaec36ced8b94bae +size 330 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..285c038aae89afa2eb0c334cdf28a9d0f6e2cb32 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/api-v1-jdq-61.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:424cd47c12a51c7bb8d8169fac80fb5601f152bd78468b241d4b115bf7d22f20 +size 1121 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..25bb1bc7760d28c156677d8d257421b3805299c1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_61/data-v1-dl-61.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afe4736924606638984e573235191025d419c545d31dc8874c96b72f5ec5db73 +size 2342 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jd-62.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jd-62.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..da14f86aac08c072962c2eecf6fe18cf319c5718 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jd-62.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7ef3551ad47d48023c5a1f1cf077047a9a4b95544bb91d4a86097f8b574f8d07 +size 656 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jdf-62.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jdf-62.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..22da3f227189e339ed4d2b3861866ded65d999a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jdf-62.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:489b177126cb7f335cb220709233b946d3a0ad71d38bba6d48b79187146e585a +size 817 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jdq-62.json.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jdq-62.json.gz new file mode 100644 index 0000000000000000000000000000000000000000..c8c1985e0bf13abce1abad45a5d872ccbcd44478 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/api-v1-jdq-62.json.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:278a52a52d569f07d14c6a7877b104762c77daac429fb1fd9817a0378d6ec634 +size 805 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/data-v1-dl-52352.arff.gz b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/data-v1-dl-52352.arff.gz new file mode 100644 index 0000000000000000000000000000000000000000..b3ce4b7991c2223af6097adb8d1f553088d1ece0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/datasets/tests/data/openml/id_62/data-v1-dl-52352.arff.gz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fb5830c82112f62a400c82ac1f1b5eb61c29c0a7cc72ba56d2aeff0fae8a60f9 +size 1625 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_cdnmf_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_cdnmf_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2cb812bedf0b7fd3571778083ef4bb66cdc92bf2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_cdnmf_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7587312bb548c58bf556e5307eb0ce6c2f5988630e2b0930792dd6fc3a58c420 +size 117744 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_online_lda_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_online_lda_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a6cd633fec2fcb8955e895bcf77b2d8413c368a6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/decomposition/_online_lda_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1c39c3e81e773d3efbc8e22521f54dbb70e8afe421d930d83f9b10c38299f8df +size 178992 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/__pycache__/_forest.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/__pycache__/_forest.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0863c442473851bea6ca57e1e3b176753b33fd3a --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/__pycache__/_forest.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1fddbbeb858eed1e6f7a43e82bf1e35cf463dc7200eaab16e5358f10cd1ea5e4 +size 117662 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_gradient_boosting.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_gradient_boosting.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1753d10c0689a804dad4b61ec4cbb5ccbbd2dac7 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_gradient_boosting.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3761fb512b3a7611bbd37dddc122257e89e088f376b30f80d90e719f9c78b2b5 +size 130904 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_gradient_boosting.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_gradient_boosting.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..829528fa6b0412454ce88d048f9d2b643e170d77 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_gradient_boosting.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:030c282361da31357101d01be91e619fb8f7ec10d1b8491663790de010a09fad +size 100977 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_predictor.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_predictor.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..7bdc00c80cdb7991712fdb493abe5e9f783aedcc --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/_predictor.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:268dccabf728b959728509bd87f975bf29bfbeba7f785fdb58b770a65f0b47aa +size 142105 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/histogram.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/histogram.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..ba3e44639c0d8438ac3fb987728d946b45810345 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/histogram.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa7d59e177acfa69ce77c17aed9800908a658aaab9af076fefd47a3cce491877 +size 236753 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..545afa2779a6680395cda0cfd630b012404bb408 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/ensemble/_hist_gradient_boosting/splitting.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf33f6e8a37c0c42d889cbaf633d4abd3ee2afbc6e931f55cfd8022443416cf4 +size 265457 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_coordinate_descent.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_coordinate_descent.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9226b3a1f35ed79bab6bf1234244e8c4e5802fbe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_coordinate_descent.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:501d8ba647bbe79b747fc1a4eb096bc6bcec0af445434a7001c10775f312aa35 +size 114413 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_ridge.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_ridge.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7af5d9a6ec46a0cd54967cb04f469a1d36581b35 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/__pycache__/_ridge.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:768b3f2d464f57d5fe8f7c5713a991b332c61974e6407315612a932c89a6f594 +size 109698 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_cd_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_cd_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..71aef3cbde5068e096f1aa3c64bd57cd4224efe2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_cd_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:31b79e23fa17b9ec371892a5f99efef4ed0a487834433c42d1cdde213dac03d9 +size 374848 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sag_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sag_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..044585524ba2e2fa60f428a24debc9bc92690033 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sag_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:58dbd126f9206d9435b2e5364cc045262dbb9d07df85654f351b931b53953400 +size 163024 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sgd_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sgd_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2039e74a0935b110fa2f7ae3680c61256f5a398c --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/_sgd_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aaf711313432c1dea0795ef6f6ed317372140b0b3d601b66317c64b4989a3a42 +size 242144 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/tests/__pycache__/test_logistic.cpython-312.pyc b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/tests/__pycache__/test_logistic.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2d9df8b7a100def69a7fe600ff10b3606d03dc2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/linear_model/tests/__pycache__/test_logistic.cpython-312.pyc @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d7fbd4bcb9015dedca0e95dc10af6b423a70f09f17b7537c1360a0c7a1aff11f +size 101897 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/manifold/_barnes_hut_tsne.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/manifold/_barnes_hut_tsne.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..3b24961f0e20c9a29c591a42ec67eff19f839c02 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/manifold/_barnes_hut_tsne.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0daa44bec4514b1f56250b6fae05b9d450bb0ab8f0a1c10716db10ea6cc17f30 +size 134169 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_dist_metrics.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_dist_metrics.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..fd54b68c916c14dbd5010cc6aefa05f445ecf148 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_dist_metrics.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:437300c91719a4b49cd6111b794f78f8ef8b50609157640ec351e26473795e54 +size 605688 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_pairwise_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_pairwise_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..94130863bf03d1ea29bc1c715d6091a27ae47d2e --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/metrics/_pairwise_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b4531c228cee52a3d307c5c637a83ac22aa204056206c837914f0621ebe28251 +size 183529 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_ball_tree.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_ball_tree.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..086924990e44413534406f3a074082af8847ebb3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_ball_tree.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b2071e3bfb47fda38f641bfbb192b4a84d363d1ab583d3f6fad6427bb1720002 +size 636192 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_kd_tree.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_kd_tree.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..35d1e9c66136ca9981dff527bedcbd45699836f4 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_kd_tree.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d5221c9f8a10bf235776d0e6d37ecd1c6e468ebdae9a6f3a59bb8ffca6f2b95c +size 638120 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_quad_tree.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_quad_tree.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..741eb2c25d0ae78a348ab8882db975bddd5fa57d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/neighbors/_quad_tree.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b989c0ca8ef4a66450f6818036103eb352759f8cf15302f8f5a77055d699832c +size 186944 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9c27fa6420db8b8504857756273e535e8683224d --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_csr_polynomial_expansion.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:28b97b43879e1c41eca5e6e551a5de99aa5acdbf123e561da0408174efeb9e63 +size 363784 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..71439d4012c0453a472cc039d6b7ee1fbf9e4440 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/preprocessing/_target_encoder_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:97f9c11d2346ff01acd008286059dd7604c2a3d2defd54a8846b7568e9ed5652 +size 385160 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_liblinear.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_liblinear.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..a112563f8a8732d8fd929e8bc23a55feebf8314b --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_liblinear.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aac48bbd17c6794d37dea1c4e7e987d7c8211da0a8926f3a4217b874b392d4ab +size 190344 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..387e7e127a2abcb5f12e8790d1b737ae193bb840 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e342d9fcbe612a5c63f598de97d25aa9c1662b888267539c92d4192b7712140c +size 430624 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm_sparse.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm_sparse.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..5390e610e6a48d59222b6da22d662bf989cc2eb6 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/svm/_libsvm_sparse.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96884e4db7f61c7c9160c2b70d7663ae961f82f00b1313af5a263eaea799eaf4 +size 380672 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_criterion.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_criterion.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9d1896d8beb6d97eb6f40f0a7f66bb9769c886f5 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_criterion.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7b71ad3c50d79e5db975c04a92cb168c59848bc881e9b9d3218fc7bd7d7eb01f +size 211400 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_partitioner.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_partitioner.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..9ac8b89ea227b90b34ae3e6b78d04001d2f2a051 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_partitioner.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:200a6b6931b3ddad0142953e7f337e468db8d9985d363aa78818a8abba6dd94d +size 181776 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_splitter.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_splitter.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..76082eb1ad41db0ac9358816d57ad06f80d5dbe2 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_splitter.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a192283452e2fa0fa3b4686a9b3a00fc5158aa6c4a2a524cee5799f0ea117bbf +size 156664 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_tree.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_tree.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..874abf1c9c23706c32acc3643125be6a01e9a571 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_tree.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3cf727128d07a98e4b596f8efbb064ff4df4abf9e6a5d64630ef5b50061e7883 +size 462256 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_utils.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_utils.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..1c1e3f523ba4a4d51d071200badb910996a73a43 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/tree/_utils.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d22b18b6fffd848622efabba863710c48a94b41ff0115fa642a358f01e738bcd +size 147496 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_cython_blas.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_cython_blas.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..289d1a965c4708a14bbeb93f7d812a450646bbca --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_cython_blas.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a551ef7a4399f28858fa935275b253016157b5392c7ac0f4148b2ca3689ae86a +size 345928 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_fast_dict.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_fast_dict.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..81ce070f92f990437b8515a67185c153d747fe24 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_fast_dict.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd8171fb86cf66df0e9fd10914ae76dae98a51abba377d2574157c873ff7d601 +size 169480 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_isfinite.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_isfinite.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8c2ac373d27f6b9ad67617a3aa4df7c9fab457a1 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_isfinite.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd5620a853fbb71d75eaa77d2ca747da669a59f224f66a60605501af64943619 +size 118048 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_random.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_random.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..8f5bfd54c1610568e0f11b80cfa4b38be15cc079 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_random.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bb5824d3845d84b28a921486100c62bfdce9746de61bb24c7c2b5f63453ffd6 +size 240848 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_seq_dataset.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_seq_dataset.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..c435df6b726ca51b1ee8aa5bc1327f30eab169f3 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_seq_dataset.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0ef1ee201309eaef355c57eb71108c07b55c644e2eeed2f9a64f4a8f1f9ed022 +size 219744 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_typedefs.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_typedefs.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..6fe3ef13cc981893ae4a12d056ec2b3e1d2f0a71 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_typedefs.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e10b798dbe3fd54182f2121d4d5c40fe3b537363f66c35ada072b34e744dc20 +size 152424 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_vector_sentinel.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_vector_sentinel.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2c15d283cce2ec45c002f0b756287bebe0f26de0 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/_vector_sentinel.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f76bf651987098ec34372701ab94a2df0c4089025a48968ae5f4a49a960e8782 +size 163056 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/arrayfuncs.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/arrayfuncs.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..e0da00381cb191b7959926b0caed3eb5c85dfdbe --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/arrayfuncs.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd5310b8bda80ff78ac86bb433299a34c8a52ead31fd6aa9d1c44ba9764decbe +size 188664 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/murmurhash.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/murmurhash.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..545759c6a4baef0d0a0602f9c71371ac4abb0341 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/murmurhash.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:177150a6d49ad6ab6ca19d03bc85566e3c43dcada60a8e8508651e0353ee46e9 +size 142464 diff --git a/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/sparsefuncs_fast.cpython-312-x86_64-linux-gnu.so b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/sparsefuncs_fast.cpython-312-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..db82cd7ffee83a25bc11f993aa002bddee79d712 --- /dev/null +++ b/platform/dbops/archive/databases_old/data/home/x/.local/lib/python3.12/site-packages/sklearn/utils/sparsefuncs_fast.cpython-312-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f67478cad0005e8c3e0aec0c216bc524342442f6260b49716b1d5cf28c78807d +size 712144